-
Notifications
You must be signed in to change notification settings - Fork 445
/
ebpfParser.cpp
717 lines (618 loc) · 27.2 KB
/
ebpfParser.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
/*
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.
*/
#include "ebpfParser.h"
#include "ebpfModel.h"
#include "ebpfType.h"
#include "frontends/p4/coreLibrary.h"
#include "frontends/p4/methodInstance.h"
namespace P4::EBPF {
void StateTranslationVisitor::compileLookahead(const IR::Expression *destination) {
cstring msgStr = absl::StrFormat("Parser: lookahead for %v %v",
state->parser->typeMap->getType(destination), destination);
builder->target->emitTraceMessage(builder, msgStr.c_str());
builder->emitIndent();
builder->blockStart();
builder->emitIndent();
builder->appendFormat("u8* %v_save = %v", state->parser->program->headerStartVar,
state->parser->program->headerStartVar);
builder->endOfStatement(true);
compileExtract(destination);
builder->emitIndent();
builder->appendFormat("%v = %v_save", state->parser->program->headerStartVar,
state->parser->program->headerStartVar);
builder->endOfStatement(true);
builder->blockEnd(true);
}
void StateTranslationVisitor::compileAdvance(const P4::ExternMethod *extMethod) {
auto argExpr = extMethod->expr->arguments->at(0)->expression;
auto cnst = argExpr->to<IR::Constant>();
if (cnst) {
cstring argStr = cstring::to_cstring(cnst->asUnsigned());
cstring offsetStr =
absl::StrFormat("%v - (u8*)%v + BYTES(%v)", state->parser->program->headerStartVar,
state->parser->program->packetStartVar, argStr);
builder->target->emitTraceMessage(builder,
"Parser (advance): check pkt_len=%%d < "
"last_read_byte=%%d",
2, state->parser->program->lengthVar.c_str(),
offsetStr.c_str());
} else {
::P4::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"packet_in.advance() method with non-constant argument is not supported yet");
return;
}
int advanceVal = cnst->asInt();
if (advanceVal % 8 != 0) {
::P4::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"packet_in.advance(%1%) must be byte-aligned in eBPF backend", advanceVal);
return;
}
builder->emitIndent();
builder->appendFormat("%v += BYTES(", state->parser->program->headerStartVar);
visit(argExpr);
builder->append(")");
builder->endOfStatement(true);
builder->emitIndent();
builder->appendFormat("if ((u8*)%v < %v) ", state->parser->program->packetEndVar,
state->parser->program->headerStartVar);
builder->blockStart();
builder->target->emitTraceMessage(builder, "Parser: invalid packet (packet too short)");
builder->emitIndent();
builder->appendFormat("%s = %s;", state->parser->program->errorVar.c_str(),
p4lib.packetTooShort.str());
builder->newline();
builder->emitIndent();
builder->appendFormat("goto %s;", IR::ParserState::reject.c_str());
builder->newline();
builder->blockEnd(true);
}
void StateTranslationVisitor::compileVerify(const IR::MethodCallExpression *expression) {
BUG_CHECK(expression->arguments->size() == 2, "Expected 2 arguments: %1%", expression);
auto errorExpr = expression->arguments->at(1)->expression;
auto errorMember = errorExpr->to<IR::Member>();
auto type = typeMap->getType(errorExpr, true);
if (!type->is<IR::Type_Error>() || errorMember == nullptr) {
::P4::error(ErrorType::ERR_UNEXPECTED, "%1%: not accessing a member error type", errorExpr);
return;
}
builder->emitIndent();
builder->append("if (!(");
visit(expression->arguments->at(0));
builder->append(")) ");
builder->blockStart();
builder->emitIndent();
builder->appendFormat("%v = %v", state->parser->program->errorVar, errorMember->member);
builder->endOfStatement(true);
cstring msg =
absl::StrFormat("Verify: condition failed, parser_error=%%u (%v)", errorMember->member);
builder->target->emitTraceMessage(builder, msg.c_str(), 1,
state->parser->program->errorVar.c_str());
builder->emitIndent();
builder->appendFormat("goto %s", IR::ParserState::reject.c_str());
builder->endOfStatement(true);
builder->blockEnd(true);
}
bool StateTranslationVisitor::preorder(const IR::AssignmentStatement *statement) {
if (auto mce = statement->right->to<IR::MethodCallExpression>()) {
auto mi = P4::MethodInstance::resolve(mce, state->parser->program->refMap,
state->parser->program->typeMap);
auto extMethod = mi->to<P4::ExternMethod>();
if (extMethod == nullptr) BUG("Unhandled method %1%", mce);
auto decl = extMethod->object;
if (decl == state->parser->packet) {
if (extMethod->method->name.name == p4lib.packetIn.lookahead.name) {
compileLookahead(statement->left);
return false;
} else if (extMethod->method->name.name == p4lib.packetIn.length.name) {
return CodeGenInspector::preorder(statement);
}
}
}
return CodeGenInspector::preorder(statement);
}
bool StateTranslationVisitor::preorder(const IR::ParserState *parserState) {
if (parserState->isBuiltin()) return false;
builder->emitIndent();
builder->append(parserState->name.name);
builder->append(":");
builder->spc();
builder->blockStart();
cstring msgStr = absl::StrFormat("Parser: state %v (curr_offset=%%d)", parserState->name);
cstring offsetStr = absl::StrFormat("%v - (u8*)%v", state->parser->program->headerStartVar,
state->parser->program->packetStartVar);
builder->target->emitTraceMessage(builder, msgStr.c_str(), 1, offsetStr.c_str());
visit(parserState->components, "components");
if (parserState->selectExpression == nullptr) {
builder->emitIndent();
builder->append("goto ");
builder->append(IR::ParserState::reject);
builder->endOfStatement(true);
} else if (parserState->selectExpression->is<IR::SelectExpression>()) {
visit(parserState->selectExpression);
} else {
// must be a PathExpression which is a state name
if (!parserState->selectExpression->is<IR::PathExpression>())
BUG("Expected a PathExpression, got a %1%", parserState->selectExpression);
builder->emitIndent();
builder->append(" goto ");
visit(parserState->selectExpression);
builder->endOfStatement(true);
}
builder->blockEnd(true);
return false;
}
bool StateTranslationVisitor::preorder(const IR::SelectExpression *expression) {
BUG_CHECK(expression->select->components.size() == 1, "%1%: tuple not eliminated in select",
expression->select);
selectValue = state->parser->program->refMap->newName("select");
auto type = state->parser->program->typeMap->getType(expression->select, true);
if (auto list = type->to<IR::Type_List>()) {
BUG_CHECK(list->components.size() == 1, "%1% list type with more than 1 element", list);
type = list->components.at(0);
}
auto etype = EBPFTypeFactory::instance->create(type);
builder->emitIndent();
etype->declare(builder, selectValue, false);
builder->endOfStatement(true);
emitAssignStatement(type, nullptr, selectValue, expression->select->components.at(0));
builder->newline();
// Init value_sets
for (auto e : expression->selectCases) {
if (e->keyset->is<IR::PathExpression>()) {
cstring pvsName = e->keyset->to<IR::PathExpression>()->path->name.name;
cstring pvsKeyVarName = state->parser->program->refMap->newName(pvsName + "_key");
auto pvs = state->parser->getValueSet(pvsName);
if (pvs != nullptr)
pvs->emitKeyInitializer(builder, expression, pvsKeyVarName);
else
::P4::error(ErrorType::ERR_UNKNOWN, "%1%: expected a value_set instance",
e->keyset);
}
}
for (auto e : expression->selectCases) visit(e);
builder->emitIndent();
builder->appendFormat("else goto %s;", IR::ParserState::reject.c_str());
builder->newline();
return false;
}
bool StateTranslationVisitor::preorder(const IR::SelectCase *selectCase) {
unsigned width = EBPFInitializerUtils::ebpfTypeWidth(typeMap, selectCase->keyset);
bool scalar = EBPFScalarType::generatesScalar(width);
builder->emitIndent();
if (auto pe = selectCase->keyset->to<IR::PathExpression>()) {
builder->append("if (");
cstring pvsName = pe->path->name.name;
auto pvs = state->parser->getValueSet(pvsName);
if (pvs) pvs->emitLookup(builder);
builder->append(" != NULL)");
} else if (auto mask = selectCase->keyset->to<IR::Mask>()) {
if (scalar) {
builder->appendFormat("if ((%v", selectValue);
builder->append(" & ");
visit(mask->right);
builder->append(") == (");
visit(mask->left);
builder->append(" & ");
visit(mask->right);
builder->append("))");
} else {
unsigned bytes = ROUNDUP(width, 8);
bool first = true;
cstring hex = EBPFInitializerUtils::genHexStr(mask->right->to<IR::Constant>()->value,
width, mask->right);
cstring value = EBPFInitializerUtils::genHexStr(mask->left->to<IR::Constant>()->value,
width, mask->left);
builder->append("if (");
for (unsigned i = 0; i < bytes; ++i) {
if (!first) {
builder->append(" && ");
}
builder->appendFormat("((%v[%u] & 0x%v)", selectValue, i, hex.substr(2 * i, 2));
builder->append(" == ");
builder->appendFormat("(%v & %v))", value.substr(2 * i, 2), hex.substr(2 * i, 2));
first = false;
}
builder->append(") ");
}
} else {
builder->appendFormat("if (%v", selectValue);
builder->append(" == ");
visit(selectCase->keyset);
builder->append(")");
}
builder->append("goto ");
visit(selectCase->state);
builder->endOfStatement(true);
return false;
}
void StateTranslationVisitor::compileExtractField(const IR::Expression *expr,
const IR::StructField *field,
unsigned hdrOffsetBits, EBPFType *type) {
unsigned alignment = hdrOffsetBits % 8;
unsigned widthToExtract = type->as<IHasWidth>().widthInBits();
auto program = state->parser->program;
cstring msgStr;
cstring fieldName = field->name.name;
msgStr = absl::StrFormat("Parser: extracting field %v", fieldName);
builder->target->emitTraceMessage(builder, msgStr.c_str());
if (widthToExtract <= 64) {
unsigned lastBitIndex = widthToExtract + alignment - 1;
unsigned lastWordIndex = lastBitIndex / 8;
unsigned wordsToRead = lastWordIndex + 1;
unsigned loadSize;
const char *helper = nullptr;
if (wordsToRead <= 1) {
helper = "load_byte";
loadSize = 8;
} else if (wordsToRead <= 2) {
helper = "load_half";
loadSize = 16;
} else if (wordsToRead <= 4) {
helper = "load_word";
loadSize = 32;
} else {
// TODO: this is wrong, since a 60-bit unaligned read may require 9 words.
if (wordsToRead > 64) BUG("Unexpected width %d", widthToExtract);
helper = "load_dword";
loadSize = 64;
}
unsigned shift = loadSize - alignment - widthToExtract;
builder->emitIndent();
visit(expr);
builder->appendFormat(".%s = (", fieldName.c_str());
type->emit(builder);
builder->appendFormat(")((%s(%s, BYTES(%u))", helper, program->headerStartVar.c_str(),
hdrOffsetBits);
if (shift != 0) builder->appendFormat(" >> %d", shift);
builder->append(")");
if (widthToExtract != loadSize) {
builder->append(" & EBPF_MASK(");
type->emit(builder);
builder->appendFormat(", %d)", widthToExtract);
}
builder->append(")");
builder->endOfStatement(true);
} else {
if (program->options.arch == "psa" && widthToExtract % 8 != 0) {
// To explain the problem in error lets assume that we have bit<68> field with value:
// 0x11223344556677889
// ^ this digit will be parsed into a half of byte
// Such fields are parsed into a table of bytes in network byte order, so possible
// values in dataplane are (note the position of additional '0' at the end):
// 0x112233445566778809
// 0x112233445566778890
// To correctly insert that padding, the length of field must be known, but tools like
// nikss-ctl (and the nikss library) don't consume P4info.txtpb to have such knowledge.
// There is also a bug in (de)parser causing such fields to be deparsed incorrectly.
::P4::error(
ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"%1%: fields wider than 64 bits must have a size multiple of 8 bits (1 byte) "
"due to ambiguous padding in the LSB byte when the condition is not met",
field);
}
// wide values; read all bytes one by one.
unsigned shift;
if (alignment == 0)
shift = 0;
else
shift = 8 - alignment;
const char *helper;
if (shift == 0)
helper = "load_byte";
else
helper = "load_half";
auto bt = EBPFTypeFactory::instance->create(IR::Type_Bits::get(8));
unsigned bytes = ROUNDUP(widthToExtract, 8);
for (unsigned i = 0; i < bytes; i++) {
builder->emitIndent();
visit(expr);
builder->appendFormat(".%s[%d] = (", fieldName.c_str(), i);
bt->emit(builder);
builder->appendFormat(")((%s(%s, BYTES(%u) + %d) >> %d)", helper,
program->headerStartVar.c_str(), hdrOffsetBits, i, shift);
if ((i == bytes - 1) && (widthToExtract % 8 != 0)) {
builder->append(" & EBPF_MASK(");
bt->emit(builder);
builder->appendFormat(", %d)", widthToExtract % 8);
}
builder->append(")");
builder->endOfStatement(true);
}
}
// eBPF can pass 64 bits of data as one argument passed in 64 bit register,
// so value of the field is printed only when it fits into that register
if (widthToExtract <= 64) {
cstring exprStr = expr->is<IR::PathExpression>()
? expr->to<IR::PathExpression>()->path->name.name
: expr->toString();
if (expr->is<IR::Member>() && expr->to<IR::Member>()->expr->is<IR::PathExpression>() &&
isPointerVariable(
expr->to<IR::Member>()->expr->to<IR::PathExpression>()->path->name.name)) {
exprStr = exprStr.replace(".", "->");
}
auto tmp = absl::StrFormat("(unsigned long long) %v.%v", exprStr, fieldName);
msgStr =
absl::StrFormat("Parser: extracted %v=0x%%llx (%u bits)", fieldName, widthToExtract);
builder->target->emitTraceMessage(builder, msgStr.c_str(), 1, tmp.c_str());
} else {
msgStr = absl::StrFormat("Parser: extracted %v (%u bits)", fieldName, widthToExtract);
builder->target->emitTraceMessage(builder, msgStr.c_str());
}
}
void StateTranslationVisitor::compileExtract(const IR::Expression *destination) {
cstring msgStr;
auto type = state->parser->typeMap->getType(destination);
auto ht = type->to<IR::Type_StructLike>();
if (ht == nullptr) {
::P4::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET, "Cannot extract to a non-struct type %1%",
destination);
return;
}
// We expect all headers to start on a byte boundary.
unsigned width = ht->width_bits();
if ((width % 8) != 0) {
::P4::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"Header %1% size %2% is not a multiple of 8 bits.", destination, width);
return;
}
auto program = state->parser->program;
auto offsetStr = absl::StrFormat("(%v - (u8*)%v) + BYTES(%d)", program->headerStartVar,
program->packetStartVar, width);
builder->target->emitTraceMessage(builder, "Parser: check pkt_len=%d >= last_read_byte=%d", 2,
program->lengthVar.c_str(), offsetStr.c_str());
// to load some fields the compiler will use larger words
// than actual width of a field (e.g. 48-bit field loaded using load_dword())
// we must ensure that the larger word is not outside of packet buffer.
// FIXME: this can fail if a packet does not contain additional payload after header.
// However, we don't have better solution in case of using load_X functions to parse packet.
// TODO: consider using a collection of smaller widths.
unsigned curr_padding = 0;
for (auto f : ht->fields) {
auto ftype = state->parser->typeMap->getType(f);
auto etype = EBPFTypeFactory::instance->create(ftype);
if (etype->is<EBPFScalarType>()) {
auto scalarType = etype->to<EBPFScalarType>();
unsigned readWordSize = scalarType->alignment() * 8;
unsigned unaligned = scalarType->widthInBits() % readWordSize;
unsigned padding = readWordSize - unaligned;
if (padding == readWordSize) padding = 0;
if (scalarType->widthInBits() + padding >= curr_padding) {
curr_padding = padding;
}
}
}
builder->emitIndent();
builder->appendFormat("if ((u8*)%s < %s + BYTES(%d + %u)) ", program->packetEndVar.c_str(),
program->headerStartVar.c_str(), width, curr_padding);
builder->blockStart();
builder->target->emitTraceMessage(builder, "Parser: invalid packet (packet too short)");
builder->emitIndent();
builder->appendFormat("%s = %s;", program->errorVar.c_str(), p4lib.packetTooShort.str());
builder->newline();
builder->emitIndent();
builder->appendFormat("goto %s;", IR::ParserState::reject.c_str());
builder->newline();
builder->blockEnd(true);
msgStr = absl::StrFormat("Parser: extracting header %v", destination);
builder->target->emitTraceMessage(builder, msgStr.c_str());
builder->newline();
unsigned hdrOffsetBits = 0;
for (auto f : ht->fields) {
auto ftype = state->parser->typeMap->getType(f);
auto etype = EBPFTypeFactory::instance->create(ftype);
auto et = etype->to<IHasWidth>();
if (et == nullptr) {
::P4::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"Only headers with fixed widths supported %1%", f);
return;
}
compileExtractField(destination, f, hdrOffsetBits, etype);
hdrOffsetBits += et->widthInBits();
}
builder->newline();
if (ht->is<IR::Type_Header>()) {
builder->emitIndent();
visit(destination);
builder->appendLine(".ebpf_valid = 1;");
}
// Increment header pointer
builder->emitIndent();
builder->appendFormat("%s += BYTES(%u);", program->headerStartVar.c_str(), width);
builder->newline();
msgStr = absl::StrFormat("Parser: extracted %v", destination);
builder->target->emitTraceMessage(builder, msgStr.c_str());
builder->newline();
}
void StateTranslationVisitor::processFunction(const P4::ExternFunction *function) {
if (function->method->name.name == IR::ParserState::verify) {
compileVerify(function->expr);
} else {
::P4::error(ErrorType::ERR_UNEXPECTED, "Unexpected extern function call in parser %1%",
function->expr);
}
}
void StateTranslationVisitor::processMethod(const P4::ExternMethod *method) {
auto expression = method->expr;
auto decl = method->object;
if (decl == state->parser->packet) {
if (method->method->name.name == p4lib.packetIn.extract.name) {
if (expression->arguments->size() != 1) {
::P4::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"Variable-sized header fields not yet supported %1%", expression);
return;
}
compileExtract(expression->arguments->at(0)->expression);
return;
} else if (method->method->name.name == p4lib.packetIn.length.name) {
builder->append(state->parser->program->lengthVar);
return;
} else if (method->method->name.name == p4lib.packetIn.advance.name) {
compileAdvance(method);
return;
}
BUG("Unhandled packet method %1%", expression->method);
}
::P4::error(ErrorType::ERR_UNEXPECTED, "Unexpected extern method call in parser %1%",
expression);
}
bool StateTranslationVisitor::preorder(const IR::MethodCallExpression *expression) {
if (commentDescriptionDepth == 0) builder->append("/* ");
commentDescriptionDepth++;
visit(expression->method);
builder->append("(");
bool first = true;
for (auto a : *expression->arguments) {
if (!first) builder->append(", ");
first = false;
visit(a);
}
builder->append(")");
if (commentDescriptionDepth == 1) {
builder->append(" */");
builder->newline();
}
commentDescriptionDepth--;
// do not process extern when comment is generated
if (commentDescriptionDepth != 0) return false;
auto mi = P4::MethodInstance::resolve(expression, state->parser->program->refMap,
state->parser->program->typeMap);
auto ef = mi->to<P4::ExternFunction>();
if (ef != nullptr) {
processFunction(ef);
return false;
}
auto extMethod = mi->to<P4::ExternMethod>();
if (extMethod != nullptr) {
processMethod(extMethod);
return false;
}
if (auto bim = mi->to<P4::BuiltInMethod>()) {
builder->emitIndent();
if (bim->name == IR::Type_Header::isValid) {
visit(bim->appliedTo);
builder->append(".ebpf_valid");
return false;
} else if (bim->name == IR::Type_Header::setValid) {
visit(bim->appliedTo);
builder->append(".ebpf_valid = true");
return false;
} else if (bim->name == IR::Type_Header::setInvalid) {
visit(bim->appliedTo);
builder->append(".ebpf_valid = false");
return false;
}
}
::P4::error(ErrorType::ERR_UNEXPECTED, "Unexpected method call in parser %1%", expression);
return false;
}
bool StateTranslationVisitor::preorder(const IR::Member *expression) {
if (expression->expr->is<IR::PathExpression>()) {
auto pe = expression->expr->to<IR::PathExpression>();
auto decl = state->parser->program->refMap->getDeclaration(pe->path, true);
if (decl == state->parser->packet) {
builder->append(expression->member);
return false;
}
}
return CodeGenInspector::preorder(expression);
}
//////////////////////////////////////////////////////////////////
EBPFParser::EBPFParser(const EBPFProgram *program, const IR::ParserBlock *block,
const P4::TypeMap *typeMap)
: program(program),
typeMap(typeMap),
parserBlock(block),
packet(nullptr),
headers(nullptr),
headerType(nullptr) {
visitor = new StateTranslationVisitor(program->refMap, program->typeMap);
}
void EBPFParser::emitDeclaration(CodeBuilder *builder, const IR::Declaration *decl) {
if (decl->is<IR::Declaration_Variable>()) {
auto vd = decl->to<IR::Declaration_Variable>();
auto etype = EBPFTypeFactory::instance->create(vd->type);
builder->emitIndent();
etype->declare(builder, vd->name, false);
builder->endOfStatement(true);
BUG_CHECK(vd->initializer == nullptr, "%1%: declarations with initializers not supported",
decl);
return;
} else if (decl->is<IR::P4ValueSet>()) {
return;
}
BUG("%1%: not yet handled", decl);
}
void EBPFParser::emit(CodeBuilder *builder) {
for (auto l : parserBlock->container->parserLocals) emitDeclaration(builder, l);
builder->emitIndent();
builder->appendFormat("goto %s;", IR::ParserState::start.c_str());
builder->newline();
visitor->setBuilder(builder);
for (auto s : states) {
visitor->setState(s);
s->state->apply(*visitor);
}
builder->newline();
// Create a synthetic reject state
builder->emitIndent();
builder->appendFormat("%s:", IR::ParserState::reject.c_str());
builder->spc();
builder->blockStart();
// This state may be called from deparser, so do not explicitly tell source of this event.
builder->target->emitTraceMessage(builder, "Packet rejected");
emitRejectState(builder);
builder->blockEnd(true);
builder->newline();
}
bool EBPFParser::build() {
auto pl = parserBlock->container->type->applyParams;
if (pl->size() != 2) {
::P4::error(ErrorType::ERR_EXPECTED, "Expected parser to have exactly 2 parameters");
return false;
}
auto it = pl->parameters.begin();
packet = *it;
++it;
headers = *it;
for (auto state : parserBlock->container->states) {
auto ps = new EBPFParserState(state, this);
states.push_back(ps);
}
auto ht = typeMap->getType(headers);
if (ht == nullptr) return false;
headerType = EBPFTypeFactory::instance->create(ht);
for (auto decl : parserBlock->container->parserLocals) {
if (decl->is<IR::P4ValueSet>()) {
cstring extName = EBPFObject::externalName(decl);
auto pvs = new EBPFValueSet(program, decl->to<IR::P4ValueSet>(), extName, visitor);
valueSets.emplace(decl->name.name, pvs);
}
}
return true;
}
void EBPFParser::emitTypes(CodeBuilder *builder) {
for (auto pvs : valueSets) {
pvs.second->emitTypes(builder);
}
}
void EBPFParser::emitValueSetInstances(CodeBuilder *builder) {
for (auto pvs : valueSets) {
pvs.second->emitInstance(builder);
}
}
void EBPFParser::emitRejectState(CodeBuilder *builder) {
builder->emitIndent();
builder->appendFormat("return %s;", builder->target->abortReturnCode().c_str());
builder->newline();
}
} // namespace P4::EBPF