-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbpf-translate.cxx
5142 lines (4523 loc) · 165 KB
/
bpf-translate.cxx
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
// bpf translation pass
// Copyright (C) 2016-2021 Red Hat Inc.
//
// This file is part of systemtap, and is free software. You can
// redistribute it and/or modify it under the terms of the GNU General
// Public License (GPL); either version 2, or (at your option) any
// later version.
#include "config.h"
#include "bpf-internal.h"
#include "parse.h"
#include "staptree.h"
#include "elaborate.h"
#include "session.h"
#include "translator-output.h"
#include "tapsets.h"
#include <sstream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
extern "C" {
#include <libelf.h>
/* Unfortunately strtab manipulation functions were only officially added
to elfutils libdw in 0.167. Before that there were internal unsupported
ebl variants. While libebl.h isn't supported we'll try to use it anyway
if the elfutils we build against is too old. */
#include <elfutils/version.h>
#if _ELFUTILS_PREREQ (0, 167)
#include <elfutils/libdwelf.h>
typedef Dwelf_Strent Stap_Strent;
typedef Dwelf_Strtab Stap_Strtab;
#define stap_strtab_init dwelf_strtab_init
#define stap_strtab_add(X,Y) dwelf_strtab_add(X,Y)
#define stap_strtab_free dwelf_strtab_free
#define stap_strtab_finalize dwelf_strtab_finalize
#define stap_strent_offset dwelf_strent_off
#else
#include <elfutils/libebl.h>
typedef Ebl_Strent Stap_Strent;
typedef Ebl_Strtab Stap_Strtab;
#define stap_strtab_init ebl_strtabinit
#define stap_strtab_add(X,Y) ebl_strtabadd(X,Y,0)
#define stap_strtab_free ebl_strtabfree
#define stap_strtab_finalize ebl_strtabfinalize
#define stap_strent_offset ebl_strtaboffset
#endif
#include <linux/version.h>
#include <asm/ptrace.h>
}
// XXX: Required static data and methods from bpf::globals, shared with stapbpf.
#include "bpf-shared-globals.h"
#ifndef EM_BPF
#define EM_BPF 0xeb9f
#endif
#ifndef R_BPF_MAP_FD
#define R_BPF_MAP_FD 1
#endif
std::string module_name;
namespace bpf {
struct side_effects_visitor : public expression_visitor
{
bool side_effects;
side_effects_visitor() : side_effects(false) { }
void visit_expression(expression *) { }
void visit_pre_crement(pre_crement *) { side_effects = true; }
void visit_post_crement(post_crement *) { side_effects = true; }
void visit_assignment (assignment *) { side_effects = true; }
void visit_functioncall (functioncall *) { side_effects = true; }
void visit_print_format (print_format *) { side_effects = true; }
void visit_stat_op (stat_op *) { side_effects = true; }
void visit_hist_op (hist_op *) { side_effects = true; }
};
struct init_block : public ::block
{
// This block contains statements that initialize global variables
// with default values. It should be visited first among any
// begin probe bodies. Note that initialization of internal globals
// (ex. the exit status) is handled by the stapbpf runtime.
init_block(globals &glob);
~init_block();
bool empty() { return this->statements.empty(); }
};
init_block::init_block(globals &glob)
{
for (auto i = glob.globals.begin(); i != glob.globals.end(); ++i)
{
struct vardecl *v = i->first;
if (v->init && v->type == pe_long)
{
struct literal_number *num = static_cast<literal_number *>(v->init);
struct symbol *sym = new symbol;
struct assignment *asgn = new assignment;
struct expr_statement *stmt = new expr_statement;
sym->referent = v;
asgn->type = pe_long;
asgn->op = "=";
asgn->left = sym;
asgn->right = num;
stmt->value = asgn;
this->statements.push_back(stmt);
}
}
}
init_block::~init_block()
{
for (auto i = this->statements.begin(); i != this->statements.end(); ++i)
{
struct expr_statement *stmt = static_cast<expr_statement *>(*i);
struct assignment *asgn = static_cast<assignment *>(stmt->value);
struct symbol *sym = static_cast<symbol *>(asgn->left);
// referent and right are not owned by this.
sym->referent = NULL;
asgn->right = NULL;
delete sym;
delete asgn;
delete stmt;
}
}
static bool
has_side_effects (expression *e)
{
side_effects_visitor t;
e->visit (&t);
return t.side_effects;
}
/* forward declarations */
struct asm_stmt;
struct bpf_unparser : public throwing_visitor
{
// The visitor class isn't as helpful as it might be. As a consequence,
// the RESULT member is set after visiting any expression type. Use the
// emit_expr helper to return the result properly.
value *result;
// The program into which we are emitting code.
program &this_prog;
globals &glob;
value *this_in_arg0 = NULL;
// The "current" block into which we are currently emitting code.
insn_append_inserter this_ins;
void set_block(block *b)
{ this_ins.b = b; this_ins.i = b->last; }
void clear_block()
{ this_ins.b = NULL; this_ins.i = NULL; }
bool in_block() const
{ return this_ins.b != NULL; }
// Destinations for "break", "continue", and "return" respectively.
std::vector<block *> loop_break;
std::vector<block *> loop_cont;
std::vector<block *> func_return;
std::vector<value *> func_return_val;
std::vector<functiondecl *> func_calls;
// Used to track errors.
value *error_status;
// Used to switch execution of program to catch blocks.
std::vector<block *> catch_jump;
std::vector<value *> catch_msg;
// Contains the mapping for resource constraints set by -D.
std::map<std::string, int> constraints;
// Local variable declarations.
typedef std::unordered_map<vardecl *, value *> locals_map;
locals_map *this_locals;
// Return 0.
block *ret0_block;
block *exit_block;
block *get_ret0_block();
block *get_exit_block();
// TODO General triage of bpf-possible functionality:
virtual void visit_embeddedcode (embeddedcode *s);
virtual void visit_try_block (try_block* s);
virtual void visit_block (::block *s);
virtual void visit_null_statement (null_statement *s);
virtual void visit_expr_statement (expr_statement *s);
virtual void visit_if_statement (if_statement* s);
virtual void visit_for_loop (for_loop* s);
virtual void visit_foreach_loop (foreach_loop* s);
virtual void visit_return_statement (return_statement* s);
virtual void visit_delete_statement (delete_statement* s);
virtual void visit_next_statement (next_statement* s);
virtual void visit_break_statement (break_statement* s);
virtual void visit_continue_statement (continue_statement* s);
virtual void visit_literal_string (literal_string *e);
virtual void visit_literal_number (literal_number* e);
// TODO visit_embedded_expr -> UNHANDLED, could treat as embedded_code
virtual void visit_binary_expression (binary_expression* e);
virtual void visit_unary_expression (unary_expression* e);
virtual void visit_pre_crement (pre_crement* e);
virtual void visit_post_crement (post_crement* e);
virtual void visit_logical_or_expr (logical_or_expr* e);
virtual void visit_logical_and_expr (logical_and_expr* e);
virtual void visit_array_in (array_in* e);
// ??? visit_regex_query -> UNHANDLED, requires new kernel functionality
virtual void visit_compound_expression (compound_expression *e);
virtual void visit_comparison (comparison* e);
// TODO visit_concatenation for kernel probes -> (2) pseudo-LOOP: copy the
// strings while concatenating
virtual void visit_concatenation (concatenation* e);
virtual void visit_ternary_expression (ternary_expression* e);
virtual void visit_assignment (assignment* e);
virtual void visit_symbol (symbol* e);
virtual void visit_target_register (target_register* e);
virtual void visit_target_deref (target_deref* e);
// visit_target_bitfield -> ?? should already be handled in earlier pass?
// visit_target_symbol -> ?? should already be handled in earlier pass
virtual void visit_arrayindex (arrayindex *e);
virtual void visit_functioncall (functioncall* e);
virtual void visit_print_format (print_format* e);
virtual void visit_stat_op (stat_op* e);
virtual void visit_hist_op (hist_op* e);
// visit_atvar_op -> ?? should already be handled in earlier pass
// visit_cast_op -> ?? should already be handled in earlier pass
// visit_autocast_op -> ?? should already be handled in earlier pass
// visit_defined_op -> ?? should already be handled in earlier pass
// visit_entry_op -> ?? should already be handled in earlier pass
// visit_perf_op -> ?? should already be handled in earlier pass
// TODO: Other bpf functionality to take advantage of in tapsets, or as alternate implementations:
// - backtrace.stp :: BPF_MAP_TYPE_STACKTRACE + bpf_getstackid
// - BPF_MAP_TYPE_LRU_HASH :: for size-limited maps
// - BPF_MAP_GET_NEXT_KEY :: for user-space iteration through maps
// see https://ferrisellis.com/posts/ebpf_syscall_and_maps/#ebpf-map-types
void emit_stmt(statement *s);
void emit_mov(value *d, value *s);
void emit_jmp(block *b);
void emit_cond(expression *e, block *t, block *f);
void emit_statmap_lookup(value *dest, globals::map_idx map_id, value *idx);
void emit_statmap_update(globals::map_idx map_id, value *idx,
int idx_ofs, value *val);
void emit_aggregation(vardecl *var, globals::map_slot& g, value *val,
value *idx = NULL, int idx_ofs = 0);
void emit_store(expression *dest, value *src);
value *emit_expr(expression *e);
value *emit_bool(expression *e);
value *emit_context_var(bpf_context_vardecl *v);
void emit_transport_msg(globals::perf_event_type msg,
value *arg = NULL, exp_type format_type = pe_unknown);
value *emit_functioncall(functiondecl *f, const std::vector<value *> &args);
value *emit_print_format(const std::string &format,
const std::vector<value *> &actual,
bool print_to_stream = true,
const token *tok = NULL);
// Used for the embedded-code assembler:
int64_t parse_imm (const asm_stmt &stmt, const std::string &str);
size_t parse_asm_stmt (embeddedcode *s, size_t start,
/*OUT*/asm_stmt &stmt);
value *emit_asm_arg(const asm_stmt &stmt, const std::string &arg,
bool allow_imm = true, bool allow_emit = true);
value *emit_asm_reg(const asm_stmt &stmt, const std::string ®);
value *get_asm_reg(const asm_stmt &stmt, const std::string ®);
void emit_asm_opcode(const asm_stmt &stmt,
std::map<std::string, block *> label_map);
// Used for the embedded-code assembler's diagnostics:
source_loc adjusted_loc;
size_t adjust_pos;
std::vector<token *> adjusted_toks; // track for delayed deallocation
// Used for string data:
value *emit_literal_string(const std::string &str, const token *tok);
value *emit_string_copy(value *dest, int ofs, value *src, bool zero_pad = false);
// Used for passing long and string arguments on the stack where an address is expected:
void emit_long_arg(value *arg, int ofs, value *val);
void emit_str_arg(value *arg, int ofs, value *str);
void add_prologue();
void add_epilogue();
locals_map *new_locals(const std::vector<vardecl *> &);
bpf_unparser (program &c, globals &g);
virtual ~bpf_unparser ();
};
bpf_unparser::bpf_unparser(program &p, globals &g)
: throwing_visitor ("unhandled statement or expression type"),
result(NULL), this_prog(p), glob(g), this_locals(NULL),
ret0_block(NULL), exit_block(NULL)
{
// If there are any resource constraints set with -D, we populate
// them into a map (as we cannot use macros in stapbpf).
for (std::string macro: glob.session->c_macros)
{
// Example: MAXERRORS=3
size_t delim = macro.find('=');
std::string option = macro.substr(0, delim);
int limit = std::stoi(macro.substr(delim + 1));
// Negative limits become 0.
if (limit < 0)
limit = 0;
constraints[option] = limit;
}
}
bpf_unparser::~bpf_unparser()
{
// TODO: Need to delay this deallocation even further for error reporting.
//for (std::vector<token *>::iterator it = adjusted_toks.begin();
// it != adjusted_toks.end(); it++)
// delete *it;
delete this_locals;
}
bpf_unparser::locals_map *
bpf_unparser::new_locals(const std::vector<vardecl *> &vars)
{
locals_map *m = new locals_map;
for (std::vector<vardecl *>::const_iterator i = vars.begin ();
i != vars.end (); ++i)
{
const locals_map::value_type v (*i, this_prog.new_reg());
auto ok = m->insert (v);
assert (ok.second);
}
return m;
}
block *
bpf_unparser::get_exit_block()
{
if (exit_block)
return exit_block;
block* cont = this_ins.get_block();
block* exit = this_prog.new_block();
set_block(exit);
add_epilogue();
this_prog.mk_exit(this_ins);
set_block(cont);
exit_block = exit;
return exit;
}
block *
bpf_unparser::get_ret0_block()
{
if (ret0_block)
return ret0_block;
block *b = this_prog.new_block();
insn_append_inserter ins(b, "ret0_block");
this_prog.mk_mov(ins, this_prog.lookup_reg(BPF_REG_0), this_prog.new_imm(0));
b->fallthru = new edge(b, get_exit_block());
ret0_block = b;
return b;
}
void
bpf_unparser::emit_stmt(statement *s)
{
if (s)
s->visit (this);
}
value *
bpf_unparser::emit_expr(expression *e)
{
e->visit (this);
value *v = result;
result = NULL;
return v;
}
void
bpf_unparser::emit_mov(value *d, value *s)
{
this_prog.mk_mov(this_ins, d, s);
}
void
bpf_unparser::emit_jmp(block *b)
{
// Begin by hoping that we can simply place the destination as fallthru.
// If this assumption doesn't hold, it'll be fixed by reorder_blocks.
assert(in_block());
block *this_block = this_ins.get_block ();
this_block->fallthru = new edge(this_block, b);
clear_block ();
}
void
bpf_unparser::emit_cond(expression *e, block *t_dest, block *f_dest)
{
condition cond;
value *s0, *s1;
// Look for and handle logical operators first.
if (logical_or_expr *l = dynamic_cast<logical_or_expr *>(e))
{
block *cont_block = this_prog.new_block ();
emit_cond (l->left, t_dest, cont_block);
set_block (cont_block);
emit_cond (l->right, t_dest, f_dest);
return;
}
if (logical_and_expr *l = dynamic_cast<logical_and_expr *>(e))
{
block *cont_block = this_prog.new_block ();
emit_cond (l->left, cont_block, f_dest);
set_block (cont_block);
emit_cond (l->right, t_dest, f_dest);
return;
}
if (unary_expression *u = dynamic_cast<unary_expression *>(e))
if (u->op == "!")
{
emit_cond (u->operand, f_dest, t_dest);
return;
}
// What is left must generate a comparison + conditional branch.
if (comparison *c = dynamic_cast<comparison *>(e))
{
s0 = emit_expr (c->left);
s1 = emit_expr (c->right);
if (c->op == "==")
cond = EQ;
else if (c->op == "!=")
cond = NE;
else if (c->op == "<")
cond = LT;
else if (c->op == "<=")
cond = LE;
else if (c->op == ">")
cond = GT;
else if (c->op == ">=")
cond = GE;
else
throw SEMANTIC_ERROR (_("unhandled comparison operator"), e->tok);
}
else
{
binary_expression *bin = dynamic_cast<binary_expression *>(e);
if (bin && bin->op == "&")
{
s0 = emit_expr (bin->left);
s1 = emit_expr (bin->right);
cond = TEST;
}
else
{
// Fall back to E != 0.
s0 = emit_expr (e);
s1 = this_prog.new_imm(0);
cond = NE;
}
}
this_prog.mk_jcond (this_ins, cond, s0, s1, t_dest, f_dest);
clear_block ();
}
value *
bpf_unparser::emit_bool (expression *e)
{
block *else_block = this_prog.new_block ();
block *join_block = this_prog.new_block ();
value *r = this_prog.new_reg();
emit_mov (r, this_prog.new_imm(1));
emit_cond (e, join_block, else_block);
set_block (else_block);
emit_mov (r, this_prog.new_imm(0));
emit_jmp (join_block);
set_block(join_block);
return r;
}
/* PR23476: Helpers for loading/storing long values in a stat field map.
Several of these map operations are issued for each stats operation,
so we avoid code duplication by taking an index already on the stack.
??? These helpers could be used in other contexts than just stats. */
void
bpf_unparser::emit_statmap_lookup(value *dest, globals::map_idx map_id, value *idx)
{
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1), map_id);
emit_mov(this_prog.lookup_reg(BPF_REG_2), idx); // XXX idx stored by caller
this_prog.mk_call(this_ins, BPF_FUNC_map_lookup_elem, 2);
// Check for null pointer:
value *r0 = this_prog.lookup_reg(BPF_REG_0);
value *i0 = this_prog.new_imm(0);
block *cont_block = this_prog.new_block();
block *join_block = this_prog.new_block();
emit_mov(dest, i0); // default to a result of 0
this_prog.mk_jcond(this_ins, EQ, r0, i0, join_block, cont_block);
set_block(cont_block);
this_prog.mk_ld(this_ins, BPF_DW, dest, r0, 0);
emit_jmp(join_block);
set_block(join_block);
}
void
bpf_unparser::emit_statmap_update(globals::map_idx map_id, value *idx,
int idx_ofs, value *val)
{
int val_ofs = idx_ofs - 8;
if ((-val_ofs) % 8 != 0) // align to double-word
val_ofs -= 8 - (-val_ofs) % 8;
this_prog.use_tmp_space(-val_ofs);
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1), map_id);
emit_mov(this_prog.lookup_reg(BPF_REG_2), idx); // XXX idx stored by caller
emit_long_arg(this_prog.lookup_reg(BPF_REG_3), val_ofs, val);
emit_mov(this_prog.lookup_reg(BPF_REG_4), this_prog.new_imm(0)); // TODO
this_prog.mk_call(this_ins, BPF_FUNC_map_update_elem, 4);
}
// XXX Based on __stap_stat_add in runtime/stat-common.c.
// There might be a clever way to avoid code duplication later,
// but right now the code format is too different. Just reimplement.
void
bpf_unparser::emit_aggregation(vardecl *var, globals::map_slot& ms,
value *val, value *idx, int idx_ofs)
{
#ifdef DEBUG_CODEGEN
this_ins.notes.push("agg");
#endif
// Obtain the correct stats_map and index:
assert (ms.is_stat());
globals::stats_map sd;
if (var->arity == 0)
{
assert (ms.is_scalar() && idx == NULL);
sd = glob.scalar_stats;
// idx is an offset into scalar stat field maps, store on the stack
value *frame = this_prog.lookup_reg(BPF_REG_10);
idx_ofs = -4; // BPF_W
this_prog.mk_st(this_ins, BPF_W, frame, idx_ofs,
this_prog.new_imm(ms.idx));
this_prog.use_tmp_space(-idx_ofs);
idx = this_prog.new_reg();
this_prog.mk_binary(this_ins, BPF_ADD, idx,
frame, this_prog.new_imm(idx_ofs));
}
else // var->arity > 0
{
assert (!ms.is_scalar());
assert (var->arity > 0 && idx != NULL);
auto it = glob.array_stats.find(var);
assert (it != glob.array_stats.end()); // XXX: should check earlier
sd = it->second;
// idx is a value stored on the stack
}
for (auto f : globals::stat_fields)
assert(sd.find(f) != sd.end());
// TODO PR23476: Emit simplified code for now.
//
// ??? lock stat
// if (idx not in sd[stat_iter_field] || sd->count == 0) {
// sd->count = 1;
// sd->sum = val;
// } else {
// if(stat_op_count) sd->count++;
// if(stat_op_sum) sd->sum += val;
// }
// ??? unlock stat
block *then_block = this_prog.new_block ();
block *else_block = this_prog.new_block ();
block *join_block = this_prog.new_block ();
value *tmp = this_prog.new_reg();
emit_statmap_lookup(tmp, sd["count"], idx);
this_prog.mk_jcond (this_ins, EQ, tmp, this_prog.new_imm(0),
then_block, else_block);
set_block (then_block);
emit_statmap_update(sd["count"], idx, idx_ofs, this_prog.new_imm(1));
emit_statmap_update(sd["sum"], idx, idx_ofs, val);
emit_jmp (join_block);
set_block (else_block);
if (1) // TODO: if (stat_op_count)
{
emit_statmap_lookup(tmp, sd["count"], idx);
this_prog.mk_binary(this_ins, BPF_ADD, tmp, tmp, this_prog.new_imm(1));
emit_statmap_update(sd["count"], idx, idx_ofs, tmp);
}
if (1) // TODO: if (stat_op_sum)
{
emit_statmap_lookup(tmp, sd["sum"], idx);
this_prog.mk_binary(this_ins, BPF_ADD, tmp, tmp, val);
emit_statmap_update(sd["sum"], idx, idx_ofs, tmp);
}
emit_jmp (join_block);
set_block(join_block);
#ifdef DEBUG_CODEGEN
this_ins.notes.pop();
#endif
}
void
bpf_unparser::emit_store(expression *e, value *val)
{
if (symbol *s = dynamic_cast<symbol *>(e)) // scalar lvalue
{
vardecl *var = s->referent;
assert (var->arity == 0);
auto g = glob.globals.find (var);
if (g != glob.globals.end())
{
value *frame = this_prog.lookup_reg(BPF_REG_10);
int key_ofs, val_ofs;
// BPF_FUNC_map_update_elem will dereference the address
// passed in BPF_REG_3:
switch (var->type)
{
case pe_long:
// Store the long on the stack and pass its address:
val_ofs = -8;
emit_long_arg(this_prog.lookup_reg(BPF_REG_3), val_ofs, val);
break;
case pe_string:
// Zero-pad and copy the string to the stack and pass its address:
val_ofs = -BPF_MAXSTRINGLEN;
emit_str_arg(this_prog.lookup_reg(BPF_REG_3), val_ofs, val);
this_prog.use_tmp_space(BPF_MAXSTRINGLEN);
break;
case pe_stats:
// Emit separate code to update stat fields:
emit_aggregation(var, g->second, val);
return;
default:
goto err;
}
key_ofs = val_ofs - 4;
this_prog.mk_st(this_ins, BPF_W, frame, key_ofs,
this_prog.new_imm(g->second.idx));
this_prog.use_tmp_space(-key_ofs);
// XXX g->second.is_stat() handled above
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1),
g->second.map_id);
this_prog.mk_binary(this_ins, BPF_ADD,
this_prog.lookup_reg(BPF_REG_2),
frame, this_prog.new_imm(key_ofs));
emit_mov(this_prog.lookup_reg(BPF_REG_4), this_prog.new_imm(0));
this_prog.mk_call(this_ins, BPF_FUNC_map_update_elem, 4);
return;
}
auto i = this_locals->find (var);
if (i != this_locals->end ())
{
emit_mov (i->second, val);
return;
}
}
else if (arrayindex *a = dynamic_cast<arrayindex *>(e)) // array lvalue
{
if (symbol *a_sym = dynamic_cast<symbol *>(a->base))
{
vardecl *v = a_sym->referent;
int key_ofs = 0, val_ofs;
auto g = glob.globals.find(v);
if (g == glob.globals.end())
throw SEMANTIC_ERROR(_("unknown array variable"), v->tok);
unsigned element = v->arity;
// iterate over the elements
do {
--element;
value *idx = emit_expr(a->indexes[element]);
switch (v->index_types[element])
{
case pe_long:
// Store the long on the stack and pass its address:
key_ofs -= 8;
emit_long_arg(this_prog.lookup_reg(BPF_REG_2), key_ofs, idx);
break;
case pe_string:
// Zero-pad and copy the string to the stack and pass its address:
key_ofs -= BPF_MAXSTRINGLEN;
emit_str_arg(this_prog.lookup_reg(BPF_REG_2), key_ofs, idx);
break;
default:
throw SEMANTIC_ERROR(_("unhandled index type"), e->tok);
}
} while (element);
switch (v->type)
{
case pe_long:
// Store the long on the stack and pass its address:
val_ofs = key_ofs - 8;
emit_long_arg(this_prog.lookup_reg(BPF_REG_3), val_ofs, val);
break;
case pe_string:
// Zero-pad and copy the string to the stack and pass its address:
val_ofs = key_ofs - BPF_MAXSTRINGLEN;
emit_str_arg(this_prog.lookup_reg(BPF_REG_3), val_ofs, val);
this_prog.use_tmp_space(BPF_MAXSTRINGLEN);
break;
case pe_stats:
// Emit separate code to update stat fields:
{
value *idx = this_prog.new_reg();
value *frame = this_prog.lookup_reg(BPF_REG_10);
this_prog.mk_binary(this_ins, BPF_ADD, idx,
frame, this_prog.new_imm(key_ofs));
this_prog.use_tmp_space(-key_ofs);
emit_aggregation(v, g->second, val, idx, key_ofs);
}
return;
default:
throw SEMANTIC_ERROR(_("unhandled array type"), v->tok);
}
this_prog.use_tmp_space(-val_ofs);
// XXX g->second.is_stat() handled above
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1),
g->second.map_id);
emit_mov(this_prog.lookup_reg(BPF_REG_4), this_prog.new_imm(0));
this_prog.mk_call(this_ins, BPF_FUNC_map_update_elem, 4);
return;
}
}
err:
throw SEMANTIC_ERROR (_("unknown lvalue"), e->tok);
}
/* WORK IN PROGRESS: A simple eBPF assembler.
In order to effectively write eBPF tapset functions, we want to use
embedded-code assembly rather than compile from SystemTap code. At
the same time, we want to hook into stapbpf functionality to
reserve stack memory, allocate virtual registers or signal errors.
The assembler syntax will probably take a couple of attempts to get
just right. This attempt keeps things as close as possible to the
first embedded-code assembler, with a few more features and a
disgustingly lenient parser that allows things like
$ this is all one "**identifier**" believe-it!-or-not
Ahh for the days of 1960s FORTRAN.
??? It might make more sense to implement an assembler based on
the syntax used in official eBPF subsystem docs. */
/* Supported assembly statement types include:
<stmt> ::= label, <dest=label>;
<stmt> ::= alloc, <dest=reg>, <imm=imm> [, align|noalign];
<stmt> ::= call, <dest=optreg>, <param[0]=function name>, <param[1]=arg>, ...;
<stmt> ::= jump_to_catch, <param[0]=error message>;
<stmt> ::= register_error, <param[0]=error message>;
<stmt> ::= terminate;
<stmt> ::= <code=integer opcode>, <dest=reg>, <src1=reg>,
<off/jmp_target=off>, <imm=imm>;
Supported argument types include:
<arg> ::= <reg> | <imm>
<optreg> ::= <reg> | -
<reg> ::= <register index> | r<register index> | $ctx
$<identifier> | $<integer constant> | $$ | <string constant>
<imm> ::= <integer constant> | BPF_MAXSTRINGLEN | BPF_F_CURRENT_CPU | -
<off> ::= <imm> | <jump label>
*/
// #define BPF_ASM_DEBUG
struct asm_stmt {
std::string kind;
unsigned code;
std::string dest, src1;
int64_t off, imm;
// metadata for jmp instructions
// ??? The logic around these flags could be pruned a bit.
bool has_jmp_target = false;
bool has_fallthrough = false;
std::string jmp_target, fallthrough;
// metadata for call, error instructions
std::vector<std::string> params;
// metadata for alloc instructions
bool align_alloc;
token *tok;
};
std::ostream&
operator << (std::ostream& o, const asm_stmt& stmt)
{
if (stmt.kind == "label")
o << "label, " << stmt.dest << ";";
else if (stmt.kind == "opcode")
{
o << std::hex << stmt.code << ", "
<< stmt.dest << ", "
<< stmt.src1 << ", ";
if (stmt.off != 0 || stmt.jmp_target == "")
o << stmt.off;
else if (stmt.off != 0) // && stmt.jmp_target != ""
o << stmt.off << "/";
if (stmt.jmp_target != "")
o << "label:" << stmt.jmp_target;
o << ", "
<< stmt.imm << ";"
<< (stmt.has_fallthrough ? " +FALLTHROUGH " + stmt.fallthrough : "");
}
else if (stmt.kind == "alloc")
{
o << "alloc, " << stmt.dest << ", " << stmt.imm << ";";
}
else if (stmt.kind == "call")
{
o << "call, " << stmt.dest << ", ";
for (unsigned k = 0; k < stmt.params.size(); k++)
{
o << stmt.params[k];
o << (k >= stmt.params.size() - 1 ? ";" : ", ");
}
}
else
o << "<unknown asm_stmt kind '" << stmt.kind << "'>";
return o;
}
bool
is_numeric (const std::string &str)
{
size_t pos = 0;
try {
stol(str, &pos, 0);
} catch (const std::invalid_argument &e) {
return false;
} catch (const std::out_of_range &e) {
/* XXX: probably numeric but not valid; give up */
return false;
} catch (...) {
/* XXX: handle other errors the same way */
std::cerr << "BUG: bpf assembler -- is_numeric() saw unexpected exception" << std::endl;
return false;
}
return (pos == str.size());
}
int64_t
bpf_unparser::parse_imm (const asm_stmt &stmt, const std::string &str)
{
int64_t val;
if (str == "BPF_MAXSTRINGLEN")
val = BPF_MAXSTRINGLEN;
else if (str == "BPF_F_CURRENT_CPU")
val = BPF_F_CURRENT_CPU;
else if (str == "-")
val = 0;
else try {
val = stol(str, 0, 0);
} catch (std::exception &e) { // XXX: invalid_argument, out_of_range
throw SEMANTIC_ERROR (_F("invalid bpf embeddedcode operand '%s'",
str.c_str()), stmt.tok);
}
return val;
}
/* Parse an assembly statement starting from position start in code,
then write the output in stmt. Returns a position immediately after
the parsed statement. */
size_t
bpf_unparser::parse_asm_stmt (embeddedcode *s, size_t start,
/*OUT*/asm_stmt &stmt)
{
const interned_string &code = s->code;
retry:
std::vector<std::string> args;
unsigned n = code.size();
size_t pos;
bool in_comment = false;
bool in_string = false;
// ??? As before, parser is extremely non-rigorous and could do
// with some tightening in terms of the inputs it accepts.
std::string arg = "";
size_t save_start = start; // -- position for diagnostics
for (pos = start; pos < n; pos++)
{
char c = code[pos];
char c2 = pos + 1 < n ? code [pos + 1] : 0;
if (isspace(c) && !in_string)
continue; // skip
else if (in_comment)
{
if (c == '*' && c2 == '/')
++pos, in_comment = false;
// else skip
}
else if (in_string)
{
// resulting string will be processed by translate_escapes()
if (c == '"')
arg.push_back(c), in_string = false; // include quote
else if (c == '\\' && c2 == '"')
++pos, arg.push_back(c), arg.push_back(c2);
else // accept any char, including whitespace
arg.push_back(c);
}
else if (c == '/' && c2 == '*')
++pos, in_comment = true;
else if (c == '"') // found a literal string
{
if (arg.empty() && args.empty())
save_start = pos; // start of first argument
// XXX: This allows '"' inside an arg and will treat the
// string as a sequence of weird identifier characters. A
// more rigorous parser would error on mixing strings and
// regular chars.
arg.push_back(c); // include quote
in_string = true;
}
else if (c == ',') // reached end of argument
{
// XXX: This strips out empty args. A more rigorous parser would error.
if (arg != "")
args.push_back(arg);
arg = "";
}
else if (c == ';') // reached end of statement
{
// XXX: This strips out empty args. A more rigorous parser would error.
if (arg != "")
args.push_back(arg);
arg = "";
pos++; break;
}
else // found (we assume) a regular char
{
if (arg.empty() && args.empty())
save_start = pos; // start of first argument
// XXX: As before, this strips whitespace within args