Debian Codegraph @

Contrib/System/Source/System.c

raw
1 // System.cpp : Defines the entry point for the DLL application.
2 //
3
4 // Unicode support by Jim Park & Olivier Marcoux
5
6 #include "stdafx.h"
7 #include "Plugin.h"
8 #include "Buffers.h"
9 #include "System.h"
10 #ifndef __GNUC__
11 #define _DECL_DLLMAIN /* enable prototypes for DllMain and _CRT_INIT */
12 #include <process.h>
13 #include <crtdbg.h>
14 #else
15 #define _RPT0(type, msg)
16 #define _CRT_WARN 0
17 #endif /* __GNUC__ */
18 #include <objbase.h>
19
20
21
22 // Parse Section Type
23 #define PST_PROC 0
24 #define PST_PARAMS 1
25 #define PST_RETURN 2
26 #define PST_OPTIONS 3
27
28 #define PCD_NONE 0
29 #define PCD_PROC 1
30 #define PCD_PARAMS 2
31 #define PCD_DONE 3 // Just Continue
32
33 const int PARAMSIZEBYTYPE_PTR = (4==sizeof(void*)) ? 1 : 2;
34 const int ParamSizeByType[8] = {
35 0, // PAT_VOID (Size will be equal to 1) //BUGBUG64?
36 1, // PAT_INT
37 2, // PAT_LONG
38 sizeof(void*) / 4, // PAT_STRING //BUGBUG64?
39 sizeof(void*) / 4, // PAT_WSTRING //BUGBUG64?
40 sizeof(void*) / 4, // PAT_GUID //BUGBUG64?
41 0, // PAT_CALLBACK (Size will be equal to 1) //BUGBUG64?
42 0 // PAT_REGMEM //BUGBUG64?
43 };
44
45 // The size of the base type when used in a struct with the '&' syntax (multiply by (Option - PAO_ARRBASE) to get the real size)
46 static const int ByteSizeByType[8] = {
47 1, // PAT_VOID
48 1, // PAT_INT
49 1, // PAT_LONG
50 1, // PAT_STRING
51 2, // PAT_WSTRING (Special case for &wN notation: N is a number of WCHAR, not a number of bytes)
52 1, // PAT_GUID (Must stay 1 for compatibility with the old '*(&g16,i)i.s' syntax)
53 1, // PAT_CALLBACK
54 1 // PAT_REGMEM
55 };
56
57 int LastStackPlace;
58 int LastStackReal;
59 DWORD LastError;
60 volatile SystemProc *LastProc;
61 int CallbackIndex;
62 CallbackThunk* g_CallbackThunkListHead;
63 HINSTANCE g_hInstance;
64
65 // Return to callback caller with stack restore
66 char retexpr[4]; //BUGBUG64?
67 HANDLE retaddr;
68
69 static TCHAR *MakeResultStr(SystemProc *proc, TCHAR *buf)
70 {
71 if (proc->ProcResult == PR_CALLBACK)
72 {
73 INT_PTR id = proc->CallbackIndex;
74 #ifdef POPT_SYNTAX2
75 if (proc->Options & POPT_SYNTAX2)
76 id = (INT_PTR) GetAssociatedSysProcFromCallbackThunkPtr(proc->Proc);
77 #endif
78 wsprintf(buf, sizeof(void*) > 4 ? _T("callback%Id") : _T("callback%d"), id); // "%d" must match format used by system_pushintptr() in Get() because script will StrCmp!
79 }
80 else
81 {
82 const TCHAR *resstr = _T("error");
83 if (proc->ProcResult == PR_OK)
84 resstr = _T("ok");
85 lstrcpy(buf, resstr);
86 }
87 return buf;
88 }
89
90 TCHAR *AllocResultStr(SystemProc *proc)
91 {
92 return MakeResultStr(proc, AllocString());
93 }
94
95 #ifdef SYSTEM_LOG_DEBUG
96
97 #ifndef COUNTOF
98 #define COUNTOF(a) ( sizeof(a) / sizeof(a[0]) )
99 #endif
100
101 // System log debugging turned on
102 #define SYSTEM_LOG_ADD(a) do{ register int _len = lstrlen(syslogbuf); lstrcpyn(syslogbuf + _len, a, COUNTOF(syslogbuf) - _len); }while(0)
103 #define SYSTEM_LOG_POST do{ SYSTEM_LOG_ADD(_T("\n")); WriteToLog(syslogbuf); *syslogbuf = 0; }while(0)
104
105 HANDLE logfile = NULL;
106 TCHAR syslogbuf[4096] = _T("");
107 int logop = 0;
108
109 void WriteToLog(TCHAR *buffer)
110 {
111 DWORD written;
112 TCHAR timebuffer[128];
113
114 GetTickCount();
115
116 if (logfile == NULL) return;
117
118 SetFilePointer(logfile, 0, 0, FILE_END);
119
120 if (-1 != logop)
121 {
122 wsprintf(timebuffer, _T("%04d %04d.%03d "), (++logop)%10000,
123 (GetTickCount() / 1000) % 10000, GetTickCount() % 1000);
124
125 #ifdef _UNICODE
126 #ifdef _RPTW0
127 _RPTW0(_CRT_WARN, timebuffer);
128 _RPTW0(_CRT_WARN, buffer);
129 #endif
130 #else
131 _RPT0(_CRT_WARN, timebuffer);
132 _RPT0(_CRT_WARN, buffer);
133 #endif
134
135 WriteFile(logfile, timebuffer, lstrlen(timebuffer)*sizeof(TCHAR), &written, NULL);
136 }
137 WriteFile(logfile, buffer, lstrlen(buffer)*sizeof(TCHAR), &written, NULL);
138 // FlushFileBuffers(logfile);
139 }
140
141 PLUGINFUNCTION(Debug)
142 {
143 TCHAR *o1;
144 o1 = system_popstring();
145
146 if (logfile == NULL)
147 if (lstrlen(o1) > 0)
148 {
149 SYSTEMTIME t;
150 TCHAR buffer[1024], buftime[1024], bufdate[1024];
151
152 // Init debugging
153 logfile = CreateFile(o1, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
154 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
155
156 SetFilePointer(logfile, 0, 0, FILE_END);
157
158 logop = 0;
159 #ifdef _UNICODE
160 { // write Unicode Byte-Order Mark
161 DWORD written;
162 unsigned short bom = 0xfeff;
163 WriteFile(logfile, &bom, 2, &written, NULL);
164 }
165 #endif
166 GetLocalTime(&t);
167 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, LOCALE_NOUSEROVERRIDE, &t, NULL, buftime, 1024);
168 GetDateFormat(LOCALE_SYSTEM_DEFAULT, LOCALE_NOUSEROVERRIDE, &t, NULL, bufdate, 1024);
169 wsprintf(buffer, _T("System, %s %s [build %hs %hs]\n"), buftime, bufdate, __TIME__, __DATE__);
170 WriteToLog(buffer);
171 } else ;
172 else
173 if (lstrlen(o1) > 0)
174 {
175 // Log in to log file
176 int orglogop;
177 WriteToLog(o1);
178 orglogop = logop, logop = -1;
179 WriteToLog(_T("\n"));
180 logop = orglogop;
181 } else
182 {
183 // Stop debugging
184 WriteToLog(_T("Debug stopped.\n\n\n"));
185 CloseHandle(logfile);
186 logfile = NULL;
187 }
188 if (o1) GlobalFree(o1);
189 } PLUGINFUNCTIONEND
190
191 #else
192
193 // System log debugging turned off
194 #define SYSTEM_EVENT(a)
195 #define SYSTEM_LOG_ADD(a)
196 #define SYSTEM_LOG_POST
197
198 #endif
199
200 /**
201 * This function is useful for Unicode support. Since the Windows
202 * GetProcAddress function always takes a char*, this function wraps
203 * the windows call and does the appropriate translation when
204 * appropriate.
205 *
206 * @param dllHandle Handle to the DLL loaded by LoadLibraryEx.
207 * @param funcName The name of the function to get the address of.
208 * @return The pointer to the function. Null if failure.
209 */
210 void * NSISGetProcAddress(HMODULE dllHandle, TCHAR* funcName)
211 {
212 #ifdef _UNICODE
213 char* ansiName = NULL;
214 int len;
215 void* funcPtr;
216
217 len = WideCharToMultiByte(CP_ACP, 0, funcName, -1, ansiName, 0, NULL, NULL);
218 ansiName = (char*) GlobalAlloc(GPTR, len);
219 WideCharToMultiByte(CP_ACP, 0, funcName, -1, ansiName, len, NULL, NULL);
220 funcPtr = GetProcAddress(dllHandle, ansiName);
221 GlobalFree(ansiName);
222 return funcPtr;
223 #else
224 return GetProcAddress(dllHandle, funcName);
225 #endif
226 }
227
228 PLUGINFUNCTIONSHORT(Free)
229 {
230 HANDLE memtofree = (HANDLE)popintptr();
231
232 if (g_CallbackThunkListHead)
233 {
234 CallbackThunk *pCb=g_CallbackThunkListHead,*pPrev=NULL;
235 do
236 {
237 if (GetAssociatedSysProcFromCallbackThunkPtr(pCb) == (SystemProc*)memtofree)
238 {
239 if (pPrev)
240 pPrev->pNext=pCb->pNext;
241 else
242 g_CallbackThunkListHead=pCb->pNext;
243
244 --(CallbackIndex);
245 VirtualFree(pCb,0,MEM_RELEASE);
246 break;
247 }
248 pPrev=pCb;
249 pCb=pCb->pNext;
250 }
251 while( pCb != NULL );
252 }
253
254 GlobalFree(memtofree);
255 }
256 PLUGINFUNCTIONEND
257
258 PLUGINFUNCTION(Get)
259 {
260 SystemProc *proc = PrepareProc(FALSE);
261 if (proc == NULL)
262 {
263 system_pushstring(_T("error"));
264 return;
265 }
266
267 SYSTEM_LOG_ADD(_T("Get "));
268 SYSTEM_LOG_ADD(proc->DllName);
269 SYSTEM_LOG_ADD(_T("::"));
270 SYSTEM_LOG_ADD(proc->ProcName);
271 //SYSTEM_LOG_ADD(_T("\n"));
272 SYSTEM_LOG_POST;
273 if (proc->Options & POPT_ALWRETURN)
274 {
275 // Always return flag set -> return separate proc and result
276 system_pushintptr((INT_PTR) proc);
277 GlobalFree(system_pushstring(AllocResultStr(proc)));
278 }
279 else
280 {
281 if (proc->ProcResult != PR_OK)
282 {
283 // No always return flag and error result - return result
284 GlobalFree(system_pushstring(AllocResultStr(proc)));
285 // If proc is permanent?
286 if (!(proc->Options & POPT_PERMANENT))
287 GlobalFree((HGLOBAL) proc); // No, free it
288 }
289 else // Ok result, return proc
290 system_pushintptr((INT_PTR) proc);
291 }
292 } PLUGINFUNCTIONEND
293
294
295 #ifdef SYSTEM_ARM64
296 /*
297 TODO: CallProc not implemented.
298 Fake the behavior of the System plugin for the LoadImage API function etc. so MUI works.
299 BUGBUG: MUI is leaking DeleteObject
300 */
301 SystemProc* CallProc(SystemProc *proc)
302 {
303 INT_PTR ret, *place;
304 if (!lstrcmp(proc->ProcName, sizeof(TCHAR) > 1 ? _T("LoadImageW") : _T("LoadImageA")))
305 {
306 ret = (INT_PTR) LoadImage((HINSTANCE)proc->Params[1].Value, (LPCTSTR)proc->Params[2].Value, (UINT)proc->Params[3].Value, (int)proc->Params[4].Value, (int)proc->Params[5].Value, (UINT)proc->Params[6].Value);
307 LastError = GetLastError();
308 }
309 else if (!lstrcmp(proc->ProcName, _T("GetClientRect")))
310 ret = GetClientRect((HWND)proc->Params[1].Value, (RECT*)proc->Params[2].Value);
311 else if (!lstrcmp(proc->ProcName, _T("GetWindowRect")))
312 ret = GetWindowRect((HWND)proc->Params[1].Value, (RECT*)proc->Params[2].Value);
313 else if (!lstrcmp(proc->ProcName, _T("MapWindowPoints")))
314 ret = MapWindowPoints((HWND)proc->Params[1].Value, (HWND)proc->Params[2].Value, (POINT*)proc->Params[3].Value, (UINT)proc->Params[4].Value);
315 else if (!lstrcmp(proc->ProcName, _T("SetWindowPos")))
316 ret = SetWindowPos((HWND)proc->Params[1].Value, (HWND)proc->Params[2].Value, (int)proc->Params[3].Value, (int)proc->Params[4].Value, (int)proc->Params[5].Value, (int)proc->Params[6].Value, (UINT)proc->Params[7].Value);
317 else if (!lstrcmp(proc->ProcName, _T("GetWindowLong")))
318 ret = GetWindowLong((HWND)proc->Params[1].Value, (int)proc->Params[2].Value);
319 else if (!lstrcmp(proc->ProcName, _T("SetWindowLong")))
320 ret = SetWindowLong((HWND)proc->Params[1].Value, (int)proc->Params[2].Value, (LONG)proc->Params[3].Value);
321 else if (!lstrcmp(proc->ProcName, _T("GetWindowText")))
322 ret = GetWindowText((HWND)proc->Params[1].Value, (LPTSTR)proc->Params[2].Value, (int)proc->Params[3].Value);
323 else if (!lstrcmp(proc->ProcName, _T("SendMessageA")))
324 ret = SendMessageA((HWND)proc->Params[1].Value, (UINT)proc->Params[2].Value, (WPARAM)proc->Params[3].Value, (LPARAM)proc->Params[4].Value);
325 else if (!lstrcmp(proc->ProcName, _T("SendMessage")) || !lstrcmp(proc->ProcName, _T("SendMessageW")))
326 ret = SendMessageW((HWND)proc->Params[1].Value, (UINT)proc->Params[2].Value, (WPARAM)proc->Params[3].Value, (LPARAM)proc->Params[4].Value);
327 else if (!lstrcmp(proc->ProcName, _T("GetVersionEx"))) // For winver
328 ret = GetVersionEx((OSVERSIONINFO*)proc->Params[1].Value), LastError = GetLastError();
329 else if (!lstrcmp(proc->ProcName, _T("GetNativeSystemInfo")))
330 GetNativeSystemInfo((SYSTEM_INFO*)(ret = proc->Params[1].Value));
331 else if (!lstrcmp(proc->ProcName, _T("CharNextW"))) // For x64
332 ret = (INT_PTR) CharNextW((LPWSTR)proc->Params[1].Value);
333 else if (!lstrcmp(proc->ProcName, _T("GetCurrentProcess"))) // For x64
334 ret = (INT_PTR) GetCurrentProcess();
335 else if (!lstrcmp(proc->ProcName, _T("IsWow64Process"))) // For x64
336 {
337 if (!(ret = (INT_PTR) GetProcAddress(LoadLibrary(_T("KERNEL32")), "IsWow64Process"))) goto fail;
338 ret = ((BOOL(WINAPI*)(HANDLE,BOOL*))ret)((HANDLE)proc->Params[1].Value, (BOOL*)proc->Params[2].Value);
339 }
340 else if (!lstrcmp(proc->ProcName, _T("IsWow64Process2"))) // For x64
341 {
342 if (!(ret = (INT_PTR) GetProcAddress(LoadLibrary(_T("KERNEL32")), "IsWow64Process2"))) goto fail;
343 ret = ((BOOL(WINAPI*)(HANDLE,USHORT*,USHORT*))ret)((HANDLE)proc->Params[1].Value, (USHORT*)proc->Params[2].Value, (USHORT*)proc->Params[3].Value);
344 }
345 else if (!lstrcmp(proc->ProcName, _T("Wow64EnableWow64FsRedirection"))) // For x64
346 {
347 if (!(ret = (INT_PTR) GetProcAddress(LoadLibrary(_T("KERNEL32")), "Wow64EnableWow64FsRedirection"))) goto fail;
348 ret = ((BYTE(WINAPI*)(BYTE))ret)((BYTE)proc->Params[1].Value);
349 }
350 else fail:
351 proc->ProcResult = PR_ERROR, ret = 0, LastError = ERROR_INVALID_FUNCTION;
352 place = (INT_PTR*) proc->Params[0].Value;
353 if (!ParamIsPointer(proc->Params[0])) place = (INT_PTR*) &(proc->Params[0].Value);
354 if (place) *place = ret;
355 return proc;
356 }
357 #endif //~ SYSTEM_ARM64
358 #ifdef _WIN64
359 /*
360 BUGBUG: TODO: CallBack support not implemented!
361 */
362 SystemProc* CallBack(SystemProc *proc)
363 {
364 proc->ProcResult = PR_ERROR;
365 return proc;
366 }
367 #endif //~ _WIN64
368
369
370 PLUGINFUNCTION(Call)
371 {
372 // Prepare input
373 SystemProc *proc = PrepareProc(TRUE);
374 if (proc == NULL) return;
375
376 SYSTEM_LOG_ADD(_T("Call "));
377 SYSTEM_LOG_ADD(proc->DllName);
378 SYSTEM_LOG_ADD(_T("::"));
379 SYSTEM_LOG_ADD(proc->ProcName);
380 //SYSTEM_LOG_ADD(_T("\n"));
381 SYSTEM_LOG_POST;
382 if (proc->ProcResult != PR_CALLBACK) ParamAllocate(proc);
383 ParamsIn(proc);
384
385 // Make the call
386 if (proc->ProcResult != PR_ERROR)
387 {
388 switch (proc->ProcType)
389 {
390 case PT_NOTHING:
391 if (proc->ProcResult == PR_CALLBACK)
392 proc = CallBack(proc);
393 break;
394 case PT_PROC:
395 case PT_VTABLEPROC:
396 proc = CallProc(proc); break;
397 case PT_STRUCT:
398 CallStruct(proc); break;
399 }
400 }
401
402 // Process output
403 if (proc->Options & POPT_ALWRETURN)
404 {
405 // Always return flag set - return separate return and result
406 ParamsOut(proc);
407 GlobalFree(system_pushstring(AllocResultStr(proc)));
408 }
409 else
410 {
411 if (proc->ProcResult != PR_OK)
412 {
413 ProcParameter pp = proc->Params[0]; // Save old return param
414
415 // Return result instead of return value
416 TCHAR resstr[50];
417 proc->Params[0].Value = (INT_PTR) MakeResultStr(proc, resstr);
418 proc->Params[0].Type = PAT_TSTRING;
419 proc->Params[0].allocatedBlock = NULL;
420
421 ParamsOut(proc); // Return all params
422 proc->Params[0] = pp; // Restore old return param
423 }
424 else
425 ParamsOut(proc);
426 }
427
428 if (proc->ProcResult != PR_CALLBACK)
429 {
430 ParamsDeAllocate(proc);
431
432 // if not callback - check for unload library option
433 if ((proc->Options & POPT_UNLOAD) && proc->ProcType == PT_PROC && proc->Dll)
434 FreeLibrary(proc->Dll); // and unload it :)
435
436 // In case of POPT_ERROR - first pop will be proc error
437 if ((proc->Options & POPT_ERROR) != 0) system_pushint(LastError);
438 }
439
440 // If proc is permanent?
441 if (!(proc->Options & POPT_PERMANENT)) GlobalFree((HGLOBAL) proc); // No, free it
442 } PLUGINFUNCTIONEND
443
444 PLUGINFUNCTIONSHORT(Int64Op)
445 {
446 __int64 i1, i2 = 0, i3, i4;
447 TCHAR *op;
448 #ifndef _WIN64
449 TCHAR buf[25], *o1, *o2;
450 #endif
451
452 // Get parameters: <num1> <op> [num2]
453 #ifdef _WIN64
454 i1 = system_popintptr();
455 #else
456 o1 = system_popstring(), i1 = myatoi64(o1);
457 #endif
458 op = system_popstring();
459 if ((*op != _T('~')) && (*op != _T('!')))
460 {
461 #ifdef _WIN64
462 i2 = system_popintptr();
463 #else
464 o2 = system_popstring(), i2 = myatoi64(o2), GlobalFree(o2);
465 #endif
466 }
467
468 // Operation
469 switch (*op)
470 {
471 case _T('+'): i1 += i2; break;
472 case _T('-'): i1 -= i2; break;
473 case _T('*'): i1 *= i2; break;
474 case _T('/'):
475 case _T('%'):
476 // It's unclear, but in this case compiler will use DivMod routine
477 // instead of two separate Div and Mod routines.
478 if (i2 == 0) { i3 = 0; i4 = i1; }
479 else {i3 = i1 / i2; i4 = i1 % i2; }
480 if (*op == _T('/')) i1 = i3; else i1 = i4;
481 break;
482 case _T('|'): if (op[1] == _T('|')) i1 = i1 || i2; else i1 |= i2; break;
483 case _T('&'): if (op[1] == _T('&')) i1 = i1 && i2; else i1 &= i2; break;
484 case _T('^'): i1 ^= i2; break;
485 case _T('~'): i1 = ~i1; break;
486 case _T('!'): i1 = !i1; break;
487 case _T('<'): if (op[1] == _T('<')) i1 = i1 << i2; else i1 = i1 < i2; break;
488 case _T('>'): if (op[1] == _T('>')) i1 = op[2] == _T('>') ? (UINT64)i1 >> (UINT64)i2 : i1 >> i2; else i1 = i1 > i2; break;
489 case _T('='): i1 = (i1 == i2); break;
490 }
491
492 // Output and freedom
493 #ifdef _WIN64
494 system_pushintptr(i1);
495 #else
496 myitoa64(i1, buf), system_pushstring(buf), GlobalFree(o1);
497 #endif
498 GlobalFree(op);
499 } PLUGINFUNCTIONEND
500
501 __int64 GetIntFromString(TCHAR **p)
502 {
503 TCHAR buffer[128], *b = buffer;
504 (*p)++; // First character should be skipped
505 while (((**p >= _T('a')) && (**p <= _T('f'))) || ((**p >= _T('A')) && (**p <= _T('F'))) || ((**p >= _T('0')) && (**p <= _T('9'))) || (**p == _T('X')) || (**p == _T('-')) || (**p == _T('x')) || (**p == _T('|'))) *(b++) = *((*p)++);
506 *b = 0;
507 (*p)--; // We should point at last digit
508 return myatoi64(buffer);
509 }
510
511 SystemProc *PrepareProc(BOOL NeedForCall)
512 {
513 int SectionType = PST_PROC, // First section is always proc spec
514 ProcType = PT_NOTHING, // Default proc spec
515 ChangesDone = 0,
516 ParamIndex = 0,
517 temp = 0, temp2, temp3;
518 INT_PTR temp4;
519 BOOL param_defined = FALSE;
520 SystemProc *proc = NULL;
521 TCHAR *ibuf, *ib, *sbuf, *cbuf, *cb;
522 unsigned int UsedTString = 0, aligntype, inpathq = 0;
523 #ifdef POPT_SYNTAX2
524 const UINT alignflag = PAT_ALIGNFLAG;
525 #else
526 const UINT alignflag = 0;
527 #endif
528
529 #ifdef __GNUC__
530 temp3 = 0; // "warning: 'temp3' may be used uninitialized in this function": temp3 is set to 0 when we start parsing a new parameter
531 #endif
532
533 // Retrieve proc specs
534 cb = (cbuf = AllocString()); // Current String buffer
535 sbuf = AllocString(); // Safe String buffer
536 ib = ibuf = system_popstring(); // Input string
537
538 // Parse the string
539 while (SectionType != -1)
540 {
541 // Check for Section Change
542 BOOL changed = TRUE;
543 ChangesDone = SectionType;
544
545 if (SectionType != PST_PROC && proc == NULL)
546 // no proc after PST_PROC is done means something is wrong with
547 // the call syntax and we'll get a crash because everything needs
548 // proc from here on.
549 break;
550
551 switch (*ib)
552 {
553 case 0x0:
554 SectionType = -1;
555 break;
556 case _T('#'): // "...#" redefines proc unless preceded by ":", then it's an ordinal (dll::#123)
557 if ((ib <= ibuf || *(ib-1) != _T(':') || PST_PROC != SectionType) && !inpathq)
558 SectionType = PST_PROC, ProcType = PT_NOTHING;
559 else
560 changed = FALSE;
561 break;
562 case _T('('):
563 if (inpathq)
564 changed = FALSE;
565 else
566 {
567 SectionType = PST_PARAMS;
568 // fake-real parameter: for COM interfaces first param is Interface Pointer
569 ParamIndex = ((ProcType == PT_VTABLEPROC)?(2):(1));
570 temp3 = temp = 0;
571 param_defined = FALSE;
572 }
573 break;
574 case _T(')'):
575 if (inpathq)
576 changed = FALSE;
577 else
578 {
579 SectionType = PST_RETURN;
580 temp3 = temp = 0;
581 }
582 break;
583 case _T('?'):
584 SectionType = PST_OPTIONS; temp = 1;
585 break;
586 default:
587 changed = FALSE;
588 }
589
590 // Check for changes
591 if (changed)
592 {
593 switch (ChangesDone)
594 {
595 case PST_PROC:
596 *cb = 0;
597 // Adopt proc
598 if (proc == NULL)
599 {
600 proc = (SystemProc *) GlobalAlloc(GPTR, sizeof(SystemProc));
601 proc->Options = 0;
602 proc->ParamCount = 0;
603 }
604 // Default parameters
605 *proc->DllName = 0;
606 *proc->ProcName = 0;
607 proc->Dll = NULL;
608 proc->Proc = NULL;
609 proc->ProcType = ProcType;
610 proc->ProcResult = PR_OK;
611
612 // Section changed and previous section was Proc
613 switch (ProcType)
614 {
615 case PT_NOTHING:
616 // Is it previous proc or just unknown proc?
617 if (cb != cbuf)
618 {
619 // Previous proc (for clear up)
620 SystemProc *pr = NULL;
621
622 if (proc != NULL) GlobalFree(proc);
623 // Get already defined proc
624 proc = (SystemProc *) StrToIntPtr(cbuf);
625 if (!proc) break;
626
627 // Find the last clone at proc queue
628 while (proc && (proc->Clone != NULL)) proc = (pr = proc)->Clone;
629
630 // Clear parents record for child callback proc
631 if (pr != NULL) pr->Clone = NULL;
632
633 // Never Redefine?
634 if (proc->Options & POPT_NEVERREDEF)
635 {
636 proc = GlobalCopy(proc); // Create new proc as copy
637 proc->Options &= ~(POPT_NEVERREDEF|POPT_PERMANENT); // NeverRedef options is never inherited
638 }
639 else
640 proc->Options |= POPT_PERMANENT; // Proc is old -> permanent
641 }
642 break;
643 case PT_PROC:
644 case PT_VTABLEPROC:
645 lstrcpy(proc->DllName, sbuf);
646 case PT_STRUCT:
647 lstrcpy(proc->ProcName, cbuf);
648 break;
649 }
650 break;
651 case PST_PARAMS:
652 if (param_defined)
653 proc->ParamCount = ParamIndex;
654 else
655 // not simply zero because of vtable calls
656 proc->ParamCount = ParamIndex - 1;
657 case PST_RETURN:
658 case PST_OPTIONS:
659 break;
660 }
661 ib++;
662 cb = cbuf;
663 continue;
664 }
665
666 // Parse the section
667 ChangesDone = PCD_NONE;
668 switch (SectionType)
669 {
670 // Proc sections parser
671 case PST_PROC: parse_next_proc_section_char:
672 switch (*ib)
673 {
674 case _T('\"'):
675 ib++; // Skip '\"'
676 if (inpathq)
677 {
678 inpathq = 0;
679 goto parse_next_proc_section_char;
680 }
681 else
682 {
683 inpathq++;
684 }
685 break;
686 case _T(':'):
687 case _T('-'):
688 // Is it '::'
689 if ((*(ib) == _T('-')) && (*(ib+1) == _T('>')))
690 {
691 ProcType = PT_VTABLEPROC;
692 }
693 else
694 {
695 if ((*(ib+1) != _T(':')) || (*(ib) == _T('-'))) break;
696 ProcType = PT_PROC;
697 }
698 ib++; // Skip next ':'
699
700 if (cb > cbuf)
701 {
702 *cb = 0;
703 lstrcpy(sbuf, cbuf);
704 }
705 else
706 *sbuf = 0; // No dll - system proc
707
708 // Ok
709 ChangesDone = PCD_DONE;
710 break;
711 case _T('*'):
712 // Structure definition
713 ProcType = PT_STRUCT;
714 ChangesDone = PCD_DONE;
715 break;
716 }
717 break;
718
719 // Params and return sections parser
720 case PST_RETURN:
721 ParamIndex = 0; // Uses the same logic as PST_PARAMS section
722 case PST_PARAMS:
723 temp2 = -1; temp4 = 0; // Our type placeholder
724 aligntype = FALSE;
725 switch (*ib)
726 {
727 case _T(' '):
728 break;
729 case _T('_'): // No param cutting specifier
730 if (proc->ParamCount > ParamIndex) ParamIndex = proc->ParamCount;
731 temp3 = temp = 0; // Clear parameter options
732 if (proc->ParamCount != ((ProcType == PT_VTABLEPROC) ? 1 : 0))
733 {
734 // only define params if the last count wasn't zero
735 // this prevents erroneous param count for:
736 // 'user32::CloseClipboard()(_)'
737 // for vtable calls, param count should not be one
738 param_defined = TRUE;
739 }
740 break;
741 case _T(','): // Next param
742 temp3 = temp = 0; // Clear parameter options
743 ParamIndex++;
744 param_defined = TRUE;
745 break;
746 case _T('&'):
747 temp = PAO_ARRBASE; break; // Special parameter option
748 case _T('*'):
749 temp = PAO_PTRFLAG; break; // Pointer parameter option
750
751 // Types
752 case _T('@'): temp2 = PAT_REGMEM; break;
753 case _T('V'): // No extra alignment for void padding
754 case _T('v'): temp2 = PAT_VOID; break;
755 case 'B': aligntype += alignflag ? 1 : 0;
756 case 'b': temp2 = PAT_INT, temp = sizeof(BYTE) + 1; break; // INT8/BYTE/BOOLEAN alias for &1
757 case 'H': aligntype += alignflag ? 1 : 0;
758 case 'h': temp2 = PAT_INT, temp = sizeof(WORD) + 1; break; // INT16/WORD/SHORT alias for &2 with 'h' AKA printf type length specifier
759 #ifndef _WIN64
760 case _T('P'):
761 #endif
762 case _T('I'): aligntype += alignflag ? 1 : 0;
763 #ifndef _WIN64
764 case _T('p'):
765 #endif
766 case _T('i'): temp2 = PAT_INT; break; // INT32
767 #ifdef _WIN64
768 case _T('P'):
769 #endif
770 case _T('L'): aligntype += alignflag ? 1 : 0;
771 #ifdef _WIN64
772 case _T('p'):
773 #endif
774 case _T('l'): temp2 = PAT_LONG; break; // INT64
775 case _T('M'): // 1 byte, no extra alignment
776 case _T('m'): temp2 = PAT_STRING; break;
777 case _T('T'): aligntype += (alignflag && sizeof(TCHAR) > 1) ? 1 : 0;
778 case _T('t'): temp2 = PAT_TSTRING, ++UsedTString; break;
779 case _T('G'): aligntype += alignflag ? 1 : 0;
780 case _T('g'): temp2 = PAT_GUID; break;
781 case _T('W'): aligntype += alignflag ? 1 : 0;
782 case _T('w'): temp2 = PAT_WSTRING; break;
783 case _T('K'): aligntype += alignflag ? 1 : 0;
784 case _T('k'): temp2 = PAT_CALLBACK; break;
785
786 // Input output specifiers
787 case _T('.'): temp3++; break; // skip specifier
788
789 case _T('R'):
790 temp4 = ((INT_PTR) GetIntFromString(&ib))+1;
791 if (temp4 < 11) temp4 += 10;
792 break;
793 case _T('r'): temp4 = ((INT_PTR) GetIntFromString(&ib))+1; break; // Register
794
795 case _T('-'):
796 case _T('0'): case _T('1'): case _T('2'): case _T('3'): case _T('4'):
797 case _T('5'): case _T('6'): case _T('7'): case _T('8'): case _T('9'):
798 // Numeric inline
799 if (temp3 == 0)
800 {
801 ib--;
802 // It's stupid, I know, but I'm too lazy to do another thing
803 myitoa64(GetIntFromString(&(ib)),(TCHAR *)(temp4 = (INT_PTR) AllocString()));
804 }
805 break;
806
807 case _T('\"'): case _T('\''): case _T('`'):
808 // Character inline
809 {
810 TCHAR start = *ib;
811 cb = cbuf;
812 // copy inline
813 while (!((*(++ib) == start) && (*(ib+1) != start)) && (*ib))
814 {
815 if ((*ib) == start) ++ib;
816 *(cb++) = *(ib);
817 }
818 // finish and save
819 *cb = 0;
820 temp4 = (INT_PTR) AllocStr(cbuf);
821 }
822 break;
823
824 case _T('s'):
825 case _T('S'): temp4 = -1; break; // Stack
826 case _T('c'):
827 case _T('C'): temp4 = INST_CMDLINE+1; break;
828 case _T('d'):
829 case _T('D'): temp4 = INST_INSTDIR+1; break;
830 case _T('o'):
831 case _T('O'): temp4 = INST_OUTDIR+1; break;
832 case _T('e'):
833 case _T('E'): temp4 = INST_EXEDIR+1; break;
834 case _T('a'):
835 case _T('A'): temp4 = INST_LANG+1; break;
836 }
837
838 // Param type changed?
839 if (temp2 != -1)
840 {
841 const int psbt = ParamSizeByType[temp2];
842 param_defined = TRUE;
843 proc->Params[ParamIndex].Type = temp2 | (alignflag && aligntype ? alignflag : 0);
844 proc->Params[ParamIndex].Size = // Pointer sized or from type
845 ParamOptionIsPointer(temp) ? (PARAMSIZEBYTYPE_PTR) : ((psbt>0) ? (psbt) : (1)); //BUGBUG64: Is it safe to fallback to 1 for CALLBACK?
846 if (temp == PAO_ARRBASE) temp =
847 PAO_ARRBASE + ((int) GetIntFromString(&ib)); // Read '&' array count specification
848 proc->Params[ParamIndex].Option = temp;
849 proc->Params[ParamIndex].Value = 0;
850 proc->Params[ParamIndex].Input = IOT_NONE;
851 proc->Params[ParamIndex].Output = IOT_NONE;
852 }
853
854 // Param source/dest changed?
855 if (temp4 != 0)
856 {
857 param_defined = TRUE;
858 if (temp3 == 0)
859 {
860 // it may contain previous inline input
861 if (!((proc->Params[ParamIndex].Input > -1) && (proc->Params[ParamIndex].Input <= __INST_LAST)))
862 GlobalFree((HGLOBAL) proc->Params[ParamIndex].Input);
863 proc->Params[ParamIndex].Input = temp4;
864 }
865 if (temp3 == 1)
866 proc->Params[ParamIndex].Output = (int) temp4; // Note: As long as we never assign a pointer to temp4 when parsing a destination the cast to int is OK.
867 // Next parameter is output or something else
868 temp3++;
869 }
870
871 ChangesDone = PCD_DONE;
872 break;
873
874 // Options sections parser
875 case PST_OPTIONS:
876 temp2 = 0;
877 switch (*ib)
878 {
879 case _T(' '): break;
880 case _T('!'): temp = -temp; break;
881 case _T('c'):
882 #ifndef _WIN64
883 temp2 = POPT_CDECL; // Only x86 cares, just eat the option for everything else
884 #endif
885 break;
886 case _T('r'): temp2 = POPT_ALWRETURN; break;
887 case _T('n'): temp2 = POPT_NEVERREDEF; break;
888 case _T('s'): temp2 = POPT_GENSTACK; break;
889 case _T('e'): temp2 = POPT_ERROR; break;
890 case _T('u'): temp2 = POPT_UNLOAD; break;
891 #ifdef POPT_SYNTAX2
892 case _T('2'): temp2 = POPT_SYNTAX2; break;
893 #endif
894 }
895
896 // New Options
897 if (temp2 != 0)
898 {
899 if (temp == 1) proc->Options |= temp2; else proc->Options &= ~temp2;
900 // Back to default (turn on nothing) state
901 temp = 1; temp2 = 0;
902 }
903
904 ChangesDone = PCD_DONE;
905 break;
906 }
907
908 // Nothing done, just copy char to buffer
909 if (ChangesDone == PCD_NONE) *(cb++) = *(ib);
910 // Something done, buffer = ""
911 else cb = cbuf;
912
913 // Increase input pointer
914 ib++;
915 }
916
917 GlobalFree(ibuf);
918 GlobalFree(cbuf);
919 GlobalFree(sbuf);
920
921 // Ok, the final step: check proc for existence
922 if (proc != NULL && proc->Proc == NULL)
923 {
924 switch (proc->ProcType)
925 {
926 case PT_NOTHING: break;
927 case PT_VTABLEPROC:
928 {
929 // Use direct system proc address
930 INT_PTR addr;
931
932 proc->Dll = (HMODULE) StrToIntPtr(proc->DllName);
933
934 if (proc->Dll == 0)
935 {
936 proc->ProcResult = PR_ERROR;
937 break;
938 }
939
940 addr = (INT_PTR) proc->Dll;
941
942 // fake-real parameter: for COM interfaces first param is Interface Pointer
943 proc->Params[1].Output = IOT_NONE;
944 proc->Params[1].Input = (INT_PTR) AllocStr(proc->DllName);
945 proc->Params[1].Size = PARAMSIZEBYTYPE_PTR;
946 proc->Params[1].Type = PAT_PTR;
947 proc->Params[1].Option = 0;
948
949 // addr - pointer to interface vtable
950 addr = *((INT_PTR *)addr);
951 // now addr contains the pointer to first item at VTABLE
952 // add the index of proc
953 addr = addr + (INT_PTR)(myatoi64(proc->ProcName)*sizeof(void*));
954 proc->Proc = *((HANDLE*)addr);
955 }
956 break;
957 case PT_PROC:
958 if (*proc->DllName == 0)
959 {
960 // Use direct system proc address
961 if ((proc->Proc = (HANDLE) StrToIntPtr(proc->ProcName)) == 0)
962 proc->ProcResult = PR_ERROR;
963 } else
964 {
965 // Get DLL address
966 if ((proc->Dll = GetModuleHandle(proc->DllName)) == NULL)
967 if ((proc->Dll = LoadLibrary(proc->DllName)) == NULL)
968 {
969 proc->ProcResult = PR_ERROR;
970 break;
971 }
972
973 // Get proc address
974 proc->Proc = NSISGetProcAddress(proc->Dll, proc->ProcName);
975 if (!proc->Proc && *proc->ProcName == _T('#'))
976 {
977 int ordinal = myatoi(proc->ProcName+1);
978 if (ordinal && IS_INTRESOURCE(ordinal))
979 proc->Proc = GetProcAddress(proc->Dll, MAKEINTRESOURCEA(ordinal));
980 }
981 if (UsedTString || !proc->Proc)
982 {
983 FARPROC tproc;
984 TCHAR*ProcName = proc->ProcName; // This buffer has room for us to party on
985 unsigned int cch = lstrlen(ProcName);
986 #ifdef _UNICODE
987 STRSET2CH(ProcName+cch, _T('W'), _T('\0'));
988 #else
989 STRSET2CH(ProcName+cch, _T('A'), _T('\0'));
990 #endif
991 tproc = NSISGetProcAddress(proc->Dll, ProcName);
992 if (tproc)
993 proc->Proc = tproc;
994 else
995 if (!proc->Proc) proc->ProcResult = PR_ERROR;
996 }
997 }
998 break;
999 case PT_STRUCT:
1000 if (*(proc->ProcName) != 0) proc->Proc = (HANDLE) StrToIntPtr(proc->ProcName);
1001 break;
1002 }
1003 }
1004
1005 return proc;
1006 }
1007
1008 void ParamAllocate(SystemProc *proc)
1009 {
1010 UINT i, c;
1011 for (i = 0, c = proc->ParamCount; i <= c; i++)
1012 if (!proc->Params[i].Value && ParamIsPointer(proc->Params[i]))
1013 proc->Params[i].Value = (INT_PTR) GlobalAlloc(GPTR, ParamSizeByType[GetParamType(proc->Params[i])] * 4);
1014 }
1015
1016 void ParamsIn(SystemProc *proc)
1017 {
1018 int i;
1019 HGLOBAL* place;
1020 TCHAR *realbuf;
1021 #ifndef _UNICODE
1022 LPWSTR wstr;
1023 #endif
1024 #if !defined(_WIN64) && defined(C_ASSERT)
1025 C_ASSERT(FIELD_OFFSET(ProcParameter, Value) + sizeof(int) == FIELD_OFFSET(ProcParameter, _value)); // Make sure PAT_LONG writes to the correct places
1026 #endif
1027 i = (proc->ParamCount > 0)?(1):(0);
1028 while (TRUE)
1029 {
1030 ProcParameter *par = &proc->Params[i];
1031 UINT partype;
1032 // Step 1: retrieve value
1033 if ((par->Input == IOT_NONE) || (par->Input == IOT_INLINE))
1034 realbuf = AllocStr(_T(""));
1035 else if (par->Input == IOT_STACK) realbuf = system_popstring();
1036 else if ((par->Input > 0) && (par->Input <= __INST_LAST))
1037 realbuf = system_getuservariable((int)par->Input - 1);
1038 else
1039 {
1040 // Inline input, will be freed as realbuf
1041 realbuf = (TCHAR*) par->Input;
1042 par->Input = IOT_INLINE;
1043 }
1044
1045 // Retrieve pointer to place
1046 place = ParamIsPointer(*par) ? (HGLOBAL*) par->Value : (HGLOBAL*) &(par->Value);
1047
1048 // by default no blocks are allocated
1049 par->allocatedBlock = NULL;
1050
1051 // Step 2: place it
1052 switch (partype = GetParamType(*par))
1053 {
1054 case PAT_VOID:
1055 par->Value = 0;
1056 break;
1057 case PAT_INT:
1058 *(int*)place = myatoi(realbuf);
1059 break;
1060 case PAT_LONG:
1061 *(__int64*)place = myatoi64(realbuf);
1062 break;
1063 case PAT_TSTRING:
1064 /* if (par->Input == IOT_NONE)
1065 *((int*) place) = (int) NULL;
1066 else*/
1067 *place = par->allocatedBlock = AllocStr(realbuf);
1068 break;
1069 #ifdef _UNICODE
1070 case PAT_STRING:
1071 *place = par->allocatedBlock = GlobalAlloc(GPTR, g_stringsize);
1072 WideCharToMultiByte(CP_ACP, 0, realbuf, g_stringsize, *(LPSTR*)place, g_stringsize, NULL, NULL);
1073 break;
1074 case PAT_GUID:
1075 *place = par->allocatedBlock = GlobalAlloc(GPTR, 16);
1076 CLSIDFromString(realbuf, *(LPCLSID*)place);
1077 break;
1078 #else
1079 case PAT_WSTRING:
1080 case PAT_GUID:
1081 wstr = (LPWSTR) GlobalAlloc(GPTR, g_stringsize*sizeof(WCHAR));
1082 MultiByteToWideChar(CP_ACP, 0, realbuf, g_stringsize, wstr, g_stringsize);
1083 if (partype == PAT_GUID)
1084 {
1085 *place = par->allocatedBlock = GlobalAlloc(GPTR, 16);
1086 CLSIDFromString(wstr, *(LPCLSID*)place);
1087 GlobalFree((HGLOBAL) wstr);
1088 } else
1089 *place = par->allocatedBlock = (HGLOBAL)wstr;
1090 break;
1091 #endif
1092 case PAT_CALLBACK:
1093 // Generate new or use old callback
1094 if (realbuf[0])
1095 par->Value = (INT_PTR) CreateCallback((SystemProc*) StrToIntPtr(realbuf));
1096 break;
1097 case PAT_REGMEM:
1098 {
1099 LPTSTR straddr = system_getuservariableptr(par->Input - 1);
1100 par->Value = (INT_PTR) straddr;
1101 par->Value += sizeof(void*) > 4 ? sizeof(_T("-9223372036854775807###")) : sizeof(_T("-2147483647")); // "###" for sizeof(void*) alignment
1102 IntPtrToStr(par->Value, straddr);
1103 }
1104 break;
1105 }
1106 GlobalFree(realbuf);
1107
1108 #ifdef SYSTEM_LOG_DEBUG
1109 {
1110 TCHAR buf[666];
1111 UINT32 hi32 = 0;
1112 #ifndef _WIN64
1113 hi32 = par->_value;
1114 #endif
1115 wsprintf(buf, _T("\t\t\tParam In %d:\tType=%#x Value=") SYSFMT_HEXPTR _T(" hi32=0x%08X"), i,
1116 par->Type, par->Value, hi32);
1117 SYSTEM_LOG_ADD(buf);
1118 SYSTEM_LOG_POST;
1119 }
1120 #endif
1121
1122 if (i == 0) break;
1123 if (i == proc->ParamCount) i = 0; else i++;
1124 }
1125 }
1126
1127 void ParamsDeAllocate(SystemProc *proc)
1128 {
1129 int i;
1130 for (i = proc->ParamCount; i >= 0; i--)
1131 if (proc->Params[i].Value && ParamIsPointer(proc->Params[i]))
1132 {
1133 GlobalFree((HGLOBAL) (proc->Params[i].Value));
1134 proc->Params[i].Value = 0;
1135 }
1136 }
1137
1138 #define GetSpecialParamTypeSize(par) ( (((par).Option)-PAO_ARRBASE) * ByteSizeByType[GetParamType(par)] ) // Option must be > PAO_ARRBASE!
1139 static const int g_intmask[4] = { 0xFFFFFFFF, 0x000000FF, 0x0000FFFF, 0x00FFFFFF };
1140 #define GetMaskedInt32Value(val, size) ( (val) & g_intmask[((UINT)(size) < 4) ? (size) : (0)] )
1141 #define GetSpecialParamInt32Value(par, size) GetMaskedInt32Value((par).Value, (size))
1142
1143 void ParamsOut(SystemProc *proc)
1144 {
1145 INT_PTR *place;
1146 LPWSTR wstr;
1147 int i, partype, intval, typsiz;
1148 TCHAR *realbuf = AllocString();
1149
1150 i = proc->ParamCount;
1151 do
1152 {
1153 // Retrieve pointer to place
1154 if (ParamIsPointer(proc->Params[i]))
1155 place = (INT_PTR*) proc->Params[i].Value;
1156 else
1157 place = (INT_PTR*) &(proc->Params[i].Value);
1158
1159 // Step 1: retrieve value
1160 switch (partype = GetParamType(proc->Params[i]))
1161 {
1162 case PAT_VOID:
1163 *realbuf = _T('\0');
1164 break;
1165 #ifndef _WIN64
1166 case PAT_REGMEM:
1167 #endif
1168 case PAT_INT:
1169 intval = (int)(*((INT_PTR*) place));
1170 if (proc->Params[i].Option > 0) // Note: We don't handle '*' pointers, "*h" and "*b" are not supported, use "*i" even on smaller types
1171 {
1172 typsiz = GetSpecialParamTypeSize(proc->Params[i]);
1173 intval = GetMaskedInt32Value(intval, typsiz);
1174 }
1175 wsprintf(realbuf, _T("%d"), intval);
1176 break;
1177 #ifdef _WIN64
1178 case PAT_REGMEM:
1179 #endif
1180 case PAT_LONG:
1181 myitoa64(*((__int64*) place), realbuf);
1182 break;
1183 case PAT_STRING:
1184 #ifdef _UNICODE
1185 MultiByteToWideChar(CP_ACP, 0, *((char**) place), g_stringsize, realbuf, g_stringsize-1);
1186 realbuf[g_stringsize-1] = _T('\0'); // make sure we have a null terminator
1187 #else
1188 lstrcpyn(realbuf,*((TCHAR**) place), g_stringsize); // note: lstrcpyn always includes a null terminator (unlike strncpy)
1189 #endif
1190 break;
1191 case PAT_GUID:
1192 #ifdef _UNICODE
1193 StringFromGUID2(*((REFGUID*)place), realbuf, g_stringsize);
1194 #else
1195 {
1196 WCHAR guidstrbuf[39];
1197 int guidcch = StringFromGUID2(*((REFGUID*)place), guidstrbuf, 39);
1198 WideCharToMultiByte(CP_ACP, 0, guidstrbuf, guidcch, realbuf, g_stringsize, NULL, NULL);
1199 }
1200 #endif
1201 break;
1202 case PAT_WSTRING:
1203 wstr = *((LPWSTR*)place);
1204 #ifdef _UNICODE
1205 lstrcpyn(realbuf, wstr, g_stringsize); // note: lstrcpyn always include a null terminator (unlike strncpy)
1206 #else
1207 WideCharToMultiByte(CP_ACP, 0, wstr, g_stringsize, realbuf, g_stringsize-1, NULL, NULL);
1208 realbuf[g_stringsize-1] = _T('\0'); // make sure we have a null terminator
1209 #endif
1210 break;
1211 case PAT_CALLBACK:
1212 wsprintf(realbuf, sizeof(void*) > 4 ? _T("%Id") : _T("%d"), proc->Params[i].Value);
1213 break;
1214 }
1215
1216 // memory cleanup
1217 if ((proc->Params[i].allocatedBlock != NULL)
1218 && ((proc->ProcType != PT_STRUCT) || ParamIsArray(proc->Params[i]))
1219 )
1220 GlobalFree(proc->Params[i].allocatedBlock);
1221
1222 SYSTEM_LOG_ADD(_T("\t\t\tParam Out("));
1223 // Step 2: place it
1224 if (proc->Params[i].Output == IOT_NONE)
1225 SYSTEM_LOG_ADD(_T("none"));
1226 else if (proc->Params[i].Output == IOT_STACK)
1227 {
1228 SYSTEM_LOG_ADD(_T("stack"));
1229 system_pushstring(realbuf);
1230 }
1231 else if (proc->Params[i].Output > 0)
1232 {
1233 SYSTEM_LOG_ADD(_T("var"));
1234 system_setuservariable(proc->Params[i].Output - 1, realbuf);
1235 }
1236 else
1237 SYSTEM_LOG_ADD(_T("?BUG?"));
1238
1239 #ifdef SYSTEM_LOG_DEBUG
1240 {
1241 TCHAR dbgbuf[99];
1242 wsprintf(dbgbuf, _T(")\t%d:\tType=%#x Optn=%d Size=%d Data="),
1243 i, proc->Params[i].Type, proc->Params[i].Option, proc->Params[i].Size);
1244 SYSTEM_LOG_ADD(dbgbuf);
1245 SYSTEM_LOG_ADD(realbuf);
1246 SYSTEM_LOG_POST;
1247 }
1248 #endif
1249
1250 i--;
1251 }
1252 while (i >= 0);
1253
1254 GlobalFree(realbuf);
1255 }
1256
1257 HANDLE CreateCallback(SystemProc *cbproc)
1258 {
1259 #if defined(SYSTEM_AMD64) || defined(SYSTEM_ARM64)
1260 return BUGBUG64(HANDLE) NULL;
1261 #else
1262 char *mem;
1263
1264 if (cbproc->Proc == NULL)
1265 {
1266 // Set callback index
1267 cbproc->CallbackIndex = ++(CallbackIndex);
1268 cbproc->Options |= POPT_PERMANENT;
1269
1270 mem = (char *) (cbproc->Proc = VirtualAlloc(NULL, sizeof(CallbackThunk), MEM_COMMIT, PAGE_EXECUTE_READWRITE));
1271
1272 ((CallbackThunk*)mem)->pNext=g_CallbackThunkListHead;
1273 g_CallbackThunkListHead=(CallbackThunk*)mem;
1274
1275 #ifdef SYSTEM_X86
1276 *(mem++) = (char) 0xB8; // Mov eax, const
1277 *((int *)mem) = (int) cbproc;
1278 mem += sizeof(int);
1279 *(mem++) = (char) 0xe9; // Jmp relative
1280 *((int *)mem) = (int) RealCallBack;
1281 *((int *)mem) -= ((int) mem) + 4;
1282 #else
1283 #error "Asm thunk not implemented for this architecture!"
1284 #endif
1285
1286 }
1287
1288 // Return proc address
1289 return cbproc->Proc;
1290 #endif
1291 }
1292
1293 #ifdef POPT_SYNTAX2
1294 static UINT GetStructParamAlignment(const ProcParameter *par)
1295 {
1296 int partype = GetParamType(*par), isarr = ParamIsArray(*par);
1297 // &l is used to get the final struct size "*(p, &l.r0)"
1298 // but it also allows you to write the struct size to the struct as a int<8|16|32|64> "*(p, &l4)"
1299 // so we can't stop that with: "if ((par->Type & PAT_ALIGNFLAG) && (!isarr || partype != PAT_LONG))"
1300 if (par->Type & PAT_ALIGNFLAG)
1301 {
1302 if ((partype == PAT_STRING) | (partype == PAT_WSTRING)) return ByteSizeByType[partype];
1303 if (partype == PAT_GUID) return 16;
1304 return !isarr ? (par->Size * 4) : GetSpecialParamTypeSize(*par);
1305 }
1306 return 0;
1307 }
1308 #endif
1309
1310 void CallStruct(SystemProc *proc)
1311 {
1312 BOOL ssflag; // "&l" struct size syntax
1313 UINT i, paramcount = proc->ParamCount, structsize = 0, size = 0, partype;
1314 char *st, *ptr;
1315 #ifdef POPT_SYNTAX2
1316 BOOL tryalign = proc->Options & POPT_SYNTAX2;
1317 #endif
1318
1319 SYSTEM_LOG_ADD(_T("\t\tStruct..."));
1320
1321 // Calculate the structure size
1322 for (i = 1; i <= paramcount; i++)
1323 {
1324 partype = GetParamType(proc->Params[i]);
1325 // Emulate g as &g16
1326 // (Changing ByteSizeByType would break compatibility with '*(&g16,i)i.s')
1327 if (PAT_GUID==partype && ParamIsSimple(proc->Params[i]))
1328 proc->Params[i].Option = PAO_ARRBASE + 16;
1329
1330 if (!ParamIsArray(proc->Params[i]))
1331 size = proc->Params[i].Size * 4;
1332 else
1333 size = GetParamArrayTypeSize(proc->Params[i]);
1334
1335 #ifdef POPT_SYNTAX2
1336 if (tryalign)
1337 structsize = SYS_ALIGNON(structsize, GetStructParamAlignment(&proc->Params[i]));
1338 #endif
1339 structsize += size;
1340 }
1341
1342 // Struct exists?
1343 if (proc->Proc == NULL) // No. Allocate struct memory
1344 proc->Proc = (HANDLE) GlobalAlloc(GPTR, structsize);
1345 else if (structsize == 0) // In case of zero size defined structure use mapped size
1346 structsize = (int) GlobalSize((HGLOBAL) proc->Proc);
1347
1348 #ifdef SYSTEM_LOG_DEBUG
1349 {
1350 TCHAR dbgbuf[99];
1351 wsprintf(dbgbuf, _T("\t(%u bytes)"), structsize);
1352 SYSTEM_LOG_ADD(dbgbuf);
1353 }
1354 #endif
1355
1356 // Pointer to current data
1357 st = (char*) proc->Proc;
1358
1359 for (i = 1; i <= paramcount; i++)
1360 {
1361 ssflag = FALSE;
1362 partype = GetParamType(proc->Params[i]);
1363
1364 // Normal or special block?
1365 if (!ParamIsArray(proc->Params[i]))
1366 {
1367 // Normal
1368 size = proc->Params[i].Size * 4;
1369 ptr = (char*) &(proc->Params[i].Value);
1370 }
1371 else
1372 {
1373 // Special
1374 size = GetParamArrayTypeSize(proc->Params[i]);
1375 ptr = NULL;
1376 switch (partype)
1377 {
1378 case PAT_VOID:
1379 break;
1380 case PAT_LONG:
1381 // real structure size
1382 proc->Params[i].Value = structsize;
1383 #ifndef _WIN64
1384 proc->Params[i]._value = 0;
1385 #endif
1386 ssflag = TRUE; // System::Call '*(...,&l.r0)'
1387 // [[fallthrough]]
1388 case PAT_INT:
1389 proc->Params[i].Value = GetSpecialParamInt32Value(proc->Params[i], size); // clears unused value bits
1390 // pointer
1391 ptr = (char*) &(proc->Params[i].Value);
1392 break;
1393
1394 case PAT_STRING:
1395 case PAT_WSTRING:
1396 case PAT_GUID:
1397 // Jim Park: Pointer for memcopy, so keep as char*
1398 ptr = (char*) proc->Params[i].Value;
1399 break;
1400 }
1401 }
1402
1403 // Process them!
1404 if (ptr != NULL)
1405 {
1406 #ifdef POPT_SYNTAX2
1407 if (tryalign)
1408 st = (char*) SYS_ALIGNON((INT_PTR) st, GetStructParamAlignment(&proc->Params[i]));
1409 #endif
1410
1411 // Input
1412 if ((proc->Params[i].Input != IOT_NONE) || (ssflag))
1413 copymem(st, ptr, size);
1414
1415 // Output
1416 if (proc->Params[i].Output != IOT_NONE)
1417 copymem(ptr, st, size);
1418 }
1419
1420 // Skip to next data block
1421 st += size;
1422 }
1423
1424 SYSTEM_LOG_POST;
1425
1426 // Proc virtual return - pointer to memory struct
1427 proc->Params[0].Value = (INT_PTR) proc->Proc;
1428 }
1429
1430 /*
1431 Use of system _DllMainCRTStartup to avoid endless recursion for the debug
1432 report macro _RPT0.
1433
1434 The system _DllMainCRTStartup initializes the C runtime environment.
1435 In particular the value for _osplatform is initialized. In the function
1436 _get_winmajor called in the execution of the _RPT0 macro an assertion
1437 failure is raised if _osplatform is not set. The assertion is reported by
1438 the same means as used for the _RPT0 macro. This leads to an endless recursion.
1439 */
1440
1441 BOOL WINAPI DllMain(HINSTANCE hInst, DWORD fdwReason, LPVOID lpReserved)
1442 {
1443 g_hInstance=hInst;
1444
1445 if (DLL_PROCESS_ATTACH == fdwReason)
1446 {
1447 // change the protection of return command
1448 VirtualProtect(&retexpr, sizeof(retexpr), PAGE_EXECUTE_READWRITE, (PDWORD)&LastStackPlace);
1449
1450 // initialize some variables
1451 LastStackPlace = 0, LastStackReal = 0;
1452 LastError = 0;
1453 LastProc = NULL;
1454 CallbackIndex = 0, g_CallbackThunkListHead = NULL;
1455 #ifdef SYSTEM_X86
1456 retexpr[0] = (char) 0xC2;
1457 retexpr[2] = 0x00;
1458 #elif defined(SYSTEM_AMD64) || defined(SYSTEM_ARM64)
1459 retexpr[0] = BUGBUG64(0);
1460 #else
1461 #error TODO
1462 #endif
1463 }
1464 return TRUE;
1465 }
1466
1467 /*
1468 Returns size by which the stack should be expanded
1469 */
1470 unsigned int GetNewStackSize(void)
1471 {
1472 return NEW_STACK_SIZE;
1473 }
1474
1475 /*
1476 Returns non-zero value if GENSTACK option is set
1477 */
1478 unsigned int GetGenStackOption(SystemProc *proc)
1479 {
1480 return (proc->Options & POPT_GENSTACK);
1481 }
1482
1483 /*
1484 Returns non-zero value if CDECL option is set
1485 */
1486 unsigned int GetCDeclOption(SystemProc *proc)
1487 {
1488 return (proc->Options & POPT_CDECL);
1489 }
1490
1491 /*
1492 Returns non-zero value if Error option is set
1493 */
1494 static unsigned int GetErrorOption(SystemProc *proc)
1495 {
1496 return (proc->Options & POPT_ERROR);
1497 }
1498
1499 /*
1500 Returns offset for element Proc of SystemProc structure
1501 */
1502 UINT_PTR GetProcOffset(void)
1503 {
1504 return (UINT_PTR)(&(((SystemProc *)0)->Proc));
1505 }
1506
1507 /*
1508 Returns offset for element Clone of SystemProc structure
1509 */
1510 unsigned int GetCloneOffset(void)
1511 {
1512 return (unsigned int)(UINT_PTR) (&(((SystemProc *)0)->Clone));
1513 }
1514
1515 /*
1516 Returns offset for element ProcName of SystemProc structure
1517 */
1518 unsigned int GetProcNameOffset(void)
1519 {
1520 return (unsigned int)(UINT_PTR) (&(((SystemProc *)0)->ProcName));
1521 }
1522
1523 /*
1524 Returns offset for element ArgsSize of SystemProc structure
1525 */
1526 unsigned int GetArgsSizeOffset(void)
1527 {
1528 return (unsigned int)(UINT_PTR) (&(((SystemProc *)0)->ArgsSize));
1529 }
1530
1531 /*
1532 Returns number of parameters
1533 */
1534 unsigned int GetParamCount(SystemProc *proc)
1535 {
1536 return proc->ParamCount;
1537 }
1538
1539 /*
1540 Returns offset for element Params of SystemProc structure
1541 */
1542 UINT_PTR GetParamsOffset(void)
1543 {
1544 return (UINT_PTR)(&(((SystemProc *)0)->Params));
1545 }
1546
1547 /*
1548 Returns size of ProcParameter structure
1549 */
1550 UINT_PTR GetSizeOfProcParam(void)
1551 {
1552 return (sizeof(ProcParameter));
1553 }
1554
1555 /*
1556 Returns offset for element Size of ProcParameter structure
1557 */
1558 unsigned int GetSizeOffsetParam(void)
1559 {
1560 return (unsigned int)(UINT_PTR) (&(((ProcParameter *)0)->Size));
1561 }
1562
1563 /*
1564 Returns offset for element Value of ProcParameter structure
1565 */
1566 UINT_PTR GetValueOffsetParam(void)
1567 {
1568 return (UINT_PTR)(&(((ProcParameter *)0)->Value));
1569 }
1570
1571 #ifndef _WIN64
1572 /*
1573 Returns offset for element _value of ProcParameter structure
1574 */
1575 unsigned int Get_valueOffsetParam(void)
1576 {
1577 return (unsigned int)(&(((ProcParameter *)0)->_value));
1578 }
1579 #endif
1580
1581 /*
1582 Sets "CLONE" option
1583 */
1584 void SetCloneOption(SystemProc *proc)
1585 {
1586 proc->Options |= POPT_CLONE;
1587 }
1588
1589 /*
1590 Sets Result of procedure call to be "OK"
1591 */
1592 static void SetProcResultOk(SystemProc *proc)
1593 {
1594 proc->ProcResult = PR_OK;
1595 }
1596
1597 /*
1598 Sets Result of procedure call to be "CALLBACK"
1599 */
1600 void SetProcResultCallback(SystemProc *proc)
1601 {
1602 proc->ProcResult = PR_CALLBACK;
1603 }
1604
1605 SystemProc* CALLBACK SetCallProcResultValues(SystemProc *proc, ULARGE_INTEGER retval)
1606 {
1607 if (GetErrorOption(proc)) LastError = GetLastError();
1608 #ifdef _WIN64
1609 proc->Params[0].Value = retval.QuadPart;
1610 #else
1611 proc->Params[0].Value = retval.LowPart, proc->Params[0]._value = retval.HighPart;
1612 #endif
1613 SetProcResultOk(proc);
1614 return proc;
1615 }