This repository has been archived by the owner on Oct 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathcalling-convention.js
548 lines (483 loc) · 20.3 KB
/
calling-convention.js
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
"use strict";
/* jshint esnext: true, evil: true */
let convention;
if (Process.arch === "arm64" && Process.platform === "darwin") {
// see swift-llvm/lib/Target/AArch64/AArch64CallingConvention.td
convention = {
selfRegister: 'x20',
errorRegister: 'x21',
indirectResultRegister: 'x8',
maxInlineArgument: 128, // TODO: the optional string arg for dump() is much larger and inline!
maxInlineReturn: 4 * Process.pointerSize, // see shouldPassIndirectlyForSwift in swift-llvm/lib/CodeGen/TargetInfo.cpp
firstArgRegister: 'x0',
intraProcedureScratch: 'x16',
maxVoluntaryInt: Process.pointerSize,
maxInt: 8,
maxIntAlignment: 8,
};
} else if (Process.arch === "arm" && Process.platform === "darwin") {
// see swift-llvm/lib/Target/ARM/ARMCallingConv.td
convention = {
selfRegister: 'r10',
errorRegister: 'r8',
indirectResultRegister: undefined, // first argument, not a special register
maxInlineArgument: 64, // TODO: watchOS uses 128
maxInlineReturn: 4 * Process.pointerSize, // see shouldPassIndirectlyForSwift in swift-llvm/lib/CodeGen/TargetInfo.cpp
firstArgRegister: 'r0',
intraProcedureScratch: 'r12',
maxVoluntaryInt: Process.pointerSize,
maxInt: 8,
maxIntAlignment: 4,
};
} else {
throw new Error("unknown platform");
}
//convention.freeze();
let errors = new Map();
let storeError = new NativeCallback(function storeError(error) {
errors.set(Process.getCurrentThreadId(), error);
}, 'void', ['pointer']);
function checkTrampolineError() {
let id = Process.getCurrentThreadId();
let val = errors.get(id);
errors.delete(id);
return val;
}
function makeCallTrampoline(func, withError, self, indirectResult) {
if (!withError && !self && !indirectResult)
return {callAddr: func};
let buf = Memory.alloc(Process.pageSize);
Memory.patchCode(buf, Process.pageSize, (wrtBuf) => {
let wr, putBlxImm;
if (Process.arch === "arm64") {
wr = new Arm64Writer(wrtBuf);
putBlxImm = 'putBlImm';
} else {
wr = new ThumbWriter(wrtBuf);
putBlxImm = 'putBlxImm';
}
// initialize error register to 0 (no error)
if (withError)
wr.putLdrRegAddress(convention.errorRegister, ptr(0));
// TODO: we should read the value for 'self' from a global/thread-local variable
// that way, we don't need to regenerate this function for every call
// set self register to self
if (self)
wr.putLdrRegAddress(convention.selfRegister, self);
// set the indirect result register to pre-allocated memory region
if (indirectResult) {
if (!convention.indirectResultRegister)
throw new Error("only provide the indirect result pointer on platforms with a specific register for it!");
wr.putLdrRegAddress(convention.indirectResultRegister, indirectResult);
}
if (withError) {
// generate call to actual function
wr[putBlxImm](func);
// check if function return error
if (Process.arch === "arm64")
wr.putTstRegImm(convention.errorRegister, ptr(0));
else
wr.putCmpRegImm(convention.errorRegister, ptr(0));
// skip return if error has occurred
wr.putBCondLabel('ne', 'err_case')
// return if no error
wr.putRet();
// error has occured!
wr.putLabel('err_case')
// move error value to first argument
wr.putMovRegReg(convention.firstArgRegister, convention.errorRegister);
// tail call to JS function that stores the error value
wr.putBImm(storeError);
} else {
// tail call to actual function
if ('putBranchAddress' in wr) {
wr.putBranchAddress(func);
} else {
wr.putLdrRegAddress(convention.intraProcedureScratch, func)
wr.putBxReg(convention.intraProcedureScratch);
}
}
wr.flush();
wr.dispose();
});
let callAddr;
if (Process.arch === "arm64")
callAddr = buf;
else
callAddr = buf.or(ptr(1)); // THUMB
return {
'callAddr': callAddr,
'_buf': buf,
};
};
function semanticLowering(signature) {
function typeNeedsIndirection(t) {
// TODO: generic arguments are also indirect (but we don't have any way to represent generic types yet)
// TODO: value types containing generic arguments are also indirect
// TODO: resilient value types are also indirect
return t.kind === "Existential";
}
function addArg(type, indirect, ownership, target, special) {
if (!indirect && type.kind === "Tuple") {
type.tupleElements().forEach(e => addArg(e.type, indirect, ownership, target, special));
} else {
indirect = indirect || typeNeedsIndirection(type);
target.push({ type, indirect, ownership, special, });
}
}
let args = [];
let swiftArgs = signature.getArguments();
for (let i = 0; i < swiftArgs.length; i++) {
let indirect = swiftArgs[i].inout;
let isSelf = i === 0 && false; // TODO
addArg(swiftArgs[i].type, indirect, args, indirect ? "keep" : "transfer", isSelf ? "self" : null);
}
const types = require('./types');
let rets = [];
addArg(signature.returnType, false, "return_take", rets, null);
if (signature.flags.doesThrow) {
addArg(types.typesByName.get("Swift.Error"), true, "return_take", rets, "error");
}
return { args, rets };
}
function physicalLowering(semantic) {
let legalTypesAndOffsets = [];
let specialCases = [];
let pointerType = "int" + (Process.pointerSize * 8);
function nextPowerOf2(val) { return Math.pow(2, Math.ceil(Math.log2(val))); }
function minimalInt(numValues) {
let log2 = Math.ceil(Math.log2(numValues));
let nextMultipleOf8 = (8 + log2 - (log2 % 8));
return nextPowerOf2(nextMultipleOf8);
}
function addEmpty(start, end, res) {
res.push(["empty", start, end]);
}
function addSwiftType(type, offset, res) {
if (res === undefined)
res = [];
switch (type.kind) {
case "Class":
case "ObjCClassWrapper":
case "ForeignClass":
case "Metatype":
case "Existential":
res.push([pointer, offset, offset + Process.pointerSize]);
break;
case "Struct": {
let prevEnd = offset;
type.fields().forEach(f => {
let offs = offset + f.offset;
if (prevEnd < offs)
addEmpty(prevEnd, offs, res);
if (f.weak) {
res.push([pointer, offs, offs + Process.pointerSize]);
prevEnd = offs + Process.pointerSize;
} else {
addSwiftType(f.type, offs, res);
prevEnd = offs + f.type.canonicalType.valueWitnessTable.size;
}
});
let end = offset + type.canonicalType.valueWitnessTable.size;
if (prevEnd < end)
addEmpty(prevEnd, offs, res);
break;
}
case "Tuple": {
let prevEnd = offset;
type.tupleElements().forEach(e => {
let offs = offset + e.offset;
if (prevEnd < offs)
addEmpty(prevEnd, offs, res);
addSwiftType(e.type, offs, res)
prevEnd = offs + e.type.canonicalType.valueWitnessTable.size;
});
let end = offset + type.canonicalType.valueWitnessTable.size;
if (prevEnd < end)
addEmpty(prevEnd, offs, res);
break;
}
case "ErrorObject":
case "ExistentialMetatype":
case "Function":
throw new Error(`conversion to legal type for types of '${type.kind}' not yet implemented`); // TODO
case "Optional":
case "Enum": {
let numPayloads = type.nominalType.enum_.getNumPayloadCases();
let numEmpty = type.nominalType.enum_.getNumEmptyCases();
let enumSize = type.canonicalType.valueWitnessTable.size;
if (numPayloads === 0) {
// C-like enum
res.push(["int" + (enumSize * 8), offset, offset + enumSize]);
} else if (numPayloads === 1) {
// single-payload enum
let payloadType = type.enumCases()[0].type;
addSwiftType(payloadType, offset, res); // payload is always at the beginning, possibly followed by discriminant
let payloadVwt = payloadType.canonicalType.valueWitnessTable;
let extraInhabitants = payloadVwt.extraInhabitantFlags.getNumExtraInhabitants();
if (extraInhabitants < numEmpty) {
// there is a tag at the end
let tagSize = minimalInt(numEmpty + numPayloads);
let offs = offset + payloadVwt.size;
// TODO: verify that the tag does not get padded for alignment
res.push(["int" + tagSize, offs, offs + tagSize]);
} else {
// no tag
res.push(["opaque", offset, offset + enumSize]);
}
} else {
// multi-payload enum
// We can't use metadata to figure out whether the payload cases have enough overlapping
// spare bits.
// We can approximate by comparing the size of the largest payload with the size of the enum.
let enumCases = type.enumCases();
let largestSize = enumCases.reduce((s, c) => {
if (c.type)
return Math.max(s, c.type.canonicalType.valueWitnessTable.size);
else
return s;
}, 0);
// primary tag
if (enumSize > largestSize) {
res.push(["opaque", offset + largestSize, offset + enumSize]);
}
// payloads
for (let i = 0; i < enumCases.length; i++) {
if (enumCases[i].type) {
addSwiftType(enumCases[i].type, offset, res);
}
}
// secondary tag for the non-payload cases
if (numEmpty > 1) {
let tagSize = minimalInt(numEmpty);
res.push(["opaque", offset, offset + tagSize]);
}
}
break;
}
case "Opaque": {
let t = type.getCType();
if (t === undefined)
throw new Error(`the equivalent C type for type '${type}' is not known.`);
if (t === "pointer")
t = pointerType;
if (t.startsWith("uint"))
t = t.slice(1);
if (t.startsWith("int") && parseInt(t.slice(3)) > convention.maxInt)
t = "opaque";
container.push([t, offset]);
break;
}
default:
throw new Error(`type '${type}' is of unknown kind '${type.kind}'`);
}
}
for (let i = 0; i < semantic.length; i++) {
if (semantic[i].special) {
specialCases.push(semantic[i].special);
continue;
}
if (semantic[i].indirect)
legalTypesAndOffsets.push([pointerType, 0, Process.pointerSize]);
else
legalTypesAndOffsets.push(addSwiftType(semantic[i].type, 0));
}
function combineAdjacent() {
let maps = {
empty: new Map(),
opaque: new Map(),
};
for (let i = 0; i < legalTypesAndOffsets.length; i++) {
let legalType = legalTypesAndOffsets[i][0];
let map = maps[legalType];
if (map === undefined)
continue;
for (let j = legalTypesAndOffsets[i][1]; j < legalTypesAndOffsets[i][2]; j++) {
if (map.has(j)) {
let other = map.get(j);
let start = Math.min(legalTypesAndOffsets[i][1], legalTypesAndOffsets[other][1]);
let end = Math.max(legalTypesAndOffsets[i][2], legalTypesAndOffsets[other][2]);
for (let k = legalTypesAndOffsets[other][1]; k < legalTypesAndOffsets[other][1]; k++) {
map.delete(k);
}
legalTypesAndOffsets[other][1] = start;
legalTypesAndOffsets[other][2] = end;
i = other - 1; // restart looking for other matches with the new bounds
break;
} else {
map.set(j, i);
}
}
}
}
combineAdjacent();
// find overlapped non-empty memory regions
let indicesByOffset = new Map();
for (let i = 0; i < legalTypesAndOffsets.length; i++) {
for (let j = legalTypesAndOffsets[i][1]; j < legalTypesAndOffsets[i][2]; j++) {
if (!indicesByOffset.has(j))
indicesByOffset.set(j, []);
indicesByOffset.get(j).push(i);
}
}
// merge overlapped non-empty memory regions
for (let [offset, indices] of indicesByOffset.entries()) {
if (indices.length <= 1)
continue;
for (let i = 1; i < indices.length; i++) {
let t0 = legalTypesAndOffsets[indices[i - 1]];
let t1 = legalTypesAndOffsets[indices[i]];
if (t0[0] === t1[0])
continue;
t0[0] = t1[0] = "opaque";
}
}
combineAdjacent();
// end of typed layout
/* legal type sequence */
// change types to opaque when their values have wrong alignment
for (let i = 0; i < legalTypesAndOffsets.length; i++) {
if (legalTypesAndOffsets[i][0] === "empty" || legalTypesAndOffsets[i][0] === "opaque")
continue;
let naturalAlignment;
let size = legalTypesAndOffsets[i][2] - legalTypesAndOffsets[i][1];
if (legalTypesAndOffsets[i][0].startsWith("int")) {
naturalAlignment = Math.min(size, convention.maxVoluntaryInt);
} else {
naturalAlignment = size;
}
if ((legalTypesAndOffsets[i][1] % naturalAlignment) !== 0) {
legalTypesAndOffsets[i][0] = "opaque";
}
}
combineAdjacent();
for (let i = 0; i < legalTypesAndOffsets.length; i++) {
let size = legalTypesAndOffsets[i][2] - legalTypesAndOffsets[i][1];
if (legalTypesAndOffsets[i][0].startsWith("int") && size <= convention.maxVoluntaryInt)
legalTypesAndOffsets[i][0] = "opaque";
}
combineAdjacent();
combineAdjacent = undefined; // make sure we don't combine anything below this point.
// split opaque values at maximal aligned storage units
for (let i = 0; i < legalTypesAndOffsets.length; i++) {
if (legalTypesAndOffsets[i][0] !== "opaque")
continue;
let start = legalTypesAndOffsets[i][1];
let end = legalTypesAndOffsets[i][2];
let nextBoundary = start - (start % convention.maxVoluntaryInt) + convention.maxVoluntaryInt;
while (nextBoundary < end - (end % convention.maxVoluntaryInt)) {
legalTypesAndOffsets.push(["opaque", start, nextBoundary]);
start = nextBoundary;
nextBoundary += convention.maxVoluntaryInt;
}
legalTypesAndOffsets[i][1] = start;
}
// turn opaques into integers
let perStorageUnit = new Map();
let lastStorageUnit = 0;
for (let i = 0; i < legalTypesAndOffsets.length; i++) {
if (legalTypesAndOffsets[i][0] !== "opaque")
continue;
let start = legalTypesAndOffsets[i][1];
let storageUnit = (start - (start % convention.maxVoluntaryInt)) / convention.maxVoluntaryInt;
if (!perStorageUnit.has(storageUnit))
perStorageUnit.set(storageUnit, []);
perStorageUnit.get(storageUnit).push(i);
lastStorageUnit = Math.max(lastStorageUnit, storageUnit);
}
let toRemove = [];
for (let sharedUnit of perStorageUnit.values()) {
let start = Number.POSITIVE_INFINITY;
let end = Number.NEGATIVE_INFINITY;
for (let i of sharedUnit) {
start = Math.min(legalTypesAndOffsets[i][1], start);
end = Math.max(legalTypesAndOffsets[i][2], end);
}
// remove all but one of the opaque values in this storage unit
toRemove = toRemove.concat(sharedUnit.slice(1));
let size;
for (size = 1; start + size < end; size *= 2) { }
let newStart = start & ~(size - 1);
if (newStart != start)
size *= 2;
let newEnd = newStart + size;
legalTypesAndOffsets[sharedUnit[0]] = ["int" + (size * 8).toString(), newStart, newEnd];
}
toRemove.sort().reverse();
for (let i of toRemove) {
legalTypesAndOffsets.splice(i, 1);
}
legalTypesAndOffsets.sort((a, b) => a[1] - b[1]);
return legalTypesAndOffsets;
}
function convertToCParams(signature) {
let [semanticArgs, semanticRets] = semanticLowering(signature);
let [physicalArgs, physicalRets] = [semanticArgs, semanticRets].map(physicalLowering);
// TODO: for generic functions, generic arguments are always passed indirectly, and arguments with the
// type metadata of those arguments are added at the end of the arg list
let lowered = [];
let argInfos = [];
// expand tuples into their components
let argTypes = [];
for (let i = 0; i < method.args.length; i++) {
let elem = toCheck.shift();
if (elem.kind === "Tuple") {
toCheck = elem.elements.map(e => e.type).concat(toCheck);
} else {
argTypes.push(elem);
}
}
// see NativeConventionSchema::getCoercionTypes
for (let i = 0; i < params.length; i++) {
// TODO: floats/doubles, vectors
// see classifyArgumentType in swift-clang/lib/CodeGen/TargetInfo.cpp
let type = method.args[i].type;
let lowering = getLowering(params[i]);
let vwt = type.canonicalType.valueWitnessTable;
if (vwt.size === 0) // ignore zero-sized types
continue;
if (method.args[i].inout || vwt.flags.IsNonBitwiseTakable || vwt.size > CC.maxInlineArgument) {
lowered.push({size: Process.pointerSize, stride: Process.pointerSize, indirect: true});
} else {
lowered.push({size: vwt.size, stride: vwt.stride, indirect: false});
}
}
// see SwiftAggLowering::finish
let remainingSpace = 0;
for (let i = 0; i < lowered.length; i++) {
}
let indirectReturn = false;
let cReturnType = 'void';
if (method.returnType) {
let vwt = method.returnType.valueWitnessTable;
// TODO: verify these are the right conditions for indirect returns
if (vwt.size > CC.maxInlineReturn || vwt.flags.IsNonPOD) {
indirectReturn = true;
lowered.unshift({size: Process.pointerSize, stride: Process.pointerSize, indirect: true});
} else {
let alignedSize = vwt.size;
let remaining = 0;
cReturnType = [];
for (let size of [8, 4, 2, 1]) {
// TODO: specify larger integers for int types larger than pointers
while (size <= convention.maxVoluntaryInt && alignedSize > 0 && alignedSize % size === 0) {
// TODO: floats/doubles, vectors
cReturnType.push('uint' + (size * 8).toString());
alignedSize -= size;
}
}
}
}
let overlappedWithSuccessor = new Set();
for (let i = 0; i < params.length; i++) {
}
let cParams = [], cArgTypes = [];
for (let i = 0; i < params.length; i++) {
}
return {cParams, lowered};
}
module.exports = {
convention,
makeCallTrampoline,
checkTrampolineError,
};