-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
assembler.ts
1319 lines (1064 loc) · 42.9 KB
/
assembler.ts
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
// @TODO:
// - warn return/revert non-empty, comment ; !assert(+1 @extra)
// - In JS add config (positionIndependent)
// - When checking name collisions, verify no collision in javascript
import { dirname, resolve } from "path";
import _module from "module";
import vm from "vm";
import { ethers } from "ethers";
import { Opcode } from "./opcodes";
import { parse as _parse, parser as _parser } from "./_parser";
import { version } from "./_version";
const logger = new ethers.utils.Logger(version);
const Guard = { };
function hexConcat(values: Array<Opcode | ethers.utils.BytesLike>): string {
return ethers.utils.hexlify(ethers.utils.concat(values.map((v) => {
if (v instanceof Opcode) { return [ v.value ]; }
if (typeof(v) === "number") {
if (v >= 0 && v <= 255 && !(v % 1)) {
return ethers.utils.hexlify(v);
} else {
throw new Error("invalid number: " + v);
}
}
return v;
})));
}
function repeat(char: string, length: number): string {
let result = char;
while (result.length < length) { result += result; }
return result.substring(0, length);
}
class Script {
readonly filename: string;
readonly context: any;
readonly contextObject: any;
private _context: { context: any };
constructor(filename: string, callback: (name: string, context: any) => any) {
ethers.utils.defineReadOnly(this, "filename", filename);
ethers.utils.defineReadOnly(this, "contextObject", this._baseContext(callback));
ethers.utils.defineReadOnly(this, "context", vm.createContext(this.contextObject));
}
_baseContext(callback: (name: string, context: any) => any): any {
return new Proxy({
__filename: this.filename,
__dirname: dirname(this.filename),
console: console,
Uint8Array: Uint8Array,
ethers: ethers,
utils: ethers.utils,
BigNumber: ethers.BigNumber,
arrayify: ethers.utils.arrayify,
concat: hexConcat,
hexlify: ethers.utils.hexlify,
zeroPad: function(value: ethers.utils.BytesLike, length: number) {
return ethers.utils.hexlify(ethers.utils.zeroPad(value, length));
},
id: ethers.utils.id,
keccak256: ethers.utils.keccak256,
namehash: ethers.utils.namehash,
sha256: ethers.utils.sha256,
parseEther: ethers.utils.parseEther,
formatEther: ethers.utils.formatEther,
parseUnits: ethers.utils.parseUnits,
formatUnits: ethers.utils.formatUnits,
randomBytes: function(length: number): string {
return ethers.utils.hexlify(ethers.utils.randomBytes(length));
},
toUtf8Bytes: ethers.utils.toUtf8Bytes,
toUtf8String: ethers.utils.toUtf8String,
formatBytes32String: ethers.utils.formatBytes32String,
parseBytes32String: ethers.utils.parseBytes32String,
Opcode: Opcode,
sighash: function(signature: string): string {
return ethers.utils.id(ethers.utils.FunctionFragment.from(signature).format()).substring(0, 10);
},
topichash: function(signature: string): string {
return ethers.utils.id(ethers.utils.EventFragment.from(signature).format());
},
assemble: assemble,
disassemble: disassemble,
Error: Error
}, {
get: (obj: any, key: string): any => {
if (obj[key]) { return obj[key]; }
if (!callback) { return undefined; }
return callback(key, this._context.context);
}
});
}
async evaluate(code: string, context?: any): Promise<string> {
if (this._context) { throw new Error("evaluation collision"); }
this._context = { context: context };
const script = new vm.Script(code, { filename: this.filename });
let result = script.runInContext(this.context);
if (result instanceof Promise) {
result = await result;
}
this._context = null;
return result;
}
}
let nextTag = 1;
export type Location = {
offset: number;
line: number;
length: number;
source: string;
statement: boolean;
};
export type AssembleVisitFunc = (node: Node, bytecode: string) => void;
export type VisitFunc = (node: Node) => void;
function throwError(message: string, location: Location): never {
return logger.throwError(message, <any>"ASSEMBLER", {
location: location
});
}
export abstract class Node {
readonly tag: string;
readonly location: Location;
constructor(guard: any, location: Location, options: { [ key: string ]: any }) {
if (guard !== Guard) { throwError("cannot instantiate class", location); }
logger.checkAbstract(new.target, Node);
ethers.utils.defineReadOnly(this, "location", Object.freeze(location));
ethers.utils.defineReadOnly(this, "tag", `node-${ nextTag++ }-${ this.constructor.name }`);
for (const key in options) {
ethers.utils.defineReadOnly<any, any>(this, key, options[key]);
}
}
// Note: EVERY node must call assemble with `this`, even if only with
// the bytes "0x" to trigger the offset and bytecode checks
async assemble(assembler: Assembler, visit: AssembleVisitFunc): Promise<void> {
assembler.start(this);
visit(this, "0x");
assembler.end(this);
}
children(): Array<Node> {
return [ ];
}
visit(visit: VisitFunc): void {
visit(this);
this.children().forEach((child) => {
child.visit(visit);
});
}
static from(options: any): Node {
const Factories: { [ type: string ]: { from: (options: any) => Node }} = {
data: DataNode,
decimal: LiteralNode,
eval: EvaluationNode,
exec: ExecutionNode,
hex: LiteralNode,
label: LabelNode,
length: LinkNode,
offset: LinkNode,
opcode: OpcodeNode,
pop: PopNode,
scope: ScopeNode,
};
const factory = Factories[options.type];
if (!factory) { throwError("unknown type: " + options.type, options.loc); }
return factory.from(options);
}
}
export abstract class ValueNode extends Node {
constructor(guard: any, location: Location, options: { [ key: string ]: any }) {
logger.checkAbstract(new.target, ValueNode);
super(guard, location, options);
}
getPushLiteral(value: ethers.utils.BytesLike | ethers.utils.Hexable | number) {
// Convert value into a hexstring
const hex = ethers.utils.hexlify(value);
if (hex === "0x") {
throwError("invalid literal: 0x", this.location);
}
// Make sure it will fit into a push
const length = ethers.utils.hexDataLength(hex);
if (length === 0 || length > 32) {
throwError(`literal out of range: ${ hex }`, this.location);
}
return hexConcat([ Opcode.from("PUSH" + String(length)), hex ]);
}
}
export class LiteralNode extends ValueNode {
readonly value: string;
readonly verbatim: boolean;
constructor(guard: any, location: Location, value: string, verbatim: boolean) {
super(guard, location, { value, verbatim });
}
async assemble(assembler: Assembler, visit: AssembleVisitFunc): Promise<void> {
assembler.start(this);
if (this.verbatim) {
if (this.value.substring(0, 2) === "0x") {
visit(this, this.value);
} else {
visit(this, ethers.BigNumber.from(this.value).toHexString());
}
} else {
visit(this, this.getPushLiteral(ethers.BigNumber.from(this.value)));
}
assembler.end(this);
}
static from(options: any): LiteralNode {
if (options.type !== "hex" && options.type !== "decimal") { throwError("expected hex or decimal type", options.loc); }
return new LiteralNode(Guard, options.loc, options.value, !!options.verbatim);
}
}
export class PopNode extends ValueNode {
readonly index: number;
constructor(guard: any, location: Location, index: number) {
super(guard, location, { index });
}
get placeholder(): string {
if (this.index === 0) { return "$$"; }
return "$" + String(this.index);
}
static from(options: any): PopNode {
return new PopNode(Guard, options.loc, options.index);
}
}
export class LinkNode extends ValueNode {
readonly type: string;
readonly label: string;
constructor(guard: any, location: Location, type: string, label: string) {
super(guard, location, { type, label });
}
async assemble(assembler: Assembler, visit: AssembleVisitFunc): Promise<void> {
assembler.start(this);
let value: number = null;
let isOffset = false;
const target = assembler.getTarget(this.label);
if (target instanceof LabelNode) {
if (this.type === "offset") {
value = (<number>(assembler.getLinkValue(target, this)));
isOffset = true;
}
} else {
const result = (<DataSource>(assembler.getLinkValue(target, this)));
if (this.type === "offset") {
value = result.offset;
isOffset = true;
} else if (this.type === "length") {
value = result.length;
}
}
if (value == null) {
throwError("labels can only be targetted as offsets", this.location);
}
if (isOffset && assembler.positionIndependentCode) {
const here = assembler.getOffset(this, this);
const opcodes = [ ];
if (here > value) {
// Jump backwards
// Find a literal with length the encodes its own length in the delta
let literal = "0x";
for (let w = 1; w <= 5; w++) {
if (w > 4) { throwError("jump too large!", this.location); }
literal = this.getPushLiteral(here - value + w);
if (ethers.utils.hexDataLength(literal) <= w) {
literal = ethers.utils.hexZeroPad(literal, w);
break;
}
}
opcodes.push(literal);
opcodes.push(Opcode.from("PC"));
opcodes.push(Opcode.from("SUB"));
// This also works, in case the above literal thing doesn't work out...
//opcodes.push(Opcode.from("PC"));
//opcodes.push(pushLiteral(-delta));
//opcodes.push(Opcode.from("SWAP1"));
//opcodes.push(Opcode.from("SUB"));
} else {
// Jump forwards; this is easy to calculate since we can
// do PC firat.
opcodes.push(Opcode.from("PC"));
opcodes.push(this.getPushLiteral(value - here));
opcodes.push(Opcode.from("ADD"));
}
visit(this, hexConcat(opcodes));
} else {
visit(this, this.getPushLiteral(value));
}
assembler.end(this);
}
static from(options: any): LinkNode {
// @TODO: Verify type is offset or link...
return new LinkNode(Guard, options.loc, options.type, options.label);
}
}
export class OpcodeNode extends ValueNode {
readonly opcode: Opcode;
readonly operands: Array<ValueNode>;
readonly instructional: boolean;
constructor(guard: any, location: Location, opcode: Opcode, operands: Array<ValueNode>, instructional: boolean) {
super(guard, location, { instructional, opcode, operands });
}
async assemble(assembler: Assembler, visit: AssembleVisitFunc): Promise<void> {
assembler.start(this);
// Compute the bytecode in reverse stack order
for (let i = this.operands.length - 1; i >= 0; i--) {
await this.operands[i].assemble(assembler, visit);
}
// Append this opcode
visit(this, ethers.utils.hexlify(this.opcode.value));
assembler.end(this);
}
children(): Array<Node> {
return this.operands;
}
visit(visit: VisitFunc): void {
for (let i = this.operands.length - 1; i >= 0; i--) {
this.operands[i].visit(visit);
}
visit(this);
}
static from(options: any): OpcodeNode {
if (options.type !== "opcode") { throwError("expected opcode type", options.loc); }
const opcode = Opcode.from(options.mnemonic);
if (!opcode) { throwError("unknown opcode: " + options.mnemonic, options.loc); }
const operands = Object.freeze(options.operands.map((o: any) => {
const operand = Node.from(o);
if (!(operand instanceof ValueNode)) {
throwError("bad grammar?!", options.loc);
}
return operand;
}));
return new OpcodeNode(Guard, options.loc, opcode, operands, !!options.bare);
}
}
export abstract class LabelledNode extends Node {
readonly name: string;
constructor(guard: any, location: Location, name: string, values?: { [ key: string ]: any }) {
logger.checkAbstract(new.target, LabelledNode);
values = ethers.utils.shallowCopy(values || { });
values.name = name;
super(guard, location, values);
}
}
export class LabelNode extends LabelledNode {
async assemble(assembler: Assembler, visit: AssembleVisitFunc): Promise<void> {
assembler.start(this);
visit(this, ethers.utils.hexlify(Opcode.from("JUMPDEST").value));
assembler.end(this);
}
static from(options: any): LabelNode {
if (options.type !== "label") { throwError("expected label type", options.loc); }
return new LabelNode(Guard, options.loc, options.name);
}
}
export class PaddingNode extends ValueNode {
_length: number;
constructor(guard: any, location: Location) {
super(guard, location, { });
this._length = 0;
}
setLength(length: number): void {
this._length = length;
}
async assemble(assembler: Assembler, visit: AssembleVisitFunc): Promise<void> {
assembler.start(this);
const padding = new Uint8Array(this._length);
padding.fill(0);
visit(this, ethers.utils.hexlify(padding));
assembler.end(this);
}
}
export class DataNode extends LabelledNode {
readonly data: Array<ValueNode>;
readonly padding: PaddingNode;
constructor(guard: any, location: Location, name: string, data: string) {
super(guard, location, name, { data });
ethers.utils.defineReadOnly(this, "padding", new PaddingNode(Guard, this.location));
}
async assemble(assembler: Assembler, visit: AssembleVisitFunc): Promise<void> {
assembler.start(this);
// @TODO: This is a problem... We need to visit before visiting children
// so offsets are correct, but then we cannot pad...
visit(this, "0x")
for (let i = 0; i < this.data.length; i++) {
await this.data[i].assemble(assembler, visit);
}
// We pad data if is contains PUSH opcodes that would overrun
// the data, which could eclipse valid operations (since the
// VM won't execute or jump within PUSH operations)
const bytecode = ethers.utils.concat(this.data.map((d) => assembler.getBytecode(d)));
// Replay the data as bytecode, skipping PUSH data
let i = 0;
while (i < bytecode.length) {
const opcode = Opcode.from(bytecode[i++]);
if (opcode) { i += opcode.isPush(); }
}
// The amount we overshot the data by is how much padding we need
this.padding.setLength(i - bytecode.length);
await this.padding.assemble(assembler, visit);
assembler.end(this);
}
children(): Array<Node> {
const children = this.data.slice();
children.push(this.padding);
return children;
}
static from(options: any): DataNode {
if (options.type !== "data") { throwError("expected data type", options.loc); }
return new DataNode(Guard, options.loc, options.name, Object.freeze(options.data.map((d: any) => Node.from(d))));
}
}
export class EvaluationNode extends ValueNode {
readonly script: string;
readonly verbatim: boolean;
constructor(guard: any, location: Location, script: string, verbatim: boolean) {
super(guard, location, { script, verbatim });
}
async assemble(assembler: Assembler, visit: AssembleVisitFunc): Promise<void> {
assembler.start(this);
const result: any = await assembler.evaluate(this.script, this);
if (this.verbatim) {
if (typeof(result) === "number") {
visit(this, ethers.BigNumber.from(result).toHexString());
} else {
visit(this, ethers.utils.hexlify(result));
}
} else {
visit(this, this.getPushLiteral(result));
}
assembler.end(this);
}
static from(options: any): EvaluationNode {
if (options.type !== "eval") { throwError("expected eval type", options.loc); }
return new EvaluationNode(Guard, options.loc, options.script, !!options.verbatim);
}
}
export class ExecutionNode extends Node {
readonly script: string;
constructor(guard: any, location: Location, script: string) {
super(guard, location, { script });
}
async assemble(assembler: Assembler, visit: AssembleVisitFunc): Promise<void> {
assembler.start(this);
await assembler.evaluate(this.script, this);
assembler.end(this);
}
static from(options: any): ExecutionNode {
if (options.type !== "exec") { throwError("expected exec type", options.loc); }
return new ExecutionNode(Guard, options.loc, options.script);
}
}
export class ScopeNode extends LabelledNode {
readonly statements: Array<Node>;
constructor(guard: any, location: Location, name: string, statements: Array<Node>) {
super(guard, location, name, { statements });
}
async assemble(assembler: Assembler, visit: AssembleVisitFunc): Promise<void> {
assembler.start(this);
visit(this, "0x");
for (let i = 0; i < this.statements.length; i++) {
await this.statements[i].assemble(assembler, visit);
}
assembler.end(this);
}
children(): Array<Node> {
return this.statements;
}
static from(options: any): ScopeNode {
if (options.type !== "scope") { throwError("expected scope type", options.loc); }
return new ScopeNode(Guard, options.loc, options.name, Object.freeze(options.statements.map((s: any) => Node.from(s))));
}
}
export type Operation = {
opcode: Opcode;
offset: number;
pushValue?: string;
};
export interface Bytecode extends Array<Operation> {
getOperation(offset: number): Operation;
}
export function disassemble(bytecode: string): Bytecode {
const ops: Array<Operation> = [ ];
const offsets: { [ offset: number ]: Operation } = { };
const bytes = ethers.utils.arrayify(bytecode, { allowMissingPrefix: true });
let i = 0;
let oob = false;
while (i < bytes.length) {
let opcode = Opcode.from(bytes[i]);
if (!opcode) {
opcode = new Opcode(`unknown (${ ethers.utils.hexlify(bytes[i]) })`, bytes[i], 0, 0);
} else if (oob && opcode.mnemonic === "JUMPDEST") {
opcode = new Opcode(`JUMPDEST (invalid; OOB!!)`, bytes[i], 0, 0);
}
const op: Operation = {
opcode: opcode,
offset: i
};
offsets[i] = op;
ops.push(op);
i++;
const push = opcode.isPush();
if (push) {
const data = ethers.utils.hexlify(bytes.slice(i, i + push));
if (ethers.utils.hexDataLength(data) === push) {
op.pushValue = data;
i += push;
} else {
oob = true;
}
}
}
(<Bytecode>ops).getOperation = function(offset: number): Operation {
return (offsets[offset] || null);
};
return (<Bytecode>ops);
}
export function formatBytecode(bytecode: Array<Operation>): string {
const lines: Array<string> = [ ];
bytecode.forEach((op) => {
const opcode = op.opcode;
let offset = ethers.utils.hexZeroPad(ethers.utils.hexlify(op.offset), 2);
if (opcode.isValidJumpDest()) {
offset += "*";
} else {
offset += " ";
}
let operation = opcode.mnemonic;
const push = opcode.isPush();
if (push) {
if (op.pushValue) {
operation = op.pushValue + `${ repeat(" ", 67 - op.pushValue.length) }; #${ push } `;
} else {
operation += `${ repeat(" ", 67 - operation.length) }; OOB!! `;
}
}
lines.push(`${ offset.substring(2) }: ${ operation }`);
});
return lines.join("\n");
}
export interface DataSource extends Array<number> {
offset: number;
ast: Node;
source: string;
_freeze?: () => void;
}
export type NodeState = {
node: Node;
offset: number;
bytecode: string;
};
export type AssemblerOptions = {
filename?: string;
retry?: number;
positionIndependentCode?: boolean;
defines?: { [ name: string ]: any };
target?: string;
};
export type ParserOptions = {
ignoreWarnings?: boolean;
}
class Assembler {
readonly root: Node;
readonly positionIndependentCode: boolean;
readonly nodes: { [ tag: string ]: NodeState };
readonly labels: { [ name: string ]: LabelledNode };
_parents: { [ tag: string ]: Node };
constructor(root: Node, positionIndependentCode?: boolean) {
ethers.utils.defineReadOnly(this, "root", root);
ethers.utils.defineReadOnly(this, "positionIndependentCode", !!positionIndependentCode);
const nodes: { [ tag: string ]: NodeState } = { };
const labels: { [ name: string ]: LabelledNode } = { };
const parents: { [ tag: string ]: Node } = { };
// Link labels to their target node
root.visit((node) => {
nodes[node.tag] = {
node: node,
offset: 0x0,
bytecode: "0x"
};
if (node instanceof LabelledNode) {
// Check for duplicate labels
if (labels[node.name]) {
logger.throwError(
("duplicate label: " + node.name),
ethers.utils.Logger.errors.UNSUPPORTED_OPERATION,
{ }
);
}
labels[node.name] = node;
}
});
root.visit((node) => {
// Check all labels exist
if (node instanceof LinkNode) {
const target = labels[node.label];
if (!target) {
logger.throwError(
("missing label: " + node.label),
ethers.utils.Logger.errors.UNSUPPORTED_OPERATION,
{ }
);
}
}
// Build the parent structure
node.children().forEach((child) => {
parents[child.tag] = node;
});
});
ethers.utils.defineReadOnly(this, "labels", Object.freeze(labels));
ethers.utils.defineReadOnly(this, "nodes", Object.freeze(nodes));
ethers.utils.defineReadOnly(this, "_parents", Object.freeze(parents));
}
// Link operations
getTarget(label: string): LabelledNode {
return this.labels[label];
}
// Evaluate script in the context of a {{! }} or {{= }}
evaluate(script: string, source: Node): Promise<any> {
return Promise.resolve(new Uint8Array(0));
}
getAncestor<T = Node>(node: Node, cls: { new(...args: any[]): T }): T {
node = this._parents[node.tag];
while (node) {
if (node instanceof cls) { return node; }
node = this._parents[node.tag];
}
return null;
}
getOffset(node: Node, source?: Node): number {
const offset = this.nodes[node.tag].offset;
if (source == null) { return offset }
const sourceScope: ScopeNode = ((source instanceof ScopeNode) ? source: this.getAncestor<ScopeNode>(source, ScopeNode));
return offset - this.nodes[sourceScope.tag].offset;
}
setOffset(node: Node, offset: number): void {
this.nodes[node.tag].offset = offset;
}
getBytecode(node: Node): string {
return this.nodes[node.tag].bytecode;
}
setBytecode(node: Node, bytecode: string): void {
this.nodes[node.tag].bytecode = bytecode;
}
getLinkValue(target: LabelledNode, source: Node): number | DataSource {
const sourceScope: ScopeNode = ((source instanceof ScopeNode) ? source: this.getAncestor<ScopeNode>(source, ScopeNode));
const targetScope: ScopeNode = ((target instanceof ScopeNode) ? target: this.getAncestor<ScopeNode>(target, ScopeNode));
if (target instanceof LabelNode) {
// Label offset (e.g. "@foo:"); accessible only within its direct scope
//const scope = this.getAncestor(source, Scope);
if (targetScope !== sourceScope) {
throwError(`cannot access ${ target.name } from ${ source.tag }`, source.location);
}
// Return the offset relative to its scope
return this.nodes[target.tag].offset - this.nodes[targetScope.tag].offset;
}
const info = this.nodes[target.tag];
// Return the offset is relative to its scope
const bytes = Array.prototype.slice.call(ethers.utils.arrayify(info.bytecode));
ethers.utils.defineReadOnly(bytes, "ast", target);
ethers.utils.defineReadOnly(bytes, "source", target.location.source);
if (!((target instanceof DataNode) || (target instanceof ScopeNode))) {
throwError("invalid link value lookup", source.location);
}
// Check that target is any descendant (or self) of the source scope
let safeOffset = (sourceScope == targetScope);
if (!safeOffset) {
sourceScope.visit((node) => {
if (node === targetScope) { safeOffset = true; }
});
}
// Not safe to access the offset; this will fault if anything tries.
if (!safeOffset) {
Object.defineProperty(bytes, "offset", {
get: function() { throwError(`cannot access ${ target.name }.offset from ${ source.tag }`, this.location); }
});
ethers.utils.defineReadOnly(bytes, "_freeze", function() { });
}
// Add the offset relative to the scope; unless the offset has
// been marked as invalid, in which case accessing it will fail
if (safeOffset) {
bytes.offset = info.offset - this.nodes[sourceScope.tag].offset;
let frozen = false;
ethers.utils.defineReadOnly(bytes, "_freeze", function() {
if (frozen) { return; }
frozen = true;
ethers.utils.defineReadOnly(bytes, "offset", bytes.offset);
});
}
return bytes;
}
start(node: Node): void { }
end(node: Node): void { }
}
export enum SemanticErrorSeverity {
error = "error",
warning = "warning"
};
export type SemanticError = {
readonly message: string;
readonly severity: SemanticErrorSeverity;
readonly node: Node;
};
// This Assembler is designed to only check for errors and warnings
// Warnings
// - Bare PUSH opcodes
// - Instructional opcode that has parameters
// Errors
// - Using a $$ outside of RPN
// - Using a $$ when it is not adjacent to the stack
// - The operand count does not match the opcode
// - An opcode is used as an operand but does not return a value
class SemanticChecker extends Assembler {
check(): Array<SemanticError> {
const errors: Array<SemanticError> = [ ];
this.root.visit((node) => {
if (node instanceof OpcodeNode) {
const opcode = node.opcode;
if (node.instructional) {
if (opcode.delta) {
errors.push({
message: `${ opcode.mnemonic } used as instructional`,
severity: SemanticErrorSeverity.warning,
node: node
});
}
} else {
if (opcode.mnemonic === "POP") {
if (node.operands.length !== 0) {
errors.push({
message: "POP expects 0 operands",
severity: SemanticErrorSeverity.error,
node: node
});
}
} else if (node.operands.length !== opcode.delta) {
errors.push({
message: `${ opcode.mnemonic } expects ${ opcode.delta } operands`,
severity: SemanticErrorSeverity.error,
node: node
});
}
}
if (opcode.isPush()) {
// A stray PUSH operation will gobble up the following code
// bytes which is bad. But this may be a disassembled program
// and that PUSH may actually be just some data (which is safe)
errors.push({
message: "PUSH opcode modifies program flow - use literals instead",
severity: SemanticErrorSeverity.warning,
node: node
});
} else if (!node.location.statement && opcode.alpha !== 1) {
// If an opcode does not push anything on the stack, it
// cannot be used as an operand
errors.push({
message: `${ node.opcode.mnemonic } cannot be an operand`,
severity: SemanticErrorSeverity.error,
node: node
});
}
}
if (node.location.statement) {
if (node instanceof PopNode) {
// $$ by istelf is useless and is intended to be an operand
errors.push({
message: `$$ must be an operand`,
severity: SemanticErrorSeverity.error,
node: node
});
} else {
const scope = this.getAncestor(node, ScopeNode);
// Make sure any $$ is stack adjacent (within this scope)
const ordered: Array<Node> = [ ];
node.visit((node) => {
if (scope !== this.getAncestor(node, ScopeNode)) { return; }
ordered.push(node);
});
// Allow any number of stack adjacent $$
let foundZero = null;
let lastIndex = 0;
while (ordered.length && ordered[0] instanceof PopNode) {
const popNode = (<PopNode>(ordered.shift()));
const index = popNode.index;
if (index === 0) {
foundZero = popNode;
} else if (index !== lastIndex + 1) {
errors.push({
message: `out-of-order stack placeholder ${ popNode.placeholder }; expected $$${ lastIndex + 1 }`,
severity: SemanticErrorSeverity.error,
node: popNode
});
while (ordered.length && ordered[0] instanceof PopNode) {
ordered.shift();
}
break;
} else {
lastIndex = index;
}
}
if (foundZero && lastIndex > 0) {
errors.push({
message: "cannot mix $$ and $1 stack placeholder",
severity: SemanticErrorSeverity.error,
node: foundZero
});
}
// If there are still any buried, we have a problem
const pops = ordered.filter((n) => (n instanceof PopNode));
if (pops.length) {
errors.push({
message: `stack placeholder ${ (<PopNode>(pops[0])).placeholder } must be stack adjacent`,
severity: SemanticErrorSeverity.error,