forked from AutoHotkey/AutoHotkey
-
Notifications
You must be signed in to change notification settings - Fork 1
/
MdFunc.cpp
522 lines (482 loc) · 13 KB
/
MdFunc.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
#include "stdafx.h"
#include "MdFunc.h"
#include "abi.h"
#include "script_func_impl.h"
#include "window.h"
// internal to this file
struct MdFuncEntry
{
LPCTSTR name;
void *function;
MdType rettype;
MdType argtype[23];
};
#if 0 // Currently unused
// For use reinterpreting member function pointers (not standard C++).
template<typename T> constexpr void* cast_into_voidp(T in)
{
union { T in; void *out; } u { in };
return u.out;
}
#endif
#define md_mode decl
#include "lib\functions.h"
#undef md_mode
MdFuncEntry sMdFunc[]
{
#define md_mode data
#include "lib\functions.h"
#undef md_mode
};
Func *Script::GetBuiltInMdFunc(LPTSTR aFuncName)
{
#ifdef _DEBUG
static bool sChecked = false;
if (!sChecked)
{
sChecked = true;
for (int i = 1; i < _countof(sMdFunc); ++i)
if (_tcsicmp(sMdFunc[i-1].name, sMdFunc[i].name) >= 0)
MsgBox(_T("DEBUG: sMdFunc out of order."), 0, sMdFunc[i].name);
}
#endif
int left, right, mid, result;
for (left = 0, right = _countof(sMdFunc) - 1; left <= right;)
{
mid = (left + right) / 2;
auto &f = sMdFunc[mid];
result = _tcsicmp(aFuncName, f.name);
if (result > 0)
left = mid + 1;
else if (result < 0)
right = mid - 1;
else // Match found.
{
int ac;
for (ac = 0; ac < _countof(f.argtype) && f.argtype[ac] != MdType::Void; ++ac);
return new MdFunc(f.name, f.function, f.rettype, f.argtype, ac);
}
}
return nullptr;
}
#pragma region PerformDynaCall
extern "C" UINT64 DynaCall(size_t aArgCount, UINT_PTR *aArg, void *aFunction, DWORD aFlag);
extern "C" float GetFloatRetval();
extern "C" double GetDoubleRetval();
#pragma endregion
MdFunc::MdFunc(LPCTSTR aName, void *aMcFunc, MdType aRetType, MdType *aArg, UINT aArgSize)
: NativeFunc(aName)
, mMcFunc {aMcFunc}
, mArgType {aArg}
, mRetType {aRetType}
, mMaxResultTokens {0}
, mArgSlots {0}
, mThisCall {false}
{
// #if _DEBUG, ensure aArg is effectively terminated for the inner loop below.
ASSERT(!aArgSize || !MdType_IsMod(aArg[aArgSize - 1]));
if (aArgSize > 1 && *aArg == MdType::ThisCall)
{
mThisCall = true;
mArgType++;
}
int ac = 0, pc = 0;
for (UINT i = 0; i < aArgSize; ++i)
{
bool opt = false, retval = false;
MdType out = MdType::Void;
for (; MdType_IsMod(aArg[i]); ++i)
{
ASSERT(i < aArgSize);
if (aArg[i] == MdType::Optional)
opt = true;
else if (MdType_IsOut(aArg[i]))
out = aArg[i];
else if (aArg[i] == MdType::RetVal)
retval = true;
}
#ifndef _WIN64
if (MdType_Is64bit(aArg[i]) && out == MdType::Void && !opt) // out and opt parameters are excluded because they are passed by address.
++ac;
#endif
++ac;
if (!retval && !MdType_IsBits(aArg[i]))
{
++pc;
if (!opt && pc - 1 == mMinParams)
mMinParams = pc;
if (aArg[i] == MdType::String || aArg[i] == MdType::Variant && out != MdType::Void)
++mMaxResultTokens;
}
}
mParamCount = pc;
mArgSlots = ac;
}
bool MdFunc::Call(ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount)
{
if (!Func::Call(aResultToken, aParam, aParamCount))
return false;
if (aParamCount < mMinParams)
{
aResultToken.Error(ERR_TOO_FEW_PARAMS, mName);
return false;
}
DEBUGGER_STACK_PUSH(this) // See comments in BuiltInFunc::Call.
// rtp stores the results of ToString() calls if needed.
ResultToken *rtp = mMaxResultTokens == 0 ? nullptr
: (ResultToken *)_alloca(mMaxResultTokens * sizeof(ResultToken));
int rt_count = 0;
UINT_PTR *args = (UINT_PTR *)_alloca(mArgSlots * sizeof(UINT_PTR));
ResultType result = OK;
MdType retval_arg_type = MdType::Void;
int retval_index = -1;
int output_var_count = 0;
auto atp = mArgType;
for (int ai = 0, pi = 0; ai < mArgSlots; ++ai, ++atp)
{
bool opt = false;
MdType out = MdType::Void;
for (; MdType_IsMod(*atp); ++atp)
{
if (*atp == MdType::Optional)
opt = true;
else if (MdType_IsOut(*atp))
out = *atp;
else if (*atp == MdType::RetVal)
retval_index = ai;
}
ASSERT(retval_index != ai || out != MdType::Void && !opt);
auto arg_type = *atp;
auto &arg_value = args[ai];
if (out != MdType::Void && !(opt && ParamIndexIsOmitted(pi)))
{
void *av_buf;
// Different 'out' modifiers could be supported here to control allocation behaviour,
// but for built-in functions we'll just use StrRet for String, pointer for all others.
if (arg_type == MdType::String)
{
if (retval_index == ai)
av_buf = aResultToken.buf;
else
av_buf = _alloca(_TSIZE(StrRet::CallerBufSize));
*(LPTSTR)av_buf = '\0';
av_buf = new (_alloca(sizeof(StrRet))) StrRet((LPTSTR)av_buf);
//MessageBox(NULL, (LPCWSTR)av_buf, NULL, 0);
}
else if (arg_type == MdType::Variant)
{
// Rarely used, so no specialized abstraction yet.
if (retval_index == ai)
av_buf = &aResultToken;
else
{
ResultToken &rt = rtp[rt_count++];
rt.InitResult(talloca(_f_retval_buf_size));
av_buf = &rt;
}
}
else
{
//ASSERT(arg_type != MdType::Variant);
av_buf = _alloca(8); // This buffer will receive the actual output value.
*(__int64*)av_buf = 0;
}
arg_value = (UINT_PTR)av_buf; // Pass the address of the buffer or StrRet.
}
if (retval_index == ai) // Not included within aParam.
{
//if (arg_type == MdType::Variant)
// arg_value = (UINT_PTR)&aResultToken;
retval_arg_type = arg_type;
//retval_out_type = out;
continue;
}
if (MdType_IsBits(arg_type))
{
// arg_type represents a constant value to put directly into args.
arg_value = MdType_BitsValue(arg_type);
continue;
}
if (ParamIndexIsOmitted(pi))
{
if (!opt)
{
result = aResultToken.Error(ERR_PARAM_REQUIRED);
goto end;
}
// Pass nullptr for this optional parameter to indicate that it has been omitted.
// MdType_Is64bit(arg_type) isn't relevant in this case since opt == true.
arg_value = 0;
pi++;
continue;
}
auto ¶m = *aParam[pi++];
if (out != MdType::Void) // Out or some variant, and not retval (which was already handled).
{
if (!TokenToOutputVar(param))
{
result = aResultToken.ParamError(pi, ¶m, _T("VarRef"));
goto end;
}
++output_var_count;
// arg_value was already set above.
continue;
}
if (arg_type == MdType::String)
{
LPTSTR buf = nullptr;
switch (param.symbol)
{
case SYM_VAR:
if (!param.var->HasObject())
break; // No buffer needed even if it's pure numeric.
case SYM_INTEGER:
case SYM_FLOAT:
case SYM_OBJECT:
buf = (LPTSTR)_alloca(MAX_NUMBER_SIZE * sizeof(TCHAR));
}
ExprTokenType *t;
if (auto obj = TokenToObject(param))
{
ResultToken &rt = rtp[rt_count++];
rt.InitResult(buf);
ObjectToString(rt, param, obj);
if (rt.Exited())
{
result = FAIL;
goto end;
}
if (rt.symbol == SYM_OBJECT)
{
result = aResultToken.TypeError(_T("String"), rt);
goto end;
}
t = &rt;
}
else
t = ¶m;
arg_value = (UINT_PTR)TokenToString(*t, buf);
}
else if (arg_type == MdType::Object)
{
arg_value = (DWORD_PTR)TokenToObject(param);
if (!arg_value)
{
result = aResultToken.ParamError(pi, ¶m, _T("Object"));
goto end;
}
}
else if (arg_type == MdType::Variant)
{
arg_value = (DWORD_PTR)¶m;
}
else
{
ExprTokenType nt;
if (arg_type == MdType::Bool32)
{
nt.SetValue(TokenToBOOL(param));
}
else
{
ASSERT(MdType_IsNum(arg_type));
if (!TokenToDoubleOrInt64(param, nt))
{
result = aResultToken.ParamError(pi - 1, ¶m, _T("Number"));
goto end;
}
}
// If necessary, convert integer <-> float within the value union.
if (arg_type == MdType::Float64)
{
if (nt.symbol == SYM_INTEGER)
nt.value_double = (double)nt.value_int64;
}
else
{
if (nt.symbol == SYM_FLOAT)
nt.value_int64 = (__int64)nt.value_double;
}
void *target = &arg_value;
if (opt) // Optional values are represented by a pointer to a value.
arg_value = (UINT_PTR)(target = _alloca(8));
#ifndef _WIN64
if (MdType_Is64bit(arg_type))
{
*(__int64*)target = nt.value_int64;
if (!opt) // See above.
++ai; // Consume an additional arg slot.
}
else
*(UINT*)target = (UINT)nt.value_int64;
#else
*(__int64*)target = nt.value_int64;
#endif
}
}
union {
UINT64 rup;
__int64 ri64;
int ri32;
FResult res;
};
// Make the call
rup = DynaCall(mArgSlots, args, mMcFunc, mThisCall);
// Convert the return value
bool aborted = false;
switch (mRetType)
{
case MdType::Int32: aResultToken.SetValue(ri32); break;
case MdType::UInt64:
case MdType::Int64: aResultToken.SetValue(ri64); break;
case MdType::UInt32: aResultToken.SetValue((UINT)rup); break;
case MdType::Float64: aResultToken.SetValue(GetDoubleRetval()); break;
case MdType::String: aResultToken.SetValue((LPTSTR)rup); break; // Strictly statically-allocated strings.
case MdType::ResultType: aResultToken.SetResult((ResultType)rup); break;
case MdType::FResult:
if (FAILED(res))
{
FResultToError(aResultToken, aParam, aParamCount, res);
aborted = true;
}
else
aborted = (res == FR_ABORTED);
break;
case MdType::NzIntWin32:
if (!(BOOL)rup)
aResultToken.Win32Error();
break;
case MdType::Bool32: aResultToken.SetValue(ri32 ? TRUE : FALSE); break;
}
if (retval_index != -1)
{
if (retval_arg_type == MdType::String)
{
auto strret = (StrRet*)args[retval_index];
if (strret->UsedMalloc())
aResultToken.AcceptMem(const_cast<LPTSTR>(strret->Value()), strret->Length());
else if (strret->Value())
aResultToken.SetValue(const_cast<LPTSTR>(strret->Value()), strret->Length());
//else leave aResultToken set to its default value, "".
}
else if (retval_arg_type != MdType::Variant) // Variant type passes aResultToken directly.
TypedPtrToToken(retval_arg_type, (void*)args[retval_index], aResultToken);
}
if (aborted)
{
aResultToken.Free(); // In case memory was allocated or an object was returned, despite the return value indicating failure.
aResultToken.mem_to_free = nullptr; // Because Free() doesn't clear it.
aResultToken.SetValue(_T(""), 0);
}
// Copy output parameters
atp = mArgType;
for (int ai = 0, pi = 0; output_var_count; ++atp, ++ai, ++pi)
{
if (ai == retval_index)
++ai; // This args slot doesn't correspond to an aParam slot.
ASSERT(pi < aParamCount); // Implied by how output_var_count was calculated.
MdType out = MdType::Void;
for (; MdType_IsMod(*atp); ++atp)
if (MdType_IsOut(*atp))
out = *atp;
if (out == MdType::Void || ParamIndexIsOmitted(pi))
continue;
--output_var_count;
auto var = ParamIndexToOutputVar(pi);
ASSERT(var); // Implied by validation during processing of parameter inputs.
auto arg_value = args[ai];
if (*atp == MdType::String)
{
auto strret = (StrRet*)arg_value;
if (!strret->Value())
var->Assign();
else if (strret->UsedMalloc())
var->AcceptNewMem(const_cast<LPTSTR>(strret->Value()), strret->Length());
else
var->AssignString(strret->Value(), strret->Length());
}
else if (*atp == MdType::Variant)
{
ResultToken &value = *(ResultToken*)arg_value;
if (value.mem_to_free)
{
ASSERT(value.symbol == SYM_STRING && value.marker == value.mem_to_free);
var->AcceptNewMem(value.marker, value.marker_length);
value.mem_to_free = nullptr;
}
else
var->Assign(value);
// ResultTokens are allocated from rtp[], and are freed below.
//value.Free();
}
else
{
ExprTokenType value;
TypedPtrToToken(*atp, (void*)arg_value, value);
if (value.symbol == SYM_OBJECT)
var->AssignSkipAddRef(value.object);
else
var->Assign(value);
}
// Now that any memory or object allocated by the function has been assigned:
if (aborted)
{
// Although 0 or "" is a fairly conventional default, it might not be safe.
// For error-detection and to avoid unexpected behaviour, "unset" the var.
var->Uninitialize();
}
}
end:
DEBUGGER_STACK_POP()
// Free any temporary results of ToString() calls.
for (int i = 0; i < rt_count; ++i)
rtp[i].Free();
return result;
}
// Shallow-copy a value from aPtr to aToken.
void TypedPtrToToken(MdType aType, void *aPtr, ExprTokenType &aToken)
{
switch (aType)
{
case MdType::Bool32:
case MdType::Int32: aToken.SetValue(*(int*)aPtr); break;
case MdType::UInt32: aToken.SetValue(*(UINT*)aPtr); break;
case MdType::UInt64:
case MdType::Int64: aToken.SetValue(*(__int64*)aPtr); break;
case MdType::Float64: aToken.SetValue(*(double*)aPtr); break;
case MdType::Object:
if (auto obj = *(IObject**)aPtr)
aToken.SetValue(obj);
else
aToken.SetValue(_T(""), 0);
break;
case MdType::String: // String*, not String
if (auto str = *(LPTSTR*)aPtr)
aToken.SetValue(str);
else
aToken.SetValue(_T(""), 0);
break;
}
}
bool MdFunc::ArgIsOutputVar(int aIndex)
{
auto atp = mArgType;
for (int ai = 0; ai < mArgSlots; ++ai, ++atp, --aIndex)
{
MdType out = MdType::Void;
for (; MdType_IsMod(*atp); ++atp)
{
if (MdType_IsOut(*atp))
out = *atp;
else if (*atp == MdType::RetVal)
++aIndex;
}
if (aIndex == 0)
return out != MdType::Void;
#ifndef _WIN64
if (MdType_Is64bit(*atp))
++ai;
#endif
}
return false;
}