/
assembler.go
3156 lines (2859 loc) · 91.8 KB
/
assembler.go
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
// Copyright (C) 2019-2024 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package logic
import (
"bufio"
"bytes"
"crypto/sha512"
"encoding/base32"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"math"
"sort"
"strconv"
"strings"
"unicode"
"github.com/algorand/avm-abi/abi"
"github.com/algorand/go-algorand/data/basics"
)
// optimizeConstantsEnabledVersion is the first version of TEAL where the
// assembler optimizes constants introduced by pseudo-ops
const optimizeConstantsEnabledVersion = 4
// Writer is what we want here. Satisfied by bufio.Buffer
type Writer interface {
Write([]byte) (int, error)
WriteByte(c byte) error
}
type labelReference struct {
// position (PC) of the label reference
position int
// token holding the label name (and line, column)
label token
// ending position of the opcode containing the label reference.
offsetPosition int
}
type constReference interface {
// get the referenced value
getValue() interface{}
// check if the referenced value equals other. Other must be the same type
valueEquals(other interface{}) bool
// get the index into ops.pending where the opcode for this reference is located
getPosition() int
// get the length of the op for this reference in ops.pending
length(ops *OpStream, assembled []byte) (int, error)
// create the opcode bytes for a new reference of the same value
makeNewReference(ops *OpStream, singleton bool, newIndex int) []byte
}
type intReference struct {
value uint64
// position of the opcode start that declares the int value
position int
}
func (ref intReference) getValue() interface{} {
return ref.value
}
func (ref intReference) valueEquals(other interface{}) bool {
return ref.value == other.(uint64)
}
func (ref intReference) getPosition() int {
return ref.position
}
func (ref intReference) length(ops *OpStream, assembled []byte) (int, error) {
opIntc0 := OpsByName[ops.Version]["intc_0"].Opcode
opIntc1 := OpsByName[ops.Version]["intc_1"].Opcode
opIntc2 := OpsByName[ops.Version]["intc_2"].Opcode
opIntc3 := OpsByName[ops.Version]["intc_3"].Opcode
opIntc := OpsByName[ops.Version]["intc"].Opcode
switch assembled[ref.position] {
case opIntc0, opIntc1, opIntc2, opIntc3:
return 1, nil
case opIntc:
return 2, nil
default:
return 0, sourceErrorf(ops.OffsetToSource[ref.position], "unexpected op at intReference: %d", assembled[ref.position])
}
}
func (ref intReference) makeNewReference(ops *OpStream, singleton bool, newIndex int) []byte {
opIntc0 := OpsByName[ops.Version]["intc_0"].Opcode
opIntc1 := OpsByName[ops.Version]["intc_1"].Opcode
opIntc2 := OpsByName[ops.Version]["intc_2"].Opcode
opIntc3 := OpsByName[ops.Version]["intc_3"].Opcode
opIntc := OpsByName[ops.Version]["intc"].Opcode
opPushInt := OpsByName[ops.Version]["pushint"].Opcode
if singleton {
var scratch [binary.MaxVarintLen64]byte
vlen := binary.PutUvarint(scratch[:], ref.value)
newBytes := make([]byte, 1+vlen)
newBytes[0] = opPushInt
copy(newBytes[1:], scratch[:vlen])
return newBytes
}
switch newIndex {
case 0:
return []byte{opIntc0}
case 1:
return []byte{opIntc1}
case 2:
return []byte{opIntc2}
case 3:
return []byte{opIntc3}
default:
return []byte{opIntc, uint8(newIndex)}
}
}
type byteReference struct {
value []byte
// position of the opcode start that declares the byte value
position int
}
func (ref byteReference) getValue() interface{} {
return ref.value
}
func (ref byteReference) valueEquals(other interface{}) bool {
return bytes.Equal(ref.value, other.([]byte))
}
func (ref byteReference) getPosition() int {
return ref.position
}
func (ref byteReference) length(ops *OpStream, assembled []byte) (int, error) {
opBytec0 := OpsByName[ops.Version]["bytec_0"].Opcode
opBytec1 := OpsByName[ops.Version]["bytec_1"].Opcode
opBytec2 := OpsByName[ops.Version]["bytec_2"].Opcode
opBytec3 := OpsByName[ops.Version]["bytec_3"].Opcode
opBytec := OpsByName[ops.Version]["bytec"].Opcode
switch assembled[ref.position] {
case opBytec0, opBytec1, opBytec2, opBytec3:
return 1, nil
case opBytec:
return 2, nil
default:
return 0, sourceErrorf(ops.OffsetToSource[ref.position], "unexpected op at byteReference: %d", assembled[ref.position])
}
}
func (ref byteReference) makeNewReference(ops *OpStream, singleton bool, newIndex int) []byte {
opBytec0 := OpsByName[ops.Version]["bytec_0"].Opcode
opBytec1 := OpsByName[ops.Version]["bytec_1"].Opcode
opBytec2 := OpsByName[ops.Version]["bytec_2"].Opcode
opBytec3 := OpsByName[ops.Version]["bytec_3"].Opcode
opBytec := OpsByName[ops.Version]["bytec"].Opcode
opPushBytes := OpsByName[ops.Version]["pushbytes"].Opcode
if singleton {
var scratch [binary.MaxVarintLen64]byte
vlen := binary.PutUvarint(scratch[:], uint64(len(ref.value)))
newBytes := make([]byte, 1+vlen+len(ref.value))
newBytes[0] = opPushBytes
copy(newBytes[1:], scratch[:vlen])
copy(newBytes[1+vlen:], ref.value)
return newBytes
}
switch newIndex {
case 0:
return []byte{opBytec0}
case 1:
return []byte{opBytec1}
case 2:
return []byte{opBytec2}
case 3:
return []byte{opBytec3}
default:
return []byte{opBytec, uint8(newIndex)}
}
}
// SourceLocation points to a specific location in a source file.
type SourceLocation struct {
// Line is the line number, starting at 0.
Line int
// Column is the column number, starting at 0.
Column int
}
// OpStream accumulates state, including the final program, during assembly.
type OpStream struct {
Version uint64
Trace *strings.Builder
Warnings []sourceError // informational warnings, shouldn't stop assembly
Errors []sourceError // errors that should prevent final assembly
Program []byte // Final program bytes. Will stay nil if any errors
// Running bytes as they are assembled. jumps must be resolved
// and cblocks added before these bytes become a legal program.
pending bytes.Buffer
intc []uint64 // observed ints in code. We'll put them into a intcblock
intcRefs []intReference // references to int pseudo-op constants, used for optimization
cntIntcBlock int // prevent prepending intcblock because asm has one
hasPseudoInt bool // were any `int` pseudo ops used?
bytec [][]byte // observed bytes in code. We'll put them into a bytecblock
bytecRefs []byteReference // references to byte/addr pseudo-op constants, used for optimization
cntBytecBlock int // prevent prepending bytecblock because asm has one
hasPseudoByte bool // were any `byte` (or equivalent) pseudo ops used?
// tracks information we know to be true at the point being assembled
known ProgramKnowledge
typeTracking bool
// current sourceLine during assembly
sourceLine int
// map label string to position within pending buffer
labels map[string]int
// track references in order to patch in jump offsets
labelReferences []labelReference
// map opcode offsets to source location
OffsetToSource map[int]SourceLocation
HasStatefulOps bool
// Need new copy for each opstream
versionedPseudoOps map[string]map[int]OpSpec
macros map[string][]token
}
// newOpStream constructs OpStream instances ready to invoke assemble. A new
// OpStream must be used for each call to assemble().
func newOpStream(version uint64) OpStream {
o := OpStream{
labels: make(map[string]int),
OffsetToSource: make(map[int]SourceLocation),
typeTracking: true,
Version: version,
macros: make(map[string][]token),
known: ProgramKnowledge{fp: -1},
}
for i := range o.known.scratchSpace {
o.known.scratchSpace[i] = StackZeroUint64
}
return o
}
// ProgramKnowledge tracks statically known information as we assemble
type ProgramKnowledge struct {
// list of the types known to be on the value stack, based on specs of
// opcodes seen while assembling. In normal code, the tip of the stack must
// match the next opcode's Arg.Types, and is then replaced with its
// Return.Types. If `deadcode` is true, `stack` should be empty.
stack StackTypes
// bottom is the type given out when `stack` is empty. It is StackNone at
// program start, so, for example, a `+` opcode at the start of a program
// fails. But when a label or callsub is encountered, `stack` is truncated
// and `bottom` becomes StackAny, because we don't track program state
// coming in from elsewhere. A `+` after a label succeeds, because the stack
// "virtually" contains an infinite list of StackAny.
bottom StackType
// deadcode indicates that the program is in deadcode, so no type checking
// errors should be reported.
deadcode bool
// fp is the frame pointer, if known/usable, or -1 if not. When
// encountering a `proto`, `stack` is grown to fit `args`, and this `fp` is
// set to the top of those args. This may not be the "real" fp when the
// program is actually evaluated, but it is good enough for frame_{dig/bury}
// to work from there.
fp int
scratchSpace [256]StackType
}
func (pgm *ProgramKnowledge) top() (StackType, bool) {
if len(pgm.stack) == 0 {
return pgm.bottom, pgm.bottom.AVMType != avmNone
}
last := len(pgm.stack) - 1
return pgm.stack[last], true
}
func (pgm *ProgramKnowledge) pop() StackType {
if len(pgm.stack) == 0 {
return pgm.bottom
}
last := len(pgm.stack) - 1
t := pgm.stack[last]
pgm.stack = pgm.stack[:last]
return t
}
func (pgm *ProgramKnowledge) push(types ...StackType) {
pgm.stack = append(pgm.stack, types...)
}
func (pgm *ProgramKnowledge) deaden() {
pgm.stack = pgm.stack[:0]
pgm.deadcode = true
}
// label resets knowledge to reflect that control may enter from elsewhere.
func (pgm *ProgramKnowledge) label() {
if pgm.deadcode {
pgm.reset()
}
}
// reset clears existing knowledge and permissively allows any stack value. It's intended to be invoked after encountering a label or pragma type tracking change.
func (pgm *ProgramKnowledge) reset() {
pgm.stack = nil
pgm.bottom = StackAny
pgm.fp = -1
pgm.deadcode = false
for i := range pgm.scratchSpace {
pgm.scratchSpace[i] = StackAny
}
}
// createLabel inserts a label to point to the next instruction, reporting an
// error for a duplicate.
func (ops *OpStream) createLabel(withColon token) {
label := strings.TrimSuffix(withColon.str, ":")
if _, ok := ops.labels[label]; ok {
ops.record(withColon.errorf("duplicate label %#v", label))
}
ops.labels[label] = ops.pending.Len()
ops.known.label()
}
// recordSourceLocation adds an entry to pc to source location mapping
func (ops *OpStream) recordSourceLocation(line, column int) {
ops.OffsetToSource[ops.pending.Len()] = SourceLocation{line - 1, column}
}
// referToLabel records an opcode label reference to resolve later
func (ops *OpStream) referToLabel(pc int, label token, offsetPosition int) {
ops.labelReferences = append(ops.labelReferences, labelReference{pc, label, offsetPosition})
}
type refineFunc func(pgm *ProgramKnowledge, immediates []token) (StackTypes, StackTypes, error)
// returns allows opcodes like `txn` to be specific about their return value
// types, based on the field requested, rather than use Any as specified by
// opSpec. It replaces StackAny in the top `count` elements of the typestack.
func (ops *OpStream) returns(spec *OpSpec, replacement StackType) {
if ops.known.deadcode {
return
}
end := len(ops.known.stack)
tip := ops.known.stack[end-len(spec.Return.Types):]
for i := range tip {
if tip[i].AVMType == avmAny {
tip[i] = replacement
return
}
}
panic(fmt.Sprintf("returns was called on OpSpec '%s' without StackAny %+v in spec.Return",
spec.Name, spec.Return))
}
// writeIntc writes opcodes for loading a uint64 constant onto the stack.
func (ops *OpStream) writeIntc(constIndex uint) error {
switch constIndex {
case 0:
ops.pending.WriteByte(OpsByName[ops.Version]["intc_0"].Opcode)
case 1:
ops.pending.WriteByte(OpsByName[ops.Version]["intc_1"].Opcode)
case 2:
ops.pending.WriteByte(OpsByName[ops.Version]["intc_2"].Opcode)
case 3:
ops.pending.WriteByte(OpsByName[ops.Version]["intc_3"].Opcode)
default:
if constIndex > 0xff {
return errors.New("cannot have more than 256 int constants")
}
ops.pending.WriteByte(OpsByName[ops.Version]["intc"].Opcode)
ops.pending.WriteByte(uint8(constIndex))
}
if constIndex >= uint(len(ops.intc)) {
return fmt.Errorf("intc %d is not defined", constIndex)
}
ops.trace("intc %d: %d", constIndex, ops.intc[constIndex])
return nil
}
// intLiteral writes opcodes for loading a uint literal
func (ops *OpStream) intLiteral(val uint64) error {
ops.hasPseudoInt = true
found := false
var constIndex uint
for i, cv := range ops.intc {
if cv == val {
constIndex = uint(i)
found = true
break
}
}
if !found {
if ops.cntIntcBlock > 0 {
return fmt.Errorf("value %d does not appear in existing intcblock", val)
}
constIndex = uint(len(ops.intc))
ops.intc = append(ops.intc, val)
}
ops.intcRefs = append(ops.intcRefs, intReference{
value: val,
position: ops.pending.Len(),
})
return ops.writeIntc(constIndex)
}
// writeBytec writes opcodes for loading a []byte constant onto the stack.
func (ops *OpStream) writeBytec(constIndex uint) error {
switch constIndex {
case 0:
ops.pending.WriteByte(OpsByName[ops.Version]["bytec_0"].Opcode)
case 1:
ops.pending.WriteByte(OpsByName[ops.Version]["bytec_1"].Opcode)
case 2:
ops.pending.WriteByte(OpsByName[ops.Version]["bytec_2"].Opcode)
case 3:
ops.pending.WriteByte(OpsByName[ops.Version]["bytec_3"].Opcode)
default:
if constIndex > 0xff {
return errors.New("cannot have more than 256 byte constants")
}
ops.pending.WriteByte(OpsByName[ops.Version]["bytec"].Opcode)
ops.pending.WriteByte(uint8(constIndex))
}
if constIndex >= uint(len(ops.bytec)) {
return fmt.Errorf("bytec %d is not defined", constIndex)
}
ops.trace("bytec %d %s", constIndex, hex.EncodeToString(ops.bytec[constIndex]))
return nil
}
// byteLiteral writes opcodes and data for loading a []byte literal
// Values are accumulated so that they can be put into a bytecblock
func (ops *OpStream) byteLiteral(val []byte) error {
ops.hasPseudoByte = true
found := false
var constIndex uint
for i, cv := range ops.bytec {
if bytes.Equal(cv, val) {
found = true
constIndex = uint(i)
break
}
}
if !found {
if ops.cntBytecBlock > 0 {
return fmt.Errorf("value 0x%x does not appear in existing bytecblock", val)
}
constIndex = uint(len(ops.bytec))
ops.bytec = append(ops.bytec, val)
}
ops.bytecRefs = append(ops.bytecRefs, byteReference{
value: val,
position: ops.pending.Len(),
})
return ops.writeBytec(constIndex)
}
func asmInt(ops *OpStream, spec *OpSpec, mnemonic token, args []token) *sourceError {
if err := ops.checkArgCount(spec.Name, mnemonic, args, 1); err != nil {
return err
}
// After backBranchEnabledVersion, control flow is confusing, so if there's
// a manual cblock, use push instead of trying to use what's given.
if ops.cntIntcBlock > 0 && ops.Version >= backBranchEnabledVersion {
// We don't understand control-flow, so use pushint
ops.warn(args[0], "int %s used with explicit intcblock. must pushint", args[0].str)
pushint := OpsByName[ops.Version]["pushint"]
return asmPushInt(ops, &pushint, mnemonic, args)
}
// There are no backjumps, but there are multiple cblocks. Maybe one is
// conditional skipped. Too confusing.
if ops.cntIntcBlock > 1 {
pushint, ok := OpsByName[ops.Version]["pushint"]
if ok {
return asmPushInt(ops, &pushint, mnemonic, args)
}
return mnemonic.errorf("int %s used with manual intcblocks. Use intc.", args[0].str)
}
// In both of the above clauses, we _could_ track whether a particular
// intcblock dominates the current instruction. If so, we could use it.
// check txn type constants
i, ok := txnTypeMap[args[0].str]
if !ok {
// check OnCompletion constants
i, ok = onCompletionMap[args[0].str]
}
if !ok {
val, err := strconv.ParseUint(args[0].str, 0, 64)
if err != nil {
return args[0].errorf("unable to parse %#v as integer", args[0].str)
}
i = val
}
err := ops.intLiteral(i)
if err != nil {
return args[0].error(err)
}
return nil
}
// Explicit invocation of const lookup and push
func asmIntC(ops *OpStream, spec *OpSpec, mnemonic token, args []token) *sourceError {
if err := ops.checkArgCount(spec.Name, mnemonic, args, 1); err != nil {
return err
}
constIndex, err := byteImm(args[0].str, "constant")
if err != nil {
return args[0].error(err)
}
err = ops.writeIntc(uint(constIndex))
if err != nil {
return args[0].error(err)
}
return nil
}
func asmByteC(ops *OpStream, spec *OpSpec, mnemonic token, args []token) *sourceError {
if err := ops.checkArgCount(spec.Name, mnemonic, args, 1); err != nil {
return err
}
constIndex, err := byteImm(args[0].str, "constant")
if err != nil {
return args[0].error(err)
}
err = ops.writeBytec(uint(constIndex))
if err != nil {
return args[0].error(err)
}
return nil
}
func asmPushInt(ops *OpStream, spec *OpSpec, mnemonic token, args []token) *sourceError {
if err := ops.checkArgCount(spec.Name, mnemonic, args, 1); err != nil {
return err
}
val, err := strconv.ParseUint(args[0].str, 0, 64)
if err != nil {
return args[0].errorf("unable to parse %#v as integer", args[0].str)
}
ops.pending.WriteByte(spec.Opcode)
var scratch [binary.MaxVarintLen64]byte
vlen := binary.PutUvarint(scratch[:], val)
ops.pending.Write(scratch[:vlen])
return nil
}
func asmPushInts(ops *OpStream, spec *OpSpec, mnemonic token, args []token) *sourceError {
ops.pending.WriteByte(spec.Opcode)
asmIntImmArgs(ops, args)
return nil
}
func asmPushBytes(ops *OpStream, spec *OpSpec, mnemonic token, args []token) *sourceError {
// asmPushBytes is sometimes used to assemble the "byte" mnemonic, so use
// mnemonic.str instead of spec.Name when reporting errors.
if len(args) == 0 {
return mnemonic.errorAfterf("%s needs byte literal argument", mnemonic.str)
}
val, consumed, err := parseBinaryArgs(args)
if err != nil {
return args[consumed].errorf("%s %w", mnemonic.str, err)
}
if len(args) != consumed {
return args[consumed].errorf("%s with extraneous argument", mnemonic.str)
}
ops.pending.WriteByte(spec.Opcode)
var scratch [binary.MaxVarintLen64]byte
vlen := binary.PutUvarint(scratch[:], uint64(len(val)))
ops.pending.Write(scratch[:vlen])
ops.pending.Write(val)
return nil
}
func asmPushBytess(ops *OpStream, spec *OpSpec, mnemonic token, args []token) *sourceError {
ops.pending.WriteByte(spec.Opcode)
_, err := asmByteImmArgs(ops, spec, args)
return err
}
func base32DecodeAnyPadding(x string) (val []byte, err error) {
val, err = base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(x)
if err != nil {
// try again with standard padding
var e2 error
val, e2 = base32.StdEncoding.DecodeString(x)
if e2 == nil {
err = nil
}
}
return
}
// parseBinaryArgs parses a byte literal argument. It returns the argument,
// interpetted into raw bytes, and the number of tokens consumed.
func parseBinaryArgs(args []token) ([]byte, int, error) {
arg := args[0].str
if strings.HasPrefix(arg, "base32(") || strings.HasPrefix(arg, "b32(") {
open := strings.IndexRune(arg, '(')
close := strings.IndexRune(arg, ')')
if close == -1 {
return nil, 0, fmt.Errorf("argument %s lacks closing parenthesis", arg)
}
if close != len(arg)-1 {
return nil, 0, fmt.Errorf("argument %s must end at first closing parenthesis", arg)
}
val, err := base32DecodeAnyPadding(arg[open+1 : close])
if err != nil {
if cie, ok := err.(base32.CorruptInputError); ok {
return nil, 0, base32.CorruptInputError(int64(cie) + int64(open) + 1)
}
return nil, 0, err
}
return val, 1, nil
} else if strings.HasPrefix(arg, "base64(") || strings.HasPrefix(arg, "b64(") {
open := strings.IndexRune(arg, '(')
close := strings.IndexRune(arg, ')')
if close == -1 {
return nil, 0, fmt.Errorf("argument %s lacks closing parenthesis", arg)
}
if close != len(arg)-1 {
return nil, 0, fmt.Errorf("argument %s must end at first closing parenthesis", arg)
}
val, err := base64.StdEncoding.DecodeString(arg[open+1 : close])
if err != nil {
if cie, ok := err.(base64.CorruptInputError); ok {
return nil, 0, base64.CorruptInputError(int64(cie) + int64(open) + 1)
}
return nil, 0, err
}
return val, 1, nil
} else if strings.HasPrefix(arg, "0x") {
val, err := hex.DecodeString(arg[2:])
if err != nil {
return nil, 0, err
}
return val, 1, nil
} else if arg == "base32" || arg == "b32" {
if len(args) < 2 {
return nil, 0, fmt.Errorf("%s needs byte literal argument", arg)
}
val, err := base32DecodeAnyPadding(args[1].str)
if err != nil {
return nil, 1, err // return 1, so that the right token is blamed
}
return val, 2, nil
} else if arg == "base64" || arg == "b64" {
if len(args) < 2 {
return nil, 0, fmt.Errorf("%s needs byte literal argument", arg)
}
val, err := base64.StdEncoding.DecodeString(args[1].str)
if err != nil {
return nil, 1, err
}
return val, 2, nil
} else if len(arg) > 1 && arg[0] == '"' && arg[len(arg)-1] == '"' {
val, err := parseStringLiteral(arg)
if err != nil {
return nil, 0, err
}
return val, 1, err
}
return nil, 0, fmt.Errorf("arg did not parse: %v", arg)
}
func parseStringLiteral(input string) (result []byte, err error) {
start := 0
end := len(input) - 1
if input[start] != '"' || input[end] != '"' {
return nil, fmt.Errorf("no quotes")
}
start++
escapeSeq := false
hexSeq := false
result = make([]byte, 0, end-start+1)
// skip first and last quotes
pos := start
for pos < end {
char := input[pos]
if char == '\\' && !escapeSeq {
if hexSeq {
return nil, fmt.Errorf("escape sequence inside hex number")
}
escapeSeq = true
pos++
continue
}
if escapeSeq {
escapeSeq = false
switch char {
case 'n':
char = '\n'
case 'r':
char = '\r'
case 't':
char = '\t'
case '\\':
char = '\\'
case '"':
char = '"'
case 'x':
hexSeq = true
pos++
continue
default:
return nil, fmt.Errorf("invalid escape sequence \\%c", char)
}
}
if hexSeq {
hexSeq = false
if pos >= len(input)-2 { // count a closing quote
return nil, fmt.Errorf("non-terminated hex sequence")
}
num, err := strconv.ParseUint(input[pos:pos+2], 16, 8)
if err != nil {
return nil, err
}
char = uint8(num)
pos++
}
result = append(result, char)
pos++
}
if escapeSeq || hexSeq {
return nil, fmt.Errorf("non-terminated escape sequence")
}
return
}
// byte {base64,b64,base32,b32}(...)
// byte {base64,b64,base32,b32} ...
// byte 0x....
// byte "this is a string\n"
func asmByte(ops *OpStream, spec *OpSpec, mnemonic token, args []token) *sourceError {
if len(args) == 0 {
return mnemonic.errorAfterf("%s needs byte literal argument", spec.Name)
}
// After backBranchEnabledVersion, control flow is confusing, so if there's
// a manual cblock, use push instead of trying to use what's given.
if ops.cntBytecBlock > 0 && ops.Version >= backBranchEnabledVersion {
// We don't understand control-flow, so use pushbytes
ops.warn(args[0], "byte %s used with explicit bytecblock. must pushbytes", args[0].str)
pushbytes := OpsByName[ops.Version]["pushbytes"] // make sure pushbytes opcode is written
return asmPushBytes(ops, &pushbytes, mnemonic, args)
}
// There are no backjumps, but there are multiple cblocks. Maybe one is
// conditional skipped. Too confusing.
if ops.cntBytecBlock > 1 {
// use pushbytes opcode if available
pushbytes, ok := OpsByName[ops.Version]["pushbytes"]
if ok {
return asmPushBytes(ops, &pushbytes, mnemonic, args)
}
return args[0].errorf("byte %s used with manual bytecblocks. Use bytec.", args[0].str)
}
// In both of the above clauses, we _could_ track whether a particular
// bytecblock dominates the current instruction. If so, we could use it.
val, consumed, err := parseBinaryArgs(args)
if err != nil {
return args[consumed].errorf("%s %w", spec.Name, err)
}
if len(args) != consumed {
return args[consumed].errorf("%s with extraneous argument", spec.Name)
}
err = ops.byteLiteral(val)
if err != nil {
return args[0].error(err)
}
return nil
}
// method "add(uint64,uint64)uint64"
func asmMethod(ops *OpStream, spec *OpSpec, mnemonic token, args []token) *sourceError {
if err := ops.checkArgCount(spec.Name, mnemonic, args, 1); err != nil {
return err
}
arg := args[0].str
if len(arg) > 1 && arg[0] == '"' && arg[len(arg)-1] == '"' {
methodSig, err := parseStringLiteral(arg)
if err != nil {
return args[0].error(err)
}
methodSigStr := string(methodSig)
err = abi.VerifyMethodSignature(methodSigStr)
if err != nil {
// Warn if an invalid signature is used. Don't return an error, since the ABI is not
// governed by the core protocol, so there may be changes to it that we don't know about
ops.warn(args[0], "invalid ARC-4 ABI method signature for method op: %w", err)
}
hash := sha512.Sum512_256(methodSig)
err = ops.byteLiteral(hash[:4])
if err != nil {
return args[0].error(err)
}
return nil
}
return args[0].errorf("unable to parse method signature")
}
func asmIntImmArgs(ops *OpStream, args []token) []uint64 {
ivals := make([]uint64, len(args))
var scratch [binary.MaxVarintLen64]byte
l := binary.PutUvarint(scratch[:], uint64(len(args)))
ops.pending.Write(scratch[:l])
for i, xs := range args {
cu, err := strconv.ParseUint(xs.str, 0, 64)
if err != nil {
ops.record(xs.error(err))
}
l = binary.PutUvarint(scratch[:], cu)
ops.pending.Write(scratch[:l])
ivals[i] = cu
}
return ivals
}
func asmIntCBlock(ops *OpStream, spec *OpSpec, mnemonic token, args []token) *sourceError {
ops.pending.WriteByte(spec.Opcode)
ivals := asmIntImmArgs(ops, args)
if !ops.known.deadcode {
// If we previously processed an `int`, we thought we could insert our
// own intcblock, but now we see a manual one.
if ops.hasPseudoInt {
return mnemonic.errorf("intcblock following int")
}
ops.intcRefs = nil
ops.intc = ivals
ops.cntIntcBlock++
}
return nil
}
func asmByteImmArgs(ops *OpStream, spec *OpSpec, args []token) ([][]byte, *sourceError) {
bvals := make([][]byte, 0, len(args))
rest := args
for len(rest) > 0 {
val, consumed, err := parseBinaryArgs(rest)
if err != nil {
// Would be nice to keep going, as in asmIntImmArgs, but
// parseBinaryArgs would have to return a useful consumed value even
// in the face of errors. Hard.
return nil, rest[0].errorf("%s %w", spec.Name, err)
}
bvals = append(bvals, val)
rest = rest[consumed:]
}
var scratch [binary.MaxVarintLen64]byte
l := binary.PutUvarint(scratch[:], uint64(len(bvals)))
ops.pending.Write(scratch[:l])
for _, bv := range bvals {
l := binary.PutUvarint(scratch[:], uint64(len(bv)))
ops.pending.Write(scratch[:l])
ops.pending.Write(bv)
}
return bvals, nil
}
func asmByteCBlock(ops *OpStream, spec *OpSpec, mnemonic token, args []token) *sourceError {
ops.pending.WriteByte(spec.Opcode)
bvals, err := asmByteImmArgs(ops, spec, args)
if err != nil {
return err
}
if !ops.known.deadcode {
// If we previously processed a pseudo `byte`, we thought we could
// insert our own bytecblock, but now we see a manual one.
if ops.hasPseudoByte {
return mnemonic.errorf("bytecblock following byte/addr/method")
}
ops.bytecRefs = nil
ops.bytec = bvals
ops.cntBytecBlock++
}
return nil
}
// addr A1EU...
// parses base32-with-checksum account address strings into a byte literal
func asmAddr(ops *OpStream, spec *OpSpec, mnemonic token, args []token) *sourceError {
if err := ops.checkArgCount(spec.Name, mnemonic, args, 1); err != nil {
return err
}
addr, err := basics.UnmarshalChecksumAddress(args[0].str)
if err != nil {
return args[0].error(err)
}
err = ops.byteLiteral(addr[:])
if err != nil {
return args[0].error(err)
}
return nil
}
func asmArg(ops *OpStream, spec *OpSpec, mnemonic token, args []token) *sourceError {
if err := ops.checkArgCount(spec.Name, mnemonic, args, 1); err != nil {
return err
}
val, err := byteImm(args[0].str, "argument")
if err != nil {
return args[0].error(err)
}
altSpec := *spec
if val < 4 {
switch val {
case 0:
altSpec = OpsByName[ops.Version]["arg_0"]
case 1:
altSpec = OpsByName[ops.Version]["arg_1"]
case 2:
altSpec = OpsByName[ops.Version]["arg_2"]
case 3:
altSpec = OpsByName[ops.Version]["arg_3"]
}
args = []token{}
}
return asmDefault(ops, &altSpec, mnemonic, args)
}
func asmBranch(ops *OpStream, spec *OpSpec, mnemonic token, args []token) *sourceError {
if err := ops.checkArgCount(spec.Name, mnemonic, args, 1); err != nil {
return err
}
ops.referToLabel(ops.pending.Len()+1, args[0], ops.pending.Len()+spec.Size)
ops.pending.WriteByte(spec.Opcode)
// zero bytes will get replaced with actual offset in resolveLabels()
ops.pending.WriteByte(0)
ops.pending.WriteByte(0)
return nil
}