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
|
/*
* Copyright 2019 The Android Open Source Project
*
* 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 "struct_def.h"
#include "fields/all_fields.h"
#include "util.h"
StructDef::StructDef(std::string name, FieldList fields) : StructDef(name, fields, nullptr) {}
StructDef::StructDef(std::string name, FieldList fields, StructDef* parent)
: ParentDef(name, fields, parent), total_size_(GetSize(true)) {}
PacketField* StructDef::GetNewField(const std::string& name, ParseLocation loc) const {
if (fields_.HasBody()) {
return new VariableLengthStructField(name, name_, loc);
} else {
return new StructField(name, name_, total_size_, loc);
}
}
TypeDef::Type StructDef::GetDefinitionType() const {
return TypeDef::Type::STRUCT;
}
void StructDef::GenSpecialize(std::ostream& s) const {
if (parent_ == nullptr) {
return;
}
s << "static " << name_ << "* Specialize(" << parent_->name_ << "* parent) {";
s << "ASSERT(" << name_ << "::IsInstance(*parent));";
s << "return static_cast<" << name_ << "*>(parent);";
s << "}";
}
void StructDef::GenToString(std::ostream& s) const {
s << "std::string ToString() {";
s << "std::stringstream ss;";
s << "ss << std::hex << std::showbase << \"" << name_ << " { \";";
if (fields_.size() > 0) {
s << "ss";
bool firstfield = true;
for (const auto& field : fields_) {
if (field->GetFieldType() == ReservedField::kFieldType ||
field->GetFieldType() == ChecksumStartField::kFieldType ||
field->GetFieldType() == FixedScalarField::kFieldType || field->GetFieldType() == CountField::kFieldType ||
field->GetFieldType() == SizeField::kFieldType)
continue;
s << (firstfield ? " << \"" : " << \", ") << field->GetName() << " = \" << ";
field->GenStringRepresentation(s, field->GetName() + "_");
if (firstfield) {
firstfield = false;
}
}
s << ";";
}
s << "ss << \" }\";";
s << "return ss.str();";
s << "}\n";
}
void StructDef::GenParse(std::ostream& s) const {
std::string iterator = (is_little_endian_ ? "Iterator<kLittleEndian>" : "Iterator<!kLittleEndian>");
if (fields_.HasBody()) {
s << "static std::optional<" << iterator << ">";
} else {
s << "static " << iterator;
}
s << " Parse(" << name_ << "* to_fill, " << iterator << " struct_begin_it ";
if (parent_ != nullptr) {
s << ", bool fill_parent = true) {";
} else {
s << ") {";
}
s << "auto to_bound = struct_begin_it;";
if (parent_ != nullptr) {
s << "if (fill_parent) {";
std::string parent_param = (parent_->parent_ == nullptr ? "" : ", true");
if (parent_->fields_.HasBody()) {
s << "auto parent_optional_it = " << parent_->name_ << "::Parse(to_fill, to_bound" << parent_param << ");";
if (fields_.HasBody()) {
s << "if (!parent_optional_it) { return {}; }";
} else {
s << "ASSERT(parent_optional_it);";
}
} else {
s << parent_->name_ << "::Parse(to_fill, to_bound" << parent_param << ");";
}
s << "}";
}
if (!fields_.HasBody()) {
s << "size_t end_index = struct_begin_it.NumBytesRemaining();";
s << "if (end_index < " << GetSize().bytes() << ")";
s << "{ return struct_begin_it.Subrange(0,0);}";
}
Size total_bits{0};
for (const auto& field : fields_) {
if (field->GetFieldType() != ReservedField::kFieldType && field->GetFieldType() != BodyField::kFieldType &&
field->GetFieldType() != FixedScalarField::kFieldType &&
field->GetFieldType() != ChecksumStartField::kFieldType && field->GetFieldType() != ChecksumField::kFieldType &&
field->GetFieldType() != CountField::kFieldType) {
total_bits += field->GetSize().bits();
}
}
s << "{";
s << "if (to_bound.NumBytesRemaining() < " << total_bits.bytes() << ")";
if (!fields_.HasBody()) {
s << "{ return to_bound.Subrange(to_bound.NumBytesRemaining(),0);}";
} else {
s << "{ return {};}";
}
s << "}";
for (const auto& field : fields_) {
if (field->GetFieldType() != ReservedField::kFieldType && field->GetFieldType() != BodyField::kFieldType &&
field->GetFieldType() != FixedScalarField::kFieldType && field->GetFieldType() != SizeField::kFieldType &&
field->GetFieldType() != ChecksumStartField::kFieldType && field->GetFieldType() != ChecksumField::kFieldType &&
field->GetFieldType() != CountField::kFieldType) {
s << "{";
int num_leading_bits =
field->GenBounds(s, GetStructOffsetForField(field->GetName()), Size(), field->GetStructSize());
s << "auto " << field->GetName() << "_ptr = &to_fill->" << field->GetName() << "_;";
field->GenExtractor(s, num_leading_bits, true);
s << "}";
}
if (field->GetFieldType() == CountField::kFieldType || field->GetFieldType() == SizeField::kFieldType) {
s << "{";
int num_leading_bits =
field->GenBounds(s, GetStructOffsetForField(field->GetName()), Size(), field->GetStructSize());
s << "auto " << field->GetName() << "_ptr = &to_fill->" << field->GetName() << "_extracted_;";
field->GenExtractor(s, num_leading_bits, true);
s << "}";
}
}
s << "return struct_begin_it + to_fill->size();";
s << "}";
}
void StructDef::GenParseFunctionPrototype(std::ostream& s) const {
s << "std::unique_ptr<" << name_ << "> Parse" << name_ << "(";
if (is_little_endian_) {
s << "Iterator<kLittleEndian>";
} else {
s << "Iterator<!kLittleEndian>";
}
s << "it);";
}
void StructDef::GenDefinition(std::ostream& s) const {
s << "class " << name_;
if (parent_ != nullptr) {
s << " : public " << parent_->name_;
} else {
if (is_little_endian_) {
s << " : public PacketStruct<kLittleEndian>";
} else {
s << " : public PacketStruct<!kLittleEndian>";
}
}
s << " {";
s << " public:";
GenConstructor(s);
s << " public:\n";
s << " virtual ~" << name_ << "() = default;\n";
GenSerialize(s);
s << "\n";
GenParse(s);
s << "\n";
GenSize(s);
s << "\n";
GenInstanceOf(s);
s << "\n";
GenSpecialize(s);
s << "\n";
GenToString(s);
s << "\n";
GenMembers(s);
for (const auto& field : fields_) {
if (field->GetFieldType() == CountField::kFieldType || field->GetFieldType() == SizeField::kFieldType) {
s << "\n private:\n";
s << " mutable " << field->GetDataType() << " " << field->GetName() << "_extracted_{0};";
}
}
s << "};\n";
if (fields_.HasBody()) {
GenParseFunctionPrototype(s);
}
s << "\n";
}
void StructDef::GenDefinitionPybind11(std::ostream& s) const {
s << "py::class_<" << name_;
if (parent_ != nullptr) {
s << ", " << parent_->name_;
} else {
if (is_little_endian_) {
s << ", PacketStruct<kLittleEndian>";
} else {
s << ", PacketStruct<!kLittleEndian>";
}
}
s << ", std::shared_ptr<" << name_ << ">";
s << ">(m, \"" << name_ << "\")";
s << ".def(py::init<>())";
s << ".def(\"Serialize\", [](" << GetTypeName() << "& obj){";
s << "std::vector<uint8_t> bytes;";
s << "BitInserter bi(bytes);";
s << "obj.Serialize(bi);";
s << "return bytes;})";
s << ".def(\"Parse\", &" << name_ << "::Parse)";
s << ".def(\"size\", &" << name_ << "::size)";
for (const auto& field : fields_) {
if (field->GetBuilderParameterType().empty()) {
continue;
}
s << ".def_readwrite(\"" << field->GetName() << "\", &" << name_ << "::" << field->GetName() << "_)";
}
s << ";\n";
}
void StructDef::GenConstructor(std::ostream& s) const {
if (parent_ != nullptr) {
s << name_ << "(const " << parent_->name_ << "& parent) : " << parent_->name_ << "(parent) {}";
s << name_ << "() : " << parent_->name_ << "() {";
} else {
s << name_ << "() {";
}
// Get the list of parent params.
FieldList parent_params;
if (parent_ != nullptr) {
parent_params = parent_->GetParamList().GetFieldsWithoutTypes({
PayloadField::kFieldType,
BodyField::kFieldType,
});
// Set constrained parent fields to their correct values.
for (const auto& field : parent_params) {
const auto& constraint = parent_constraints_.find(field->GetName());
if (constraint != parent_constraints_.end()) {
s << parent_->name_ << "::" << field->GetName() << "_ = ";
if (field->GetFieldType() == ScalarField::kFieldType) {
s << std::get<int64_t>(constraint->second) << ";";
} else if (field->GetFieldType() == EnumField::kFieldType) {
s << std::get<std::string>(constraint->second) << ";";
} else {
ERROR(field) << "Constraints on non enum/scalar fields should be impossible.";
}
}
}
}
s << "}\n";
}
Size StructDef::GetStructOffsetForField(std::string field_name) const {
auto size = Size(0);
for (auto it = fields_.begin(); it != fields_.end(); it++) {
// We've reached the field, end the loop.
if ((*it)->GetName() == field_name) break;
const auto& field = *it;
// When we need to parse this field, all previous fields should already be parsed.
if (field->GetStructSize().empty()) {
ERROR() << "Empty size for field " << (*it)->GetName() << " finding the offset for field: " << field_name;
}
size += field->GetStructSize();
}
// We need the offset until a body field.
if (parent_ != nullptr) {
auto parent_body_offset = static_cast<StructDef*>(parent_)->GetStructOffsetForField("body");
if (parent_body_offset.empty()) {
ERROR() << "Empty offset for body in " << parent_->name_ << " finding the offset for field: " << field_name;
}
size += parent_body_offset;
}
return size;
}
void StructDef::GenRustFieldNameAndType(std::ostream& s, bool include_fixed) const {
auto fields = fields_.GetFieldsWithoutTypes({
BodyField::kFieldType,
CountField::kFieldType,
PaddingField::kFieldType,
ReservedField::kFieldType,
SizeField::kFieldType,
});
for (const auto& field : fields) {
if (!include_fixed && field->GetFieldType() == FixedScalarField::kFieldType) {
continue;
}
field->GenRustNameAndType(s);
s << ", ";
}
}
void StructDef::GenRustFieldNames(std::ostream& s) const {
auto fields = fields_.GetFieldsWithoutTypes({
BodyField::kFieldType,
CountField::kFieldType,
PaddingField::kFieldType,
ReservedField::kFieldType,
SizeField::kFieldType,
});
for (const auto& field : fields) {
s << field->GetName();
s << ", ";
}
}
void StructDef::GenRustDeclarations(std::ostream& s) const {
s << "#[derive(Debug, Clone)] ";
s << "pub struct " << name_ << "{";
// Generate struct fields
auto fields = fields_.GetFieldsWithoutTypes({
BodyField::kFieldType,
CountField::kFieldType,
PaddingField::kFieldType,
ReservedField::kFieldType,
SizeField::kFieldType,
});
for (const auto& field : fields) {
s << "pub ";
field->GenRustNameAndType(s);
s << ", ";
}
s << "}\n";
}
void StructDef::GenRustImpls(std::ostream& s) const {
s << "impl " << name_ << "{";
s << "fn conforms(bytes: &[u8]) -> bool {";
GenRustConformanceCheck(s);
s << " true";
s << "}";
s << "pub fn parse(bytes: &[u8]) -> Result<Self> {";
auto fields = fields_.GetFieldsWithoutTypes({
BodyField::kFieldType,
});
for (const auto& field : fields) {
auto start_field_offset = GetOffsetForField(field->GetName(), false);
auto end_field_offset = GetOffsetForField(field->GetName(), true);
if (start_field_offset.empty() && end_field_offset.empty()) {
ERROR(field) << "Field location for " << field->GetName() << " is ambiguous, "
<< "no method exists to determine field location from begin() or end().\n";
}
field->GenBoundsCheck(s, start_field_offset, end_field_offset, name_);
field->GenRustGetter(s, start_field_offset, end_field_offset, name_);
}
fields = fields_.GetFieldsWithoutTypes({
BodyField::kFieldType,
CountField::kFieldType,
PaddingField::kFieldType,
ReservedField::kFieldType,
SizeField::kFieldType,
});
s << "Ok(Self {";
for (const auto& field : fields) {
if (field->GetFieldType() == FixedScalarField::kFieldType) {
s << field->GetName() << ": ";
static_cast<FixedScalarField*>(field)->GenValue(s);
} else {
s << field->GetName();
}
s << ", ";
}
s << "})}\n";
// write_to function
s << "fn write_to(&self, buffer: &mut [u8]) {";
GenRustWriteToFields(s);
s << "}\n";
s << "fn get_total_size(&self) -> usize {";
GenSizeRetVal(s);
s << "}";
s << "}\n";
}
void StructDef::GenRustDef(std::ostream& s) const {
GenRustDeclarations(s);
GenRustImpls(s);
}
|