-
Notifications
You must be signed in to change notification settings - Fork 2
/
asm.go
1314 lines (1173 loc) · 33.6 KB
/
asm.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 2018 Andrei Tudor Călin
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package ebpf
import (
"encoding/binary"
"fmt"
"io"
"strconv"
"unsafe"
)
var hostByteOrder binary.ByteOrder
func init() {
var buf [2]byte
u16ptr := (*uint16)(unsafe.Pointer(&buf[0]))
*u16ptr = 0x1234
switch buf[0] {
case 0x12:
hostByteOrder = binary.BigEndian
case 0x34:
hostByteOrder = binary.LittleEndian
}
}
// Opcode is an eBPF opcode.
type Opcode uint8
// Class returns the instruction class of o.
func (o Opcode) Class() Class {
return Class(o & classMask)
}
// Size returns the size of the instruction, applicable if
// o represents a load or a store.
func (o Opcode) Size() Size {
return Size(o & sizeMask)
}
// Mode returns the address mode of the instruction, applicable
// if o represents a load or a store.
func (o Opcode) Mode() Mode {
return Mode(o & modeMask)
}
// ALUOp returns the ALU operation associated with o, applicable
// if o.Class() is ALU or ALU64.
func (o Opcode) ALUOp() ALUOp {
return ALUOp(o & aluOpMask)
}
// JumpCond returns the jump condition associated with o, applicable
// if o.Class() is JMP.
func (o Opcode) JumpCond() JumpCond {
return JumpCond(o & jumpCondMask)
}
// SourceOperand returns the source operand associated with o, applicable
// if o.Class() is ALU or ALU64.
func (o Opcode) SourceOperand() SourceOperand {
return SourceOperand(o & sourceOperandMask)
}
func (o Opcode) String() string {
// TODO(acln): how does this relate to Instruction.String()?
return errNotImplemented.Error()
}
// Class is an eBPF instruction class.
type Class uint8
// Instruction classes.
const (
LD Class = 0x00
LDX Class = 0x01
ST Class = 0x02
STX Class = 0x03
ALU Class = 0x04
JMP Class = 0x05
ALU64 Class = 0x07
)
var classStrings = map[Class]string{
LD: "ld",
LDX: "ldx",
ST: "st",
STX: "stx",
ALU: "alu",
JMP: "jmp",
ALU64: "alu64",
}
func (c Class) String() string {
s, ok := classStrings[c]
if !ok {
return "unknown class"
}
return s
}
const classMask = 0x07
// Size is the size of a load or store instruction.
type Size uint8
// Instruction widths.
const (
W Size = 0x00 // 32 bit
H Size = 0x08 // 16 bit
B Size = 0x10 // 8 bit
DW Size = 0x18 // 64 bit
)
var sizeStrings = map[Size]string{
W: "w",
H: "h",
B: "b",
DW: "dw",
}
func (sz Size) String() string {
s, ok := sizeStrings[sz]
if !ok {
return "unknown size"
}
return s
}
const sizeMask = 0x18
// Mode is the addres mode of a load or store instruction.
type Mode uint8
// Valid address modes.
const (
IMM Mode = 0x00
ABS Mode = 0x20
IND Mode = 0x40
MEM Mode = 0x60
LEN Mode = 0x80
MSH Mode = 0xa0
XADD Mode = 0xc0
)
var modeStrings = map[Mode]string{
IMM: "imm",
ABS: "abs",
IND: "ind",
MEM: "mem",
LEN: "len",
MSH: "msh",
XADD: "xadd",
}
func (m Mode) String() string {
s, ok := modeStrings[m]
if !ok {
return "unknown mode"
}
return s
}
const modeMask = 0xe0
// ALUOp specifies an ALU operation.
type ALUOp uint8
// Valid ALU operations.
const (
ADD ALUOp = 0x00
SUB ALUOp = 0x10
MUL ALUOp = 0x20
DIV ALUOp = 0x30
OR ALUOp = 0x40
AND ALUOp = 0x50
LSH ALUOp = 0x60
RSH ALUOp = 0x70
NEG ALUOp = 0x80
MOD ALUOp = 0x90
XOR ALUOp = 0xa0
MOV ALUOp = 0xb0
ARSH ALUOp = 0xc0
END ALUOp = 0xd0
)
var aluOpStrings = map[ALUOp]string{
ADD: "add",
SUB: "sub",
MUL: "mul",
DIV: "div",
OR: "or",
AND: "and",
LSH: "lsh",
RSH: "rsh",
NEG: "neg",
MOD: "mod",
XOR: "xor",
MOV: "mov",
ARSH: "arsh",
END: "end",
}
func (op ALUOp) String() string {
s, ok := aluOpStrings[op]
if !ok {
return "unknown ALU op"
}
return s
}
const aluOpMask = 0xf0
// JumpCond specifies a jump condition.
type JumpCond uint8
// Valid jump conditions.
const (
JA JumpCond = 0x00
JEQ JumpCond = 0x10
JGT JumpCond = 0x20
JGE JumpCond = 0x30
JSET JumpCond = 0x40
JNE JumpCond = 0x50
JSGT JumpCond = 0x60
JSGE JumpCond = 0x70
CALL JumpCond = 0x80
EXIT JumpCond = 0x90
JLT JumpCond = 0xa0
JLE JumpCond = 0xb0
JSLT JumpCond = 0xc0
JSLE JumpCond = 0xd0
)
var jumpCondStrings = map[JumpCond]string{
JA: "ja",
JEQ: "jeq",
JGT: "jgt",
JGE: "jge",
JSET: "jset",
JNE: "jne",
JSGT: "jsgt",
JSGE: "jsge",
CALL: "call",
EXIT: "exit",
JLT: "jlt",
JLE: "jle",
JSLT: "jslt",
JSLE: "jsle",
}
func (jc JumpCond) String() string {
s, ok := jumpCondStrings[jc]
if !ok {
return "unknown jump condition"
}
return s
}
const jumpCondMask = 0xf0
// SourceOperand specifies the souce operand for an instruction.
type SourceOperand uint8
// Source operands.
const (
// K specifies the 32 bit immediate as the source operand.
K SourceOperand = 0x00
// X specifies the source register as the source operand.
X SourceOperand = 0x08
)
var sourceOperandStrings = map[SourceOperand]string{
K: "k",
X: "x",
}
func (op SourceOperand) String() string {
s, ok := sourceOperandStrings[op]
if !ok {
return "unknown source operand"
}
return s
}
const sourceOperandMask = 0x08
// Register is an eBPF register.
type Register uint8
// Valid eBPF registers.
//
// When calling kernel functions, R0 holds the return value, R1 -
// R5 are destroyed and set to unreadable, and R6 - R9 are preserved
// (callee-saved). R10 or FP is the read-only frame pointer.
const (
R0 Register = iota
R1
R2
R3
R4
R5
R6
R7
R8
R9
R10
FP = R10
// PseudoMapFD is used to specify a map file descriptor
// for loading, in a 64 bit immediate load instruction.
PseudoMapFD Register = 1
// PseudoCall is used to specify a kernel function to call,
// in a call instruction.
PseudoCall Register = 1
)
var registerStrings = map[Register]string{
R0: "r0",
R1: "r1",
R2: "r2",
R3: "r3",
R4: "r4",
R5: "r5",
R6: "r6",
R7: "r7",
R8: "r8",
R9: "r9",
FP: "fp",
}
func (r Register) String() string {
// We don't care about PseudoMapFD and PseudoCall here.
// Code that cares deals with them in the larger context
// of one specific instruction.
s, ok := registerStrings[r]
if !ok {
return "unknown register"
}
return s
}
// KernelFunc is a function callable by eBPF programs from inside the kernel.
type KernelFunc int32
// Kernel functions.
const (
KernelFunctionUnspec KernelFunc = iota // bpf_unspec
MapLookupElem // bpf_map_lookup_elem
MapUpdateElem // bpf_map_update_elem
MapDeleteElem // bpf_map_delete_elem
ProbeRead // bpf_probe_read
KTimeGetNS // bpf_ktime_get_ns
TracePrintk // bpf_trace_printk
GetPrandomU32 // bpf_get_prandom_u32
GetSMPProcessorID // bpf_get_smp_processor_id
SKBStoreBytes // bpf_skb_store_bytes
L3CSumReplace // bpf_l3_csum_replace
L4CSumReplace // bpf_l4_csum_replace
TailCall // bpf_tail_call
CloneRedirect // bpf_clone_redirect
GetCurrentPIDTGID // bpf_get_current_pid_tgid
GetCurrentUIDGID // bpf_get_current_uid_gid
GetCurrentComm // bpf_get_current_comm
GetCGroupClassID // bpf_get_cgroup_classid
SKBVLanPush // bpf_skb_vlan_push
SKBVLanPop // bpf_skb_vlan_pop
SKBGetTunnelKey // bpf_skb_get_tunnel_key
SKBSetTunnelKey // bpf_skb_set_tunnel_key
PerfEventRead // bpf_perf_event_read
Redirect // bpf_redirect
GetRouteRealm // bpf_get_route_realm
PerfEventOutput // bpf_perf_event_output
SKBLoadBytes // bpf_skb_load_bytes
GetStackID // bpf_get_stackid
CSumDiff // bpf_csum_diff
SKBGetTunnelOpt // bpf_skb_get_tunnel_opt
SKBSetTunnelOpt // bpf_skb_set_tunnel_opt
SKBChangeProto // bpf_skb_change_proto
SKBChangeType // bpf_skb_change_type
SKBUnderCGroup // bpf_skb_under_cgroup
GetHashRecalc // bpf_get_hash_recalc
GetCurrentTask // bpf_get_current_task
ProbeWriteUser // bpf_probe_write_user
CurrentTaskUnderCGroup // bpf_current_task_under_cgroup
SKBChangeTail // bpf_skb_change_tail
SKBPullData // bpf_skb_pull_data
CSumUpdate // bpf_csum_update
SetHashInvalid // bpf_set_hash_invalid
GetNUMANodeID // bpf_get_numa_node_id
SKBChangeHEad // bpf_skb_change_head
XDPAdjustHead // bpf_xdp_adjust_head
ProbeReadStr // bpf_probe_read_str
GetSocketCookie // bpf_get_socket_cookie
GetSocketUID // bpf_get_socket_uid
SetHash // bpf_set_hash
SetSockopt // bpf_setsockopt
SKBAdjustRoom // bpf_skb_adjust_room
RedirectMap // bpf_redirect_map
SKRedirectMap // bpf_sk_redirect_map
SockMapUpdate // bpf_sock_map_update
XDPAdjustMeta // bpf_xdp_adjust_meta
PerfEventReadValue // bpf_perf_event_read_value
PerfProgReadValue // bpf_perf_prog_read_value
GetSockopt // bpf_getsockopt
OverrideReturn // bpf_override_return
SockOpsCBFlagsSet // bpf_sock_ops_cb_flags_set
MsgRedirectMap // bpf_msg_redirect_map
MsgApplyBytes // bpf_msg_apply_bytes
MsgCorkBytes // bpf_msg_cork_bytes
MsgPullData // bpf_msg_pull_data
Bind // bpf_bind
XDPAdjustTail // bpf_xdp_adjust_tail
SKBGetXFRMState // bpf_skb_get_xfrm_state
GetStack // bpf_get_stack
SKBLoadBytesRelative // bpf_skb_load_bytes_relative
FibLookup // bpf_fib_lookup
SockHashUpdate // bpf_sock_hash_update
MsgRedirectHash // bpf_msg_redirect_hash
SKRedirectHash // bpf_sk_redirect_hash
LWTPushEncap // bpf_lwt_push_encap
LWTSeg6StoreBytes // bpf_lwt_seg6_store_bytes
LWTSeg6AdjustSRH // bpf_lwt_seg6_adjust_srh
LWTSeg6Action // bpf_lwt_seg6_action
RCRepeat // bpf_rc_repeat
RCKeydown // bpf_rc_keydown
SKBCGroupID // bpf_skb_cgroup_id
GetCurrentCGroupID // bpf_get_current_cgroup_id
GetLocalStorage // bpf_get_local_storage
SKSelectReuseport // bpf_sk_select_reuseport
SKBAncestorCGroupID // bpf_skb_ancestor_cgroup_id
SKLookupTCP // bpf_sk_lookup_tcp
SKLookupUDP // bpf_sk_lookup_udp
SKRelease // bpf_sk_release
MapPushElem // bpf_map_push_elem
MapPopElem // bpf_map_pop_elem
MapPeekElem // bpf_map_peek_elem
MsgPushData // bpf_msg_push_data
)
// String returns the name of the kernel function represented by fn.
func (fn KernelFunc) String() string {
s, ok := kernelFuncStrings[fn]
if !ok {
return "unknown kernel function"
}
return s
}
var kernelFuncStrings = map[KernelFunc]string{
MapLookupElem: "bpf_map_lookup_elem",
MapUpdateElem: "bpf_map_update_elem",
MapDeleteElem: "bpf_map_delete_elem",
ProbeRead: "bpf_probe_read",
KTimeGetNS: "bpf_ktime_get_ns",
TracePrintk: "bpf_trace_printk",
GetPrandomU32: "bpf_get_prandom_u32",
GetSMPProcessorID: "bpf_get_smp_processor_id",
SKBStoreBytes: "bpf_skb_store_bytes",
L3CSumReplace: "bpf_l3_csum_replace",
L4CSumReplace: "bpf_l4_csum_replace",
TailCall: "bpf_tail_call",
CloneRedirect: "bpf_clone_redirect",
GetCurrentPIDTGID: "bpf_get_current_pid_tgid",
GetCurrentUIDGID: "bpf_get_current_uid_gid",
GetCurrentComm: "bpf_get_current_comm",
GetCGroupClassID: "bpf_get_cgroup_classid",
SKBVLanPush: "bpf_skb_vlan_push",
SKBVLanPop: "bpf_skb_vlan_pop",
SKBGetTunnelKey: "bpf_skb_get_tunnel_key",
SKBSetTunnelKey: "bpf_skb_set_tunnel_key",
PerfEventRead: "bpf_perf_event_read",
Redirect: "bpf_redirect",
GetRouteRealm: "bpf_get_route_realm",
PerfEventOutput: "bpf_perf_event_output",
SKBLoadBytes: "bpf_skb_load_bytes",
GetStackID: "bpf_get_stackid",
CSumDiff: "bpf_csum_diff",
SKBGetTunnelOpt: "bpf_skb_get_tunnel_opt",
SKBSetTunnelOpt: "bpf_skb_set_tunnel_opt",
SKBChangeProto: "bpf_skb_change_proto",
SKBChangeType: "bpf_skb_change_type",
SKBUnderCGroup: "bpf_skb_under_cgroup",
GetHashRecalc: "bpf_get_hash_recalc",
GetCurrentTask: "bpf_get_current_task",
ProbeWriteUser: "bpf_probe_write_user",
CurrentTaskUnderCGroup: "bpf_current_task_under_cgroup",
SKBChangeTail: "bpf_skb_change_tail",
SKBPullData: "bpf_skb_pull_data",
CSumUpdate: "bpf_csum_update",
SetHashInvalid: "bpf_set_hash_invalid",
GetNUMANodeID: "bpf_get_numa_node_id",
SKBChangeHEad: "bpf_skb_change_head",
XDPAdjustHead: "bpf_xdp_adjust_head",
ProbeReadStr: "bpf_probe_read_str",
GetSocketCookie: "bpf_get_socket_cookie",
GetSocketUID: "bpf_get_socket_uid",
SetHash: "bpf_set_hash",
SetSockopt: "bpf_setsockopt",
SKBAdjustRoom: "bpf_skb_adjust_room",
RedirectMap: "bpf_redirect_map",
SKRedirectMap: "bpf_sk_redirect_map",
SockMapUpdate: "bpf_sock_map_update",
XDPAdjustMeta: "bpf_xdp_adjust_meta",
PerfEventReadValue: "bpf_perf_event_read_value",
PerfProgReadValue: "bpf_perf_prog_read_value",
GetSockopt: "bpf_getsockopt",
OverrideReturn: "bpf_override_return",
SockOpsCBFlagsSet: "bpf_sock_ops_cb_flags_set",
MsgRedirectMap: "bpf_msg_redirect_map",
MsgApplyBytes: "bpf_msg_apply_bytes",
MsgCorkBytes: "bpf_msg_cork_bytes",
MsgPullData: "bpf_msg_pull_data",
Bind: "bpf_bind",
XDPAdjustTail: "bpf_xdp_adjust_tail",
SKBGetXFRMState: "bpf_skb_get_xfrm_state",
GetStack: "bpf_get_stack",
SKBLoadBytesRelative: "bpf_skb_load_bytes_relative",
FibLookup: "bpf_fib_lookup",
SockHashUpdate: "bpf_sock_hash_update",
MsgRedirectHash: "bpf_msg_redirect_hash",
SKRedirectHash: "bpf_sk_redirect_hash",
LWTPushEncap: "bpf_lwt_push_encap",
LWTSeg6StoreBytes: "bpf_lwt_seg6_store_bytes",
LWTSeg6AdjustSRH: "bpf_lwt_seg6_adjust_srh",
LWTSeg6Action: "bpf_lwt_seg6_action",
RCRepeat: "bpf_rc_repeat",
RCKeydown: "bpf_rc_keydown",
SKBCGroupID: "bpf_skb_cgroup_id",
GetCurrentCGroupID: "bpf_get_current_cgroup_id",
GetLocalStorage: "bpf_get_local_storage",
SKSelectReuseport: "bpf_sk_select_reuseport",
SKBAncestorCGroupID: "bpf_skb_ancestor_cgroup_id",
SKLookupTCP: "bpf_sk_lookup_tcp",
SKLookupUDP: "bpf_sk_lookup_udp",
SKRelease: "bpf_sk_release",
MapPushElem: "bpf_map_push_elem",
MapPopElem: "bpf_map_pop_elem",
MapPeekElem: "bpf_map_peek_elem",
MsgPushData: "bpf_msg_push_data",
}
// MaxInstructions is the maximum number of instructions in a BPF or eBPF program.
const MaxInstructions = 4096
// Instruction is an eBPF instruction.
//
// Note that Instruction does not pack the destination and source registers
// into a single 8 bit field, as the kernel ABI demands. This means that
// Instruction values are not suitable for loading into the kernel.
type Instruction struct {
Opcode Opcode
Dst Register
Src Register
Off int16
Imm int32
}
func (ins Instruction) pack(bo binary.ByteOrder) instruction {
i := instruction{
Opcode: uint8(ins.Opcode),
Off: ins.Off,
Imm: ins.Imm,
}
switch bo {
case binary.LittleEndian:
i.Registers = uint8(ins.Src<<4) | uint8(ins.Dst)
case binary.BigEndian:
i.Registers = uint8(ins.Dst<<4) | uint8(ins.Src)
default:
panic("ebpf: bad byte order: want binary.LittleEndian or binary.BigEndian")
}
return i
}
// instruction is an assembled eBPF instruction, suitable for passing
// into the Linux kernel.
type instruction struct {
Opcode uint8
Registers uint8
Off int16
Imm int32
}
func (i instruction) unpack(bo binary.ByteOrder) Instruction {
ins := Instruction{
Opcode: Opcode(i.Opcode),
Off: i.Off,
Imm: i.Imm,
}
switch bo {
case binary.LittleEndian:
ins.Dst = Register(i.Registers & 0x0f)
ins.Src = Register(i.Registers >> 4)
case binary.BigEndian:
ins.Dst = Register(i.Registers >> 4)
ins.Src = Register(i.Registers & 0x0f)
default:
panic("ebpf: bad byte order: want binary.LittleEndian or binary.BigEndian")
}
return ins
}
// InstructionStream is a stream of eBPF instructions. The zero value is an
// empty InstructionStream which assembles instructions in host byte order.
//
// After instructions on 32 bit subregisters, the destination register is
// zero extended into 64 bits.
//
// Comments on InstructionStream methods which emit instructions may contain
// pseudocode that loosely describes the semantics of the instruction. The
// conventions are the following:
//
// "$sym" means the value represented by the symbol, after it is resolved.
//
// "uintsz" represents an unsigned integer, with size given by the sz
// parameter.
type InstructionStream struct {
// ByteOrder is the byte order to produce instructions for.
//
// If it is nil, it defaults to the host byte order.
//
// If set, it must be one of binary.LittleEndian or binary.BigEndian,
// otherwise method calls on the InstructionStream will panic.
ByteOrder binary.ByteOrder
insns []instruction
mapSyms map[string][]int
imm64Syms map[string][]int
imm32Syms map[string][]int
usesSymbols bool
resolved bool
}
func (s *InstructionStream) empty() bool {
return len(s.insns) == 0
}
func (s *InstructionStream) hasUnresolvedSymbols() bool {
if s.usesSymbols {
return !s.resolved
}
return false
}
func (s *InstructionStream) instructions() []instruction {
// Make a copy, to avoid aliasing surprises.
insns := make([]instruction, len(s.insns))
copy(insns, s.insns)
return insns
}
func (s *InstructionStream) byteOrder() binary.ByteOrder {
if s.ByteOrder != nil {
return s.ByteOrder
}
return hostByteOrder
}
// PrintTo prints the instruction stream in textual form to w.
func (s *InstructionStream) PrintTo(w io.Writer) error {
sew := &stickyErrorWriter{w: w}
for index, ins := range s.insns {
s.printInstruction(sew, index, ins)
if index < len(s.insns)-1 {
io.WriteString(sew, "\n")
}
}
return sew.err
}
func (s *InstructionStream) printInstruction(w io.Writer, index int, rawins instruction) {
var bo binary.ByteOrder
if s.ByteOrder == nil {
bo = hostByteOrder
}
ins := rawins.unpack(bo)
switch class := ins.Opcode.Class(); class {
case ALU, ALU64:
opstr := ins.Opcode.ALUOp().String() // "add"
if class == ALU64 {
opstr += "64" // "add64"
} else {
opstr += "32" // "add32"
}
opstr += "\t" + ins.Dst.String() + ", " // "add64 r1, "
if ins.Opcode.SourceOperand() == X {
opstr += ins.Src.String() // "add64 r1, r3"
} else {
// Symbolic or direct immediate. Find out which.
if sym := s.symbol(index); sym == "" {
opstr += "#" + strconv.Itoa(int(ins.Imm)) // "add64 r1, #128"
} else {
opstr += "$" + sym // "add64 r1, $offset"
}
}
io.WriteString(w, opstr)
case JMP:
cond := ins.Opcode.JumpCond()
switch cond {
case CALL:
// "call bpf_probe_read"
fmt.Fprintf(w, "call\t%s", KernelFunc(ins.Imm).String())
return
case EXIT:
// "exit"
io.WriteString(w, cond.String())
return
}
opstr := cond.String() + "\t" // "jeq "
opstr += ins.Dst.String() + ", " // "jeq r1, "
if ins.Opcode.SourceOperand() == X {
opstr += ins.Src.String() + ", " // "jeq r1, r2, "
} else {
if sym := s.symbol(index); sym == "" {
opstr += "#" + strconv.Itoa(int(ins.Imm)) // jeq r1, #128"
} else {
opstr += "$" + sym // "jeq r1, $proto"
}
opstr += ", " // "jeq r1, $proto, "
}
if ins.Off >= 0 {
opstr += "+" // "jeq r1, #128, +"
}
opstr += strconv.Itoa(int(ins.Off)) // "jeq r1, #128, +2"
io.WriteString(w, opstr)
case ST, STX:
opstr := class.String() + ins.Opcode.Size().String() + "\t[" // "sth ["
opstr += ins.Dst.String() // "sth [r1"
if ins.Off >= 0 {
opstr += "+" // "sth [r1+"
}
opstr += strconv.Itoa(int(ins.Off)) + "], " // "sth [r1+24], "
if class == ST {
if sym := s.symbol(index); sym == "" {
opstr += "#" + strconv.Itoa(int(ins.Imm)) // "sth [r1+24], #42"
} else {
opstr += "$" + sym // "sth [r1+24], $something"
}
} else {
opstr += ins.Src.String() // "stxw [r1+24], r3"
}
io.WriteString(w, opstr)
}
}
func (s *InstructionStream) symbol(index int) string {
symbolMaps := []map[string][]int{
s.mapSyms,
s.imm64Syms,
s.imm32Syms,
}
for _, symbolMap := range symbolMaps {
for sym, indexes := range symbolMap {
for _, symindex := range indexes {
if index == symindex {
return sym
}
}
}
}
return ""
}
type stickyErrorWriter struct {
w io.Writer
err error
}
func (sew *stickyErrorWriter) Write(p []byte) (int, error) {
if sew.err != nil {
return 0, sew.err
}
n, err := sew.w.Write(p)
sew.err = err
return n, err
}
// Raw emits a raw instruction.
func (s *InstructionStream) Raw(ins Instruction) {
s.insns = append(s.insns, ins.pack(s.byteOrder()))
}
// RawSym emits a raw instruction with a symbolic 32 bit immediate. ins.Imm is ignored.
func (s *InstructionStream) RawSym(ins Instruction, sym string) {
// We ignore ins.Imm, but there is no need to overwrite it here,
// or do anything else to it. If sym does not resolve, we can't load
// the program anyway.
s.Raw(ins)
s.addImm32Sym(sym, len(s.insns)-1)
}
// 64 bit MOVs and ALU operations.
func alu64Opcode(op ALUOp, operand SourceOperand) Opcode {
return Opcode(ALU64) | Opcode(op) | Opcode(operand)
}
// Mov64Reg emits a move on 64 bit registers.
//
// dst = src
func (s *InstructionStream) Mov64Reg(dst, src Register) {
s.Raw(Instruction{
Opcode: alu64Opcode(MOV, X),
Dst: dst,
Src: src,
})
}
// Mov64Imm emits a 64 bit move of a 32 bit immediate into a register.
//
// dst = imm
func (s *InstructionStream) Mov64Imm(dst Register, imm int32) {
s.Raw(Instruction{
Opcode: alu64Opcode(MOV, K),
Dst: dst,
Imm: imm,
})
}
// Mov64Sym emits a 64 bit move of a 32 bit symbolic immediate into
// a register.
//
// dst = $sym
func (s *InstructionStream) Mov64Sym(dst Register, sym string) {
s.RawSym(Instruction{
Opcode: alu64Opcode(MOV, K),
Dst: dst,
}, sym)
}
// ALU64Reg emits a 64 bit ALU operation on registers.
//
// dst = dst <op> src
func (s *InstructionStream) ALU64Reg(op ALUOp, dst, src Register) {
s.Raw(Instruction{
Opcode: alu64Opcode(op, X),
Dst: dst,
Src: src,
})
}
// ALU64Imm emits a 64 bit ALU instruction on a register and a 32 bit
// immediate.
//
// dst = dst <op> imm
func (s *InstructionStream) ALU64Imm(op ALUOp, dst Register, imm int32) {
s.Raw(Instruction{
Opcode: alu64Opcode(op, K),
Dst: dst,
Imm: imm,
})
}
// ALU64Sym emits a 64 bit ALU instruction on a register and a 32 bit
// symbolic immediate.
//
// dst = dst <op> $sym
func (s *InstructionStream) ALU64Sym(op ALUOp, dst Register, sym string) {
s.RawSym(Instruction{
Opcode: alu64Opcode(op, K),
Dst: dst,
}, sym)
}
// 32 bit MOVs and ALU operations
func alu32Opcode(op ALUOp, operand SourceOperand) Opcode {
return Opcode(ALU) | Opcode(op) | Opcode(operand)
}
// Mov32Reg emits a move on 32 bit subregisters.
//
// dst = int32(src)
func (s *InstructionStream) Mov32Reg(dst, src Register) {
s.Raw(Instruction{
Opcode: alu32Opcode(MOV, X),
Dst: dst,
Src: src,
})
}
// Mov32Imm emits a move of a 32 bit immediate into a register.
//
// dst = imm
func (s *InstructionStream) Mov32Imm(dst Register, imm int32) {
s.Raw(Instruction{
Opcode: alu32Opcode(MOV, K),
Dst: dst,
Imm: imm,
})
}
// Mov32Sym emits a move of a symbolic 32 bit immediate into a
// register.
//
// dst = $sym
func (s *InstructionStream) Mov32Sym(dst Register, sym string) {
s.RawSym(Instruction{
Opcode: alu32Opcode(MOV, K),
Dst: dst,
}, sym)
}
// ALU32Reg emits a 32 bit ALU operation on registers.
//
// dst = dst <op> src
func (s *InstructionStream) ALU32Reg(op ALUOp, dst, src Register) {
s.Raw(Instruction{
Opcode: alu32Opcode(op, X),
Dst: dst,
Src: src,
})
}
// ALU32Imm emits a 32 bit ALU instruction on a register and a 32 bit
// immediate.
//
// dst = int32(dst) <op> imm
func (s *InstructionStream) ALU32Imm(op ALUOp, dst Register, imm int32) {
s.Raw(Instruction{
Opcode: alu32Opcode(op, K),
Dst: dst,
Imm: imm,
})
}
// ALU32Sym emits a 32 bit ALU instruction on a register and a 32 bit
// symbolic immediate.
//
// dst = int32(dst) <op> $sym
func (s *InstructionStream) ALU32Sym(op ALUOp, dst Register, sym string) {
s.RawSym(Instruction{
Opcode: alu32Opcode(op, K),
Dst: dst,
}, sym)
}
// Memory loads and stores.
func memOpcode(class Class, size Size, mode Mode) Opcode {
return Opcode(class) | Opcode(size) | Opcode(mode)
}
// MemLoad emids a memory load.
//
// dst = *(uintsz *)(src + off)
func (s *InstructionStream) MemLoad(sz Size, dst, src Register, off int16) {
s.Raw(Instruction{
Opcode: memOpcode(LDX, sz, MEM),
Dst: dst,
Src: src,
Off: off,
})
}
// MemStoreReg emits a memory store from a register.
//
// *(uintsz *)(dst + off) = src
func (s *InstructionStream) MemStoreReg(sz Size, dst, src Register, off int16) {
s.Raw(Instruction{
Opcode: memOpcode(STX, sz, MEM),
Dst: dst,
Src: src,
Off: off,
})
}
// MemStoreImm emits a memory store from a 32 bit immediate.