forked from p4lang/behavioral-model
-
Notifications
You must be signed in to change notification settings - Fork 0
/
P4Objects.cpp
2615 lines (2284 loc) · 97.1 KB
/
P4Objects.cpp
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 2013-present Barefoot Networks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Antonin Bas (antonin@barefootnetworks.com)
*
*/
#include <bm/bm_sim/P4Objects.h>
#include <bm/bm_sim/phv.h>
#include <istream>
#include <ostream>
#include <string>
#include <tuple>
#include <vector>
#include <set>
#include <exception>
#include "jsoncpp/json.h"
#include "crc_map.h"
namespace bm {
using std::unique_ptr;
using std::string;
namespace {
constexpr int required_major_version = 2;
constexpr int max_minor_version = 12;
// not needed for now
// constexpr int min_minor_version = 0;
std::string get_version_str(int major, int minor) {
return std::to_string(major) + "." + std::to_string(minor);
}
template <typename T,
typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
T hexstr_to_int(const std::string &hexstr) {
// TODO(antonin): temporary trick to avoid code duplication
return Data(hexstr).get<T>();
}
class json_exception : public std::exception {
public:
json_exception(const std::string &error_string, const Json::Value &json_value)
: error_string(error_string), json_value(json_value), with_json(true) { }
explicit json_exception(const std::string &error_string)
: error_string(error_string) { }
const std::string msg(bool verbose) const {
std::string verbose_string(error_string);
if (verbose && with_json) {
verbose_string += std::string("\nbad json:\n");
verbose_string += json_value.toStyledString();
}
verbose_string += std::string("\n");
return verbose_string;
}
const char *what() const noexcept override {
return error_string.c_str();
}
private:
std::string error_string;
Json::Value json_value{};
bool with_json{false};
};
// Inspired from
// http://stackoverflow.com/questions/12261915/howto-throw-stdexceptions-with-variable-messages
class ExceptionFormatter {
public:
ExceptionFormatter() = default;
template <typename Type>
ExceptionFormatter &operator <<(const Type &value) {
stream_ << value;
return *this;
}
std::string str() const { return stream_.str(); }
// implicit conversion to string
operator std::string() const { return stream_.str(); }
ExceptionFormatter(const ExceptionFormatter &other) = delete;
ExceptionFormatter &operator=(const ExceptionFormatter &other) = delete;
ExceptionFormatter(ExceptionFormatter &&other) = delete;
ExceptionFormatter &operator=(ExceptionFormatter &&other) = delete;
private:
std::stringstream stream_{};
};
using EFormat = ExceptionFormatter;
} // namespace
enum class P4Objects::ExprType {
UNKNOWN, DATA, HEADER, HEADER_STACK, BOOL, UNION, UNION_STACK
};
std::string
P4Objects::get_json_version_string() {
return get_version_str(required_major_version, max_minor_version);
}
void
P4Objects::build_expression(const Json::Value &json_expression,
Expression *expr) {
ExprType expr_type(ExprType::UNKNOWN);
build_expression(json_expression, expr, &expr_type);
}
namespace {
using ExprType = P4Objects::ExprType;
ExprOpcode get_eq_opcode(ExprType expr_type) {
switch (expr_type) {
case ExprType::DATA:
return ExprOpcode::EQ_DATA;
case ExprType::HEADER:
return ExprOpcode::EQ_HEADER;
case ExprType::BOOL:
return ExprOpcode::EQ_BOOL;
case ExprType::UNION:
return ExprOpcode::EQ_UNION;
default:
break;
}
assert(0);
return ExprOpcode::EQ_DATA;
}
ExprOpcode get_neq_opcode(ExprType expr_type) {
switch (expr_type) {
case ExprType::DATA:
return ExprOpcode::NEQ_DATA;
case ExprType::HEADER:
return ExprOpcode::NEQ_HEADER;
case ExprType::BOOL:
return ExprOpcode::NEQ_BOOL;
case ExprType::UNION:
return ExprOpcode::NEQ_UNION;
default:
break;
}
assert(0);
return ExprOpcode::NEQ_DATA;
}
// TODO(antonin): should this information be in expressions.h?
ExprType get_opcode_type(ExprOpcode opcode) {
switch (opcode) {
case ExprOpcode::LOAD_FIELD:
case ExprOpcode::LOAD_CONST:
case ExprOpcode::LOAD_LOCAL:
case ExprOpcode::LOAD_REGISTER_REF:
case ExprOpcode::LOAD_REGISTER_GEN:
case ExprOpcode::LOAD_LAST_HEADER_STACK_FIELD:
case ExprOpcode::ADD:
case ExprOpcode::SUB:
case ExprOpcode::MOD:
case ExprOpcode::DIV:
case ExprOpcode::MUL:
case ExprOpcode::SHIFT_LEFT:
case ExprOpcode::SHIFT_RIGHT:
case ExprOpcode::BIT_AND:
case ExprOpcode::BIT_OR:
case ExprOpcode::BIT_XOR:
case ExprOpcode::BIT_NEG:
case ExprOpcode::TWO_COMP_MOD:
case ExprOpcode::BOOL_TO_DATA:
case ExprOpcode::LAST_STACK_INDEX:
case ExprOpcode::SIZE_STACK:
case ExprOpcode::ACCESS_FIELD:
return ExprType::DATA;
case ExprOpcode::LOAD_BOOL:
case ExprOpcode::EQ_DATA:
case ExprOpcode::NEQ_DATA:
case ExprOpcode::GT_DATA:
case ExprOpcode::LT_DATA:
case ExprOpcode::GET_DATA:
case ExprOpcode::LET_DATA:
case ExprOpcode::EQ_HEADER:
case ExprOpcode::NEQ_HEADER:
case ExprOpcode::EQ_UNION:
case ExprOpcode::NEQ_UNION:
case ExprOpcode::EQ_BOOL:
case ExprOpcode::NEQ_BOOL:
case ExprOpcode::AND:
case ExprOpcode::OR:
case ExprOpcode::NOT:
case ExprOpcode::VALID_HEADER:
case ExprOpcode::VALID_UNION:
case ExprOpcode::DATA_TO_BOOL:
return ExprType::BOOL;
case ExprOpcode::LOAD_HEADER:
case ExprOpcode::DEREFERENCE_HEADER_STACK:
case ExprOpcode::ACCESS_UNION_HEADER:
return ExprType::HEADER;
case ExprOpcode::LOAD_HEADER_STACK:
return ExprType::HEADER_STACK;
case ExprOpcode::LOAD_UNION:
case ExprOpcode::DEREFERENCE_UNION_STACK:
return ExprType::UNION;
case ExprOpcode::LOAD_UNION_STACK:
return ExprType::UNION_STACK;
case ExprOpcode::TERNARY_OP:
return ExprType::UNKNOWN;
case ExprOpcode::SKIP:
break;
}
assert(0);
return ExprType::UNKNOWN;
}
std::unique_ptr<SourceInfo> object_source_info(const Json::Value &cfg_object) {
std::string filename = "";
unsigned int line = 0;
unsigned int column = 0;
std::string source_fragment = "";
auto cfg_source_info = cfg_object["source_info"];
if (cfg_source_info.isNull()) {
return nullptr;
}
if (!cfg_source_info["filename"].isNull()) {
filename = cfg_source_info["filename"].asString();
}
if (!cfg_source_info["line"].isNull()) {
line = cfg_source_info["line"].asUInt();
}
if (!cfg_source_info["column"].isNull()) {
column = cfg_source_info["column"].asUInt();
}
if (!cfg_source_info["source_fragment"].isNull()) {
source_fragment = cfg_source_info["source_fragment"].asString();
}
auto source_info =
std::unique_ptr<SourceInfo>{new SourceInfo(filename, line, column,
source_fragment)};
return source_info;
}
} // namespace
void
P4Objects::build_expression(const Json::Value &json_expression,
Expression *expr, ExprType *expr_type) {
*expr_type = ExprType::UNKNOWN;
if (json_expression.isNull()) return;
const auto type = json_expression["type"].asString();
const auto &json_value = json_expression["value"];
if (type == "expression") {
const auto op = json_value["op"].asString();
const auto &json_left = json_value["left"];
const auto &json_right = json_value["right"];
ExprType typeL, typeR;
if (op == "?") {
const auto &json_cond = json_value["cond"];
build_expression(json_cond, expr);
Expression e1, e2;
build_expression(json_left, &e1, &typeL);
build_expression(json_right, &e2, &typeR);
assert(typeL == typeR);
expr->push_back_ternary_op(e1, e2);
*expr_type = typeL;
} else if (op == "==" || op == "!=") {
build_expression(json_left, expr, &typeL);
build_expression(json_right, expr, &typeR);
assert(typeL == typeR);
assert(typeL != ExprType::UNKNOWN);
auto opcode = (op == "==") ? get_eq_opcode(typeL) : get_neq_opcode(typeL);
expr->push_back_op(opcode);
*expr_type = ExprType::BOOL;
} else if (op == "access_field") {
build_expression(json_left, expr);
expr->push_back_access_field(json_right.asInt());
} else {
// special handling for unary + and -, we set the left operand to 0
if ((op == "+" || op == "-") && json_left.isNull())
expr->push_back_load_const(Data(0));
else
build_expression(json_left, expr);
build_expression(json_right, expr);
auto opcode = ExprOpcodesMap::get_opcode(op);
expr->push_back_op(opcode);
*expr_type = get_opcode_type(opcode);
}
} else if (type == "header") {
auto header_id = get_header_id(json_value.asString());
expr->push_back_load_header(header_id);
*expr_type = ExprType::HEADER;
enable_arith(header_id);
} else if (type == "field") {
const auto header_name = json_value[0].asString();
auto header_id = get_header_id(header_name);
const auto field_name = json_value[1].asString();
int field_offset = get_field_offset(header_id, field_name);
expr->push_back_load_field(header_id, field_offset);
*expr_type = ExprType::DATA;
enable_arith(header_id, field_offset);
} else if (type == "bool") {
expr->push_back_load_bool(json_value.asBool());
*expr_type = ExprType::BOOL;
} else if (type == "hexstr") {
expr->push_back_load_const(Data(json_value.asString()));
*expr_type = ExprType::DATA;
} else if (type == "local") { // runtime data for expressions in actions
expr->push_back_load_local(json_value.asInt());
*expr_type = ExprType::DATA;
} else if (type == "register") {
// TODO(antonin): cheap optimization
// this may not be worth doing, and probably does not belong here
const auto register_array_name = json_value[0].asString();
const auto &json_index = json_value[1];
assert(json_index.size() == 2);
if (json_index["type"].asString() == "hexstr") {
const auto idx = hexstr_to_int<unsigned int>(
json_index["value"].asString());
expr->push_back_load_register_ref(
get_register_array(register_array_name), idx);
} else {
build_expression(json_index, expr);
expr->push_back_load_register_gen(
get_register_array(register_array_name));
}
*expr_type = ExprType::DATA;
} else if (type == "header_stack") {
auto header_stack_id = get_header_stack_id(json_value.asString());
expr->push_back_load_header_stack(header_stack_id);
*expr_type = ExprType::HEADER_STACK;
phv_factory.enable_all_stack_field_arith(header_stack_id);
} else if (type == "stack_field") {
const auto header_stack_name = json_value[0].asString();
auto header_stack_id = get_header_stack_id(header_stack_name);
auto *header_type = header_stack_to_type_map[header_stack_name];
const auto field_name = json_value[1].asString();
int field_offset = header_type->get_field_offset(field_name);
expr->push_back_load_last_header_stack_field(header_stack_id, field_offset);
*expr_type = ExprType::DATA;
phv_factory.enable_stack_field_arith(header_stack_id, field_offset);
} else if (type == "header_union") {
auto header_union_id = get_header_union_id(json_value.asString());
expr->push_back_load_header_union(header_union_id);
*expr_type = ExprType::UNION;
} else if (type == "header_union_stack") {
auto header_union_stack_id = get_header_union_stack_id(
json_value.asString());
expr->push_back_load_header_union_stack(header_union_stack_id);
*expr_type = ExprType::UNION_STACK;
phv_factory.enable_all_union_stack_field_arith(header_union_stack_id);
} else {
throw json_exception(
EFormat() << "Invalid 'type' in expression: '" << type << "'",
json_expression);
}
}
int
P4Objects::add_primitive_to_action(const Json::Value &cfg_primitive,
ActionFn *action_fn) {
const auto primitive_name = cfg_primitive["op"].asString();
auto primitive = get_primitive(primitive_name);
if (!primitive)
throw json_exception(
EFormat() << "Unknown primitive action: " << primitive_name);
action_fn->push_back_primitive(primitive,
object_source_info(cfg_primitive));
const auto &cfg_primitive_parameters = cfg_primitive["parameters"];
// check number of parameters
const size_t num_params_expected = primitive->get_num_params();
const size_t num_params = cfg_primitive_parameters.size();
if (num_params != num_params_expected) {
// should not happen with a good compiler
throw json_exception(
EFormat() << "Invalid number of parameters for primitive action "
<< primitive_name << ": expected " << num_params_expected
<< " but got " << num_params,
cfg_primitive);
}
for (const auto &cfg_parameter : cfg_primitive_parameters) {
const auto type = cfg_parameter["type"].asString();
if (type == "hexstr") {
const auto value_hexstr = cfg_parameter["value"].asString();
action_fn->parameter_push_back_const(Data(value_hexstr));
} else if (type == "runtime_data") {
auto action_data_offset = cfg_parameter["value"].asUInt();
auto runtime_data_size = action_fn->get_num_params();
if (action_data_offset >= runtime_data_size) {
throw json_exception(
EFormat() << "Invalid 'runtime_data' parameter reference in "
<< "action '" << action_fn->get_name() << "' when "
<< "calling primitive '" << primitive_name << "': trying "
<< "to use parameter at offset " << action_data_offset
<< " but action only has " << runtime_data_size
<< " parameter(s)",
cfg_parameter);
}
action_fn->parameter_push_back_action_data(action_data_offset);
} else if (type == "header") {
const auto header_name = cfg_parameter["value"].asString();
auto header_id = get_header_id(header_name);
action_fn->parameter_push_back_header(header_id);
enable_arith(header_id);
} else if (type == "field") {
const auto &cfg_value_field = cfg_parameter["value"];
const auto header_name = cfg_value_field[0].asString();
auto header_id = get_header_id(header_name);
const auto field_name = cfg_value_field[1].asString();
auto field_offset = get_field_offset(header_id, field_name);
action_fn->parameter_push_back_field(header_id, field_offset);
enable_arith(header_id, field_offset);
} else if (type == "calculation") {
const auto name = cfg_parameter["value"].asString();
auto calculation = get_named_calculation(name);
action_fn->parameter_push_back_calculation(calculation);
} else if (type == "meter_array") {
const auto name = cfg_parameter["value"].asString();
auto meter = get_meter_array(name);
action_fn->parameter_push_back_meter_array(meter);
} else if (type == "counter_array") {
const auto name = cfg_parameter["value"].asString();
auto counter = get_counter_array(name);
action_fn->parameter_push_back_counter_array(counter);
} else if (type == "register_array") {
const auto name = cfg_parameter["value"].asString();
auto register_array = get_register_array(name);
action_fn->parameter_push_back_register_array(register_array);
} else if (type == "header_stack") {
const auto header_stack_name = cfg_parameter["value"].asString();
auto header_stack_id = get_header_stack_id(header_stack_name);
action_fn->parameter_push_back_header_stack(header_stack_id);
} else if (type == "expression") {
// TODO(Antonin): should this make the field case (and other) obsolete
// maybe if we can optimize this case
auto expr = new ArithExpression();
build_expression(cfg_parameter["value"], expr);
expr->build();
action_fn->parameter_push_back_expression(
std::unique_ptr<ArithExpression>(expr));
} else if (type == "register") {
// TODO(antonin): cheap optimization
// this may not be worth doing, and probably does not belong here
const auto &cfg_register = cfg_parameter["value"];
const auto register_array_name = cfg_register[0].asString();
auto &json_index = cfg_register[1];
assert(json_index.size() == 2);
if (json_index["type"].asString() == "hexstr") {
const auto idx = hexstr_to_int<unsigned int>(
json_index["value"].asString());
action_fn->parameter_push_back_register_ref(
get_register_array(register_array_name), idx);
} else {
auto idx_expr = new ArithExpression();
build_expression(json_index, idx_expr);
idx_expr->build();
action_fn->parameter_push_back_register_gen(
get_register_array(register_array_name),
std::unique_ptr<ArithExpression>(idx_expr));
}
} else if (type == "extern") {
const auto name = cfg_parameter["value"].asString();
auto extern_instance = get_extern_instance(name);
action_fn->parameter_push_back_extern_instance(extern_instance);
} else if (type == "string") {
action_fn->parameter_push_back_string(cfg_parameter["value"].asString());
} else if (type == "stack_field") {
const auto &cfg_value = cfg_parameter["value"];
const auto header_stack_name = cfg_value[0].asString();
auto header_stack_id = get_header_stack_id(header_stack_name);
auto *header_type = header_stack_to_type_map[header_stack_name];
const auto field_name = cfg_value[1].asString();
auto field_offset = header_type->get_field_offset(field_name);
action_fn->parameter_push_back_last_header_stack_field(
header_stack_id, field_offset);
phv_factory.enable_stack_field_arith(header_stack_id, field_offset);
} else {
throw json_exception(
EFormat() << "Parameter type '" << type << "' not supported",
cfg_parameter);
return 1;
}
}
return 0;
}
void
P4Objects::parse_config_options(const Json::Value &root) {
if (!root.isMember("config_options")) return;
const auto &cfg_options = root["config_options"];
for (auto it = cfg_options.begin(); it != cfg_options.end(); ++it) {
auto key = it.key().asString();
auto v = it->asString();
config_options.emplace(key, v);
}
}
namespace {
struct DirectMeterArray {
MeterArray *meter;
header_id_t header;
int offset;
};
class HeaderUnionType : public NamedP4Object {
public:
HeaderUnionType(const std::string &name, p4object_id_t id)
: NamedP4Object(name, id) { }
struct EntryInfo {
std::string name;
HeaderType *header_type;
};
size_t get_header_offset(const std::string &name) {
for (size_t i = 0; i < entries.size(); i++) {
if (name == entries.at(i).name) return i;
}
throw json_exception(EFormat() << "Unknown field name '" << name
<< "' in union type '" << get_name() << "'");
}
HeaderType *get_header_type(const std::string &header_name) {
auto header_offset = get_header_offset(header_name);
return entries.at(header_offset).header_type;
}
void push_back(const std::string &name, HeaderType *header_type) {
entries.push_back({name, header_type});
}
private:
std::vector<EntryInfo> entries{};
};
void check_json_tuple_size(const Json::Value &cfg_parent,
const std::string &key,
size_t expected_size) {
const auto &cfg_v = cfg_parent[key];
if (!cfg_v.isArray()) {
throw json_exception(
EFormat() << "Expected '" << key << "' to be a JSON array",
cfg_parent);
}
if (cfg_v.size() != expected_size) {
throw json_exception(
EFormat() << "Expected '" << key << "' to be a JSON array of size "
<< expected_size << " but array has size " << cfg_v.size(),
cfg_parent);
}
}
void check_json_version(const Json::Value &cfg_root) {
// to avoid a huge number of backward-compatibility issues, we accept JSON
// inputs which are not tagged with a version number.
if (!cfg_root.isMember("__meta__")) return;
const auto &cfg_meta = cfg_root["__meta__"];
if (!cfg_meta.isMember("version")) return;
const auto &cfg_version = cfg_meta["version"];
check_json_tuple_size(cfg_meta, "version", 2);
auto major = cfg_version[0].asInt();
auto minor = cfg_version[1].asInt();
if (major != required_major_version) {
throw json_exception(
EFormat() << "We require a bmv2 JSON major version number of "
<< required_major_version << " but this JSON input is "
<< "tagged with a major version number of " << major,
cfg_meta);
}
if (minor > max_minor_version) {
throw json_exception(
EFormat() << "The most recent bmv2 JSON version number supported is "
<< get_version_str(required_major_version, max_minor_version)
<< " but this JSON input is tagged with version number "
<< get_version_str(major, minor),
cfg_meta);
}
}
} // namespace
struct P4Objects::InitState {
std::unordered_map<std::string, DirectMeterArray> direct_meters{};
std::unordered_map<std::string, std::unique_ptr<HeaderUnionType> >
header_union_types_map{};
std::unordered_map<std::string, HeaderUnionType *> header_union_to_type_map{};
std::unordered_map<std::string, HeaderUnionType *>
header_union_stack_to_type_map{};
};
void
P4Objects::init_enums(const Json::Value &cfg_root) {
const auto &cfg_enums = cfg_root["enums"];
for (const auto &cfg_enum : cfg_enums) {
auto enum_name = cfg_enum["name"].asString();
auto enum_added = enums.add_enum(enum_name);
if (!enum_added)
throw json_exception("Invalid enums specification in json", cfg_enums);
const auto &cfg_enum_entries = cfg_enum["entries"];
for (const auto &cfg_enum_entry : cfg_enum_entries) {
auto entry_name = cfg_enum_entry[0].asString();
auto value = static_cast<EnumMap::type_t>(cfg_enum_entry[1].asInt());
auto entry_added = enums.add_entry(enum_name, entry_name, value);
if (!entry_added)
throw json_exception("Invalid enums specification in json", cfg_enum);
}
}
}
void
P4Objects::init_header_types(const Json::Value &cfg_root) {
const Json::Value &cfg_header_types = cfg_root["header_types"];
for (const auto &cfg_header_type : cfg_header_types) {
const string header_type_name = cfg_header_type["name"].asString();
header_type_id_t header_type_id = cfg_header_type["id"].asInt();
HeaderType *header_type = new HeaderType(header_type_name,
header_type_id);
const Json::Value &cfg_fields = cfg_header_type["fields"];
for (const auto cfg_field : cfg_fields) {
const string field_name = cfg_field[0].asString();
bool is_signed = false;
if (cfg_field.size() > 2)
is_signed = cfg_field[2].asBool();
bool is_saturating = false;
if (cfg_field.size() > 3)
is_saturating = cfg_field[3].asBool();
if (cfg_field[1].asString() == "*") { // VL field
std::unique_ptr<VLHeaderExpression> VL_expr(nullptr);
if (cfg_header_type.isMember("length_exp")) {
const Json::Value &cfg_length_exp = cfg_header_type["length_exp"];
ArithExpression raw_expr;
build_expression(cfg_length_exp, &raw_expr);
raw_expr.build();
VL_expr.reset(new VLHeaderExpression(raw_expr));
}
int max_header_bytes = 0;
if (cfg_header_type.isMember("max_length"))
max_header_bytes = cfg_header_type["max_length"].asInt();
header_type->push_back_VL_field(
field_name, max_header_bytes, std::move(VL_expr),
is_signed, is_saturating);
} else {
int field_bit_width = cfg_field[1].asInt();
header_type->push_back_field(
field_name, field_bit_width, is_signed, is_saturating);
}
}
add_header_type(header_type_name, unique_ptr<HeaderType>(header_type));
}
}
void
P4Objects::init_headers(const Json::Value &cfg_root) {
const Json::Value &cfg_headers = cfg_root["headers"];
for (const auto &cfg_header : cfg_headers) {
const string header_name = cfg_header["name"].asString();
const string header_type_name = cfg_header["header_type"].asString();
header_id_t header_id = cfg_header["id"].asInt();
bool metadata = cfg_header["metadata"].asBool();
HeaderType *header_type = get_header_type(header_type_name);
header_to_type_map[header_name] = header_type;
phv_factory.push_back_header(header_name, header_id,
*header_type, metadata);
phv_factory.disable_all_field_arith(header_id);
add_header_id(header_name, header_id);
}
}
void
P4Objects::init_header_stacks(const Json::Value &cfg_root) {
const Json::Value &cfg_header_stacks = cfg_root["header_stacks"];
for (const auto &cfg_header_stack : cfg_header_stacks) {
const string header_stack_name = cfg_header_stack["name"].asString();
const string header_type_name = cfg_header_stack["header_type"].asString();
header_stack_id_t header_stack_id = cfg_header_stack["id"].asInt();
HeaderType *header_stack_type = get_header_type(header_type_name);
header_stack_to_type_map[header_stack_name] = header_stack_type;
std::vector<header_id_t> header_ids;
for (const auto &cfg_header_id : cfg_header_stack["header_ids"]) {
header_ids.push_back(cfg_header_id.asInt());
header_id_to_stack_id[cfg_header_id.asInt()] = header_stack_id;
}
phv_factory.push_back_header_stack(header_stack_name, header_stack_id,
*header_stack_type, header_ids);
add_header_stack_id(header_stack_name, header_stack_id);
}
}
void
P4Objects::init_header_unions(const Json::Value &cfg_root,
InitState *init_state) {
auto &header_union_types_map = init_state->header_union_types_map;
auto &header_union_to_type_map = init_state->header_union_to_type_map;
const auto &cfg_header_union_types = cfg_root["header_union_types"];
for (const auto &cfg_header_union_type : cfg_header_union_types) {
auto header_union_type_name = cfg_header_union_type["name"].asString();
p4object_id_t header_union_type_id = cfg_header_union_type["id"].asInt();
std::unique_ptr<HeaderUnionType> header_union_type(new HeaderUnionType(
header_union_type_name, header_union_type_id));
for (const auto &cfg_header : cfg_header_union_type["headers"]) {
auto name = cfg_header[0].asString();
auto type_name = cfg_header[1].asString();
header_union_type->push_back(name, get_header_type(type_name));
}
header_union_types_map.emplace(header_union_type_name,
std::move(header_union_type));
}
const auto &cfg_header_unions = cfg_root["header_unions"];
for (const auto &cfg_header_union : cfg_header_unions) {
auto header_union_name = cfg_header_union["name"].asString();
header_union_id_t header_union_id = cfg_header_union["id"].asInt();
auto header_union_type_name = cfg_header_union["union_type"].asString();
auto &header_union_type = header_union_types_map.at(header_union_type_name);
std::vector<header_id_t> header_ids;
for (const auto &cfg_header_id : cfg_header_union["header_ids"]) {
header_id_to_union_pos.emplace(
cfg_header_id.asInt(),
HeaderUnionPos({header_union_id, header_ids.size()}));
header_ids.push_back(cfg_header_id.asInt());
}
phv_factory.push_back_header_union(header_union_name, header_union_id,
header_ids);
add_header_union_id(header_union_name, header_union_id);
header_union_to_type_map.emplace(header_union_name,
header_union_type.get());
}
}
void
P4Objects::init_header_union_stacks(const Json::Value &cfg_root,
InitState *init_state) {
auto &header_union_types_map = init_state->header_union_types_map;
auto &header_union_stack_to_type_map =
init_state->header_union_stack_to_type_map;
const auto &cfg_header_union_stacks = cfg_root["header_union_stacks"];
for (const auto &cfg_header_union_stack : cfg_header_union_stacks) {
auto header_union_stack_name = cfg_header_union_stack["name"].asString();
header_union_stack_id_t header_union_stack_id =
cfg_header_union_stack["id"].asInt();
auto header_union_type_name =
cfg_header_union_stack["union_type"].asString();
auto &header_union_type = header_union_types_map.at(header_union_type_name);
std::vector<header_union_id_t> header_union_ids;
auto &cfg_header_unions = cfg_header_union_stack["header_union_ids"];
for (const auto &cfg_header_union_id : cfg_header_unions) {
header_union_ids.push_back(cfg_header_union_id.asInt());
union_id_to_union_stack_id[cfg_header_union_id.asInt()] =
header_union_stack_id;
}
phv_factory.push_back_header_union_stack(
header_union_stack_name, header_union_stack_id, header_union_ids);
add_header_union_stack_id(header_union_stack_name, header_union_stack_id);
header_union_stack_to_type_map.emplace(header_union_stack_name,
header_union_type.get());
}
}
void
P4Objects::init_extern_instances(const Json::Value &cfg_root) {
const Json::Value &cfg_extern_instances = cfg_root["extern_instances"];
for (const auto &cfg_extern_instance : cfg_extern_instances) {
const string extern_instance_name = cfg_extern_instance["name"].asString();
const p4object_id_t extern_instance_id = cfg_extern_instance["id"].asInt();
const string extern_type_name = cfg_extern_instance["type"].asString();
auto instance = ExternFactoryMap::get_instance()->get_extern_instance(
extern_type_name);
if (instance == nullptr) {
throw json_exception(
EFormat() << "Invalid reference to extern type '"
<< extern_type_name << "'",
cfg_extern_instance);
}
instance->_register_attributes();
instance->_set_name_and_id(extern_instance_name, extern_instance_id);
const Json::Value &cfg_extern_attributes =
cfg_extern_instance["attribute_values"];
for (const auto &cfg_extern_attribute : cfg_extern_attributes) {
// only hexstring accepted
const string name = cfg_extern_attribute["name"].asString();
const string type = cfg_extern_attribute["type"].asString();
if (!instance->_has_attribute(name)) {
throw json_exception(
EFormat() << "Extern type '" << extern_type_name
<< "' has no attribute '" << name << "'",
cfg_extern_attribute);
}
if (type == "hexstr") {
const string value_hexstr = cfg_extern_attribute["value"].asString();
instance->_set_attribute<Data>(name, Data(value_hexstr));
} else if (type == "string") {
// adding string to possible attributes for more flexible externs
// (especially now that externs can access P4Objects), while we finalize
// the extern design
const string value_string = cfg_extern_attribute["value"].asString();
instance->_set_attribute<std::string>(name, value_string);
} else if (type == "expression") {
Expression expr;
build_expression(cfg_extern_attribute["value"], &expr);
expr.build();
// we rely on the fact that an Expression can be copied
instance->_set_attribute<Expression>(name, expr);
} else {
throw json_exception("Only attributes of type 'hexstr', 'string' or"
" 'expression' are supported for extern instance"
" attribute initialization", cfg_extern_attribute);
}
}
// needs to be set before the call to init!
instance->_set_p4objects(this);
add_extern_instance(extern_instance_name, std::move(instance));
}
}
void
P4Objects::init_parse_vsets(const Json::Value &cfg_root) {
const Json::Value &cfg_parse_vsets = cfg_root["parse_vsets"];
for (const auto &cfg_parse_vset : cfg_parse_vsets) {
const string parse_vset_name = cfg_parse_vset["name"].asString();
const p4object_id_t parse_vset_id = cfg_parse_vset["id"].asInt();
const size_t parse_vset_cbitwidth =
cfg_parse_vset["compressed_bitwidth"].asUInt();
std::unique_ptr<ParseVSet> vset(
new ParseVSet(parse_vset_name, parse_vset_id, parse_vset_cbitwidth));
add_parse_vset(parse_vset_name, std::move(vset));
}
}
void
P4Objects::init_errors(const Json::Value &cfg_root) {
const auto &cfg_errors = cfg_root["errors"];
for (const auto &cfg_error : cfg_errors) {
auto name = cfg_error[0].asString();
auto value = static_cast<ErrorCode::type_t>(cfg_error[1].asInt());
auto added = error_codes.add(name, value);
if (!added)
throw json_exception("Invalid errors specification in json", cfg_errors);
}
error_codes.add_core();
}
void
P4Objects::init_parsers(const Json::Value &cfg_root, InitState *init_state) {
auto &header_union_stack_to_type_map =
init_state->header_union_stack_to_type_map;
const auto &cfg_parsers = cfg_root["parsers"];
for (const auto &cfg_parser : cfg_parsers) {
const string parser_name = cfg_parser["name"].asString();
p4object_id_t parser_id = cfg_parser["id"].asInt();
std::unique_ptr<Parser> parser(
new Parser(parser_name, parser_id, &error_codes));
std::unordered_map<string, ParseState *> current_parse_states;
// parse states
const Json::Value &cfg_parse_states = cfg_parser["parse_states"];
for (const auto &cfg_parse_state : cfg_parse_states) {
const string parse_state_name = cfg_parse_state["name"].asString();
const p4object_id_t id = cfg_parse_state["id"].asInt();
// p4object_id_t parse_state_id = cfg_parse_state["id"].asInt();
std::unique_ptr<ParseState> parse_state(
new ParseState(parse_state_name, id));
const Json::Value &cfg_parser_ops = cfg_parse_state["parser_ops"];
for (const auto &cfg_parser_op : cfg_parser_ops) {
const string op_type = cfg_parser_op["op"].asString();
const Json::Value &cfg_parameters = cfg_parser_op["parameters"];
if (op_type == "extract") {
check_json_tuple_size(cfg_parser_op, "parameters", 1);
const Json::Value &cfg_extract = cfg_parameters[0];
const string extract_type = cfg_extract["type"].asString();
if (extract_type == "regular") {
const string extract_header = cfg_extract["value"].asString();
header_id_t header_id = get_header_id(extract_header);
const auto &header_type = phv_factory.get_header_type(header_id);
if (header_type.is_VL_header() && !header_type.has_VL_expr()) {
throw json_exception(
EFormat() << "Cannot use 'extract' parser op with a VL header"
<< " for which no length expression was provided,"
<< " use 'extract_VL' instead",
cfg_parser_op);
}
parse_state->add_extract(header_id);
} else if (extract_type == "stack") {
const string extract_header = cfg_extract["value"].asString();
header_stack_id_t header_stack_id =
get_header_stack_id(extract_header);
parse_state->add_extract_to_stack(header_stack_id);
} else if (extract_type == "union_stack") {
const auto &cfg_union_stack = cfg_extract["value"];
check_json_tuple_size(cfg_extract, "value", 2);
auto extract_union_stack = cfg_union_stack[0].asString();
auto header_union_stack_id = get_header_union_stack_id(
extract_union_stack);
auto *union_type = header_union_stack_to_type_map.at(
extract_union_stack);
auto header_offset = union_type->get_header_offset(
cfg_union_stack[1].asString());
parse_state->add_extract_to_union_stack(
header_union_stack_id, header_offset);
} else {
throw json_exception(
EFormat() << "Extract type '" << extract_type
<< "' not supported",
cfg_parser_op);
}
} else if (op_type == "extract_VL") {
check_json_tuple_size(cfg_parser_op, "parameters", 2);
const Json::Value &cfg_extract = cfg_parameters[0];
const Json::Value &cfg_VL_expr = cfg_parameters[1];
assert(cfg_extract["type"].asString() == "regular");
assert(cfg_VL_expr["type"].asString() == "expression");
auto header_id = get_header_id(cfg_extract["value"].asString());
const auto &header_type = phv_factory.get_header_type(header_id);
ArithExpression VL_expr;
build_expression(cfg_VL_expr["value"], &VL_expr);
VL_expr.build();
parse_state->add_extract_VL(header_id, VL_expr,
header_type.get_VL_max_header_bytes());
} else if (op_type == "set") {
check_json_tuple_size(cfg_parser_op, "parameters", 2);
const Json::Value &cfg_dest = cfg_parameters[0];
const Json::Value &cfg_src = cfg_parameters[1];
const string &dest_type = cfg_dest["type"].asString();
if (dest_type != "field") {
throw json_exception(
EFormat() << "Parser 'set' operation has invalid destination "
<< "type '" << dest_type << "', expected 'field'",
cfg_parser_op);