summaryrefslogtreecommitdiffstats
path: root/src/vpp-api/vapi/vapi_json_parser.py
blob: 8728a1a6bc2fede9596694ccb93be4f3df61ca5f (plain)
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
#!/usr/bin/env python2

import json


class ParseError (Exception):
    pass


magic_prefix = "vl_api_"
magic_suffix = "_t"


def remove_magic(what):
    if what.startswith(magic_prefix) and what.endswith(magic_suffix):
        return what[len(magic_prefix): - len(magic_suffix)]
    return what


class Field(object):

    def __init__(self, field_name, field_type, array_len=None,
                 nelem_field=None):
        self.name = field_name
        self.type = field_type
        self.len = array_len
        self.nelem_field = nelem_field

    def __str__(self):
        if self.len is None:
            return "Field(name: %s, type: %s)" % (self.name, self.type)
        elif self.len > 0:
            return "Field(name: %s, type: %s, length: %s)" % (self.name,
                                                              self.type,
                                                              self.len)
        else:
            return (
                "Field(name: %s, type: %s, variable length stored in: %s)" %
                (self.name, self.type, self.nelem_field))

    def is_vla(self):
        return self.nelem_field is not None

    def has_vla(self):
        return self.is_vla() or self.type.has_vla()


class Type(object):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name


class SimpleType (Type):

    def __init__(self, name):
        super(SimpleType, self).__init__(name)

    def __str__(self):
        return self.name

    def has_vla(self):
        return False


def get_msg_header_defs(struct_type_class, field_class, json_parser, logger):
    return [
        struct_type_class(['msg_header1_t',
                           ['u16', '_vl_msg_id'],
                           ['u32', 'context'],
                           ],
                          json_parser, field_class, logger
                          ),
        struct_type_class(['msg_header2_t',
                           ['u16', '_vl_msg_id'],
                           ['u32', 'client_index'],
                           ['u32', 'context'],
                           ],
                          json_parser, field_class, logger
                          ),
    ]


class Struct(object):

    def __init__(self, name, fields):
        self.name = name
        self.fields = fields
        self.field_names = [n.name for n in self.fields]
        self.depends = [f.type for f in self.fields]

    def __str__(self):
        return "[%s]" % "], [".join([str(f) for f in self.fields])

    def has_vla(self):
        for f in self.fields:
            if f.has_vla():
                return True
        return False


class Enum(SimpleType):
    def __init__(self, name, value_pairs, enumtype):
        super(Enum, self).__init__(name)
        self.type = enumtype
        self.value_pairs = value_pairs

    def __str__(self):
        return "Enum(%s, [%s])" % (
            self.name,
            "], [" .join(["%s => %s" % (i, j) for i, j in self.value_pairs])
        )


class Union(Type):
    def __init__(self, name, type_pairs, crc):
        Type.__init__(self, name)
        self.crc = crc
        self.type_pairs = type_pairs
        self.depends = [t for t, _ in self.type_pairs]

    def __str__(self):
        return "Union(%s, [%s])" % (
            self.name,
            "], [" .join(["%s %s" % (i, j) for i, j in self.type_pairs])
        )

    def has_vla(self):
        return False


class Message(object):

    def __init__(self, logger, definition, json_parser):
        struct_type_class = json_parser.struct_type_class
        field_class = json_parser.field_class
        self.request = None
        self.logger = logger
        m = definition
        logger.debug("Parsing message definition `%s'" % m)
        name = m[0]
        self.name = name
        logger.debug("Message name is `%s'" % name)
        ignore = True
        self.header = None
        self.is_reply = json_parser.is_reply(self.name)
        self.is_event = json_parser.is_event(self.name)
        fields = []
        for header in get_msg_header_defs(struct_type_class, field_class,
                                          json_parser, logger):
            logger.debug("Probing header `%s'" % header.name)
            if header.is_part_of_def(m[1:]):
                self.header = header
                logger.debug("Found header `%s'" % header.name)
                fields.append(field_class(field_name='header',
                                          field_type=self.header))
                ignore = False
                break
        if ignore and not self.is_event and not self.is_reply:
            raise ParseError("While parsing message `%s': could not find all "
                             "common header fields" % name)
        for field in m[1:]:
            if len(field) == 1 and 'crc' in field:
                self.crc = field['crc']
                logger.debug("Found CRC `%s'" % self.crc)
                continue
            else:
                field_type = json_parser.lookup_type_like_id(field[0])
                logger.debug("Parsing message field `%s'" % field)
                if len(field) == 2:
                    if self.header is not None and\
                            self.header.has_field(field[1]):
                        continue
                    p = field_class(field_name=field[1],
                                    field_type=field_type)
                elif len(field) == 3:
                    if field[2] == 0:
                        raise ParseError(
                            "While parsing message `%s': variable length "
                            "array `%s' doesn't have reference to member "
                            "containing the actual length" % (
                                name, field[1]))
                    p = field_class(
                        field_name=field[1],
                        field_type=field_type,
                        array_len=field[2])
                elif len(field) == 4:
                    nelem_field = None
                    for f in fields:
                        if f.name == field[3]:
                            nelem_field = f
                    if nelem_field is None:
                        raise ParseError(
                            "While parsing message `%s': couldn't find "
                            "variable length array `%s' member containing "
                            "the actual length `%s'" % (
                                name, field[1], field[3]))
                    p = field_class(
                        field_name=field[1],
                        field_type=field_type,
                        array_len=field[2],
                        nelem_field=nelem_field)
                else:
                    raise Exception("Don't know how to parse message "
                                    "definition for message `%s': `%s'" %
                                    (m, m[1:]))
                logger.debug("Parsed field `%s'" % p)
                fields.append(p)
        self.fields = fields
        self.depends = [f.type for f in self.fields]
        logger.debug("Parsed message: %s" % self)

    def __str__(self):
        return "Message(%s, [%s], {crc: %s}" % \
            (self.name,
             "], [".join([str(f) for f in self.fields]),
             self.crc)


class StructType (Type, Struct):

    def __init__(self, definition, json_parser, field_class, logger):
        t = definition
        logger.debug("Parsing struct definition `%s'" % t)
        name = t[0]
        fields = []
        for field in t[1:]:
            if len(field) == 1 and 'crc' in field:
                self.crc = field['crc']
                continue
            field_type = json_parser.lookup_type_like_id(field[0])
            logger.debug("Parsing type field `%s'" % field)
            if len(field) == 2:
                p = field_class(field_name=field[1],
                                field_type=field_type)
            elif len(field) == 3:
                if field[2] == 0:
                    raise ParseError("While parsing type `%s': array `%s' has "
                                     "variable length" % (name, field[1]))
                p = field_class(field_name=field[1],
                                field_type=field_type,
                                array_len=field[2])
            elif len(field) == 4:
                nelem_field = None
                for f in fields:
                    if f.name == field[3]:
                        nelem_field = f
                if nelem_field is None:
                    raise ParseError(
                        "While parsing message `%s': couldn't find "
                        "variable length array `%s' member containing "
                        "the actual length `%s'" % (
                            name, field[1], field[3]))
                p = field_class(field_name=field[1],
                                field_type=field_type,
                                array_len=field[2],
                                nelem_field=nelem_field)
            else:
                raise ParseError(
                    "Don't know how to parse field `%s' of type definition "
                    "for type `%s'" % (field, t))
            fields.append(p)
        Type.__init__(self, name)
        Struct.__init__(self, name, fields)

    def __str__(self):
        return "StructType(%s, %s)" % (Type.__str__(self),
                                       Struct.__str__(self))

    def has_field(self, name):
        return name in self.field_names

    def is_part_of_def(self, definition):
        for idx in range(len(self.fields)):
            field = definition[idx]
            p = self.fields[idx]
            if field[1] != p.name:
                return False
            if field[0] != p.type.name:
                raise ParseError(
                    "Unexpected field type `%s' (should be `%s'), "
                    "while parsing msg/def/field `%s/%s/%s'" %
                    (field[0], p.type, p.name, definition, field))
        return True


class JsonParser(object):
    def __init__(self, logger, files, simple_type_class=SimpleType,
                 enum_class=Enum, union_class=Union,
                 struct_type_class=StructType, field_class=Field,
                 message_class=Message):
        self.services = {}
        self.messages = {}
        self.enums = {}
        self.unions = {}
        self.types = {
            x: simple_type_class(x) for x in [
                'i8', 'i16', 'i32', 'i64',
                'u8', 'u16', 'u32', 'u64',
                'f64'
            ]
        }

        self.replies = set()
        self.events = set()
        self.simple_type_class = simple_type_class
        self.enum_class = enum_class
        self.union_class = union_class
        self.struct_type_class = struct_type_class
        self.field_class = field_class
        self.message_class = message_class

        self.exceptions = []
        self.json_files = []
        self.types_by_json = {}
        self.enums_by_json = {}
        self.unions_by_json = {}
        self.messages_by_json = {}
        self.logger = logger
        for f in files:
            self.parse_json_file(f)
        self.finalize_parsing()

    def parse_json_file(self, path):
        self.logger.info("Parsing json api file: `%s'" % path)
        self.json_files.append(path)
        self.types_by_json[path] = []
        self.enums_by_json[path] = []
        self.unions_by_json[path] = []
        self.messages_by_json[path] = {}
        with open(path) as f:
            j = json.load(f)
            for k in j['services']:
                if k in self.services:
                    raise ParseError("Duplicate service `%s'" % k)
                self.services[k] = j['services'][k]
                self.replies.add(self.services[k]["reply"])
                if "events" in self.services[k]:
                    for x in self.services[k]["events"]:
                        self.events.add(x)
            for e in j['enums']:
                name = e[0]
                value_pairs = e[1:-1]
                enumtype = self.types[e[-1]["enumtype"]]
                enum = self.enum_class(name, value_pairs, enumtype)
                self.enums[enum.name] = enum
                self.logger.debug("Parsed enum: %s" % enum)
                self.enums_by_json[path].append(enum)
            exceptions = []
            progress = 0
            last_progress = 0
            while True:
                for u in j['unions']:
                    name = u[0]
                    if name in self.unions:
                        progress = progress + 1
                        continue
                    try:
                        type_pairs = [[self.lookup_type_like_id(t), n]
                                      for t, n in u[1:-1]]
                        crc = u[-1]["crc"]
                        union = self.union_class(name, type_pairs, crc)
                        progress = progress + 1
                    except ParseError as e:
                        exceptions.append(e)
                        continue
                    self.unions[union.name] = union
                    self.logger.debug("Parsed union: %s" % union)
                    self.unions_by_json[path].append(union)
                for t in j['types']:
                    if t[0] in self.types:
                        progress = progress + 1
                        continue
                    try:
                        type_ = self.struct_type_class(t, self,
                                                       self.field_class,
                                                       self.logger)
                        if type_.name in self.types:
                            raise ParseError(
                                "Duplicate type `%s'" % type_.name)
                        progress = progress + 1
                    except ParseError as e:
                        exceptions.append(e)
                        continue
                    self.types[type_.name] = type_
                    self.types_by_json[path].append(type_)
                    self.logger.debug("Parsed type: %s" % type_)
                if not exceptions:
                    # finished parsing
                    break
                if progress <= last_progress:
                    # cannot make forward progress
                    self.exceptions.extend(exceptions)
                exceptions = []
                last_progress = progress
                progress = 0
            prev_length = len(self.messages)
            processed = []
            while True:
                exceptions = []
                for m in j['messages']:
                    if m in processed:
                        continue
                    try:
                        msg = self.message_class(self.logger, m, self)
                        if msg.name in self.messages:
                            raise ParseError(
                                "Duplicate message `%s'" % msg.name)
                    except ParseError as e:
                        exceptions.append(e)
                        continue
                    self.messages[msg.name] = msg
                    self.messages_by_json[path][msg.name] = msg
                    processed.append(m)
                if prev_length == len(self.messages):
                    # cannot make forward progress ...
                    self.exceptions.extend(exceptions)
                    break
                prev_length = len(self.messages)

    def lookup_type_like_id(self, name):
        mundane_name = remove_magic(name)
        if name in self.types:
            return self.types[name]
        elif name in self.enums:
            return self.enums[name]
        elif name in self.unions:
            return self.unions[name]
        elif mundane_name in self.types:
            return self.types[mundane_name]
        elif mundane_name in self.enums:
            return self.enums[mundane_name]
        elif mundane_name in self.unions:
            return self.unions[mundane_name]
        raise ParseError(
            "Could not find type, enum or union by magic name `%s' nor by "
            "mundane name `%s'" % (name, mundane_name))

    def is_reply(self, message):
        return message in self.replies

    def is_event(self, message):
        return message in self.events

    def get_reply(self, message):
        return self.messages[self.services[message]['reply']]

    def finalize_parsing(self):
        if len(self.messages) == 0:
            for e in self.exceptions:
                self.logger.warning(e)
        for jn, j in self.messages_by_json.items():
            remove = []
            for n, m in j.items():
                try:
                    if not m.is_reply and not m.is_event:
                        try:
                            m.reply = self.get_reply(n)
                            if "stream" in self.services[m.name]:
                                m.reply_is_stream = \
                                    self.services[m.name]["stream"]
                            else:
                                m.reply_is_stream = False
                            m.reply.request = m
                        except:
                            raise ParseError(
                                "Cannot find reply to message `%s'" % n)
                except ParseError as e:
                    self.exceptions.append(e)
                    remove.append(n)

            self.messages_by_json[jn] = {
                k: v for k, v in j.items() if k not in remove}
/span> elog_string (elog_main_t * em, char *fmt, ...) { u32 offset; va_list va; va_start (va, fmt); offset = vec_len (em->string_table); em->string_table = (char *) va_format ((u8 *) em->string_table, fmt, &va); va_end (va); /* Null terminate string if it is not already. */ if (vec_end (em->string_table)[-1] != 0) vec_add1 (em->string_table, 0); return offset; } elog_event_t * elog_get_events (elog_main_t * em) { if (!em->events) em->events = elog_peek_events (em); return em->events; } static void maybe_fix_string_table_offset (elog_event_t * e, elog_event_type_t * t, u32 offset) { void *d = (u8 *) e->data; char *a; if (offset == 0) return; a = t->format_args; while (1) { uword n_bytes = 0, n_digits; if (a[0] == 0) break; /* Don't go past end of event data. */ ASSERT (d < (void *) (e->data + sizeof (e->data))); n_digits = parse_2digit_decimal (a + 1, &n_bytes); switch (a[0]) { case 'T': ASSERT (n_bytes == 4); clib_mem_unaligned (d, u32) += offset; break; case 'i': case 't': case 'f': case 's': break; default: ASSERT (0); break; } ASSERT (n_digits > 0 && n_digits <= 2); a += 1 + n_digits; d += n_bytes; } } static int elog_cmp (void *a1, void *a2) { elog_event_t *e1 = a1; elog_event_t *e2 = a2; return e1->time - e2->time; } void elog_merge (elog_main_t * dst, u8 * dst_tag, elog_main_t * src, u8 * src_tag) { elog_event_t *e; uword l; u32 string_table_offset_for_src_events; u32 track_offset_for_src_tracks; elog_track_t newt; int i; memset (&newt, 0, sizeof (newt)); elog_get_events (src); elog_get_events (dst); string_table_offset_for_src_events = vec_len (dst->string_table); vec_append (dst->string_table, src->string_table); l = vec_len (dst->events); vec_add (dst->events, src->events, vec_len (src->events)); /* Prepend the supplied tag (if any) to all dst track names */ if (dst_tag) { for (i = 0; i < vec_len (dst->tracks); i++) { elog_track_t *t = vec_elt_at_index (dst->tracks, i); char *new_name; new_name = (char *) format (0, "%s:%s%c", dst_tag, t->name, 0); vec_free (t->name); t->name = new_name; } } track_offset_for_src_tracks = vec_len (dst->tracks); /* Copy / tag source tracks */ for (i = 0; i < vec_len (src->tracks); i++) { elog_track_t *t = vec_elt_at_index (src->tracks, i); if (src_tag) newt.name = (char *) format (0, "%s:%s%c", src_tag, t->name, 0); else newt.name = (char *) format (0, "%s%c", t->name, 0); (void) elog_track_register (dst, &newt); vec_free (newt.name); } /* Across all (copied) src events... */ for (e = dst->events + l; e < vec_end (dst->events); e++) { elog_event_type_t *t = vec_elt_at_index (src->event_types, e->type); /* Remap type from src -> dst. */ e->type = find_or_create_type (dst, t); /* Remap string table offsets for 'T' format args */ maybe_fix_string_table_offset (e, t, string_table_offset_for_src_events); /* Remap track */ e->track += track_offset_for_src_tracks; } /* Adjust event times for relative starting times of event streams. */ { f64 dt_event, dt_os_nsec, dt_clock_nsec; /* Set clock parameters if dst was not generated by unserialize. */ if (dst->serialize_time.cpu == 0) { dst->init_time = src->init_time; dst->serialize_time = src->serialize_time; dst->nsec_per_cpu_clock = src->nsec_per_cpu_clock; } dt_os_nsec = elog_time_stamp_diff_os_nsec (&src->init_time, &dst->init_time); dt_event = dt_os_nsec; dt_clock_nsec = (elog_time_stamp_diff_cpu (&src->init_time, &dst->init_time) * .5 * (dst->nsec_per_cpu_clock + src->nsec_per_cpu_clock)); /* Heuristic to see if src/dst came from same time source. If frequencies are "the same" and os clock and cpu clock agree to within 100e-9 secs about time difference between src/dst init_time, then we use cpu clock. Otherwise we use OS clock. */ if (fabs (src->nsec_per_cpu_clock - dst->nsec_per_cpu_clock) < 1e-2 && fabs (dt_os_nsec - dt_clock_nsec) < 100) dt_event = dt_clock_nsec; /* Convert to seconds. */ dt_event *= 1e-9; if (dt_event > 0) { /* Src started after dst. */ for (e = dst->events + l; e < vec_end (dst->events); e++) e->time += dt_event; } else { /* Dst started after src. */ for (e = dst->events + 0; e < dst->events + l; e++) e->time += dt_event; } } /* Sort events by increasing time. */ vec_sort_with_function (dst->events, elog_cmp); /* Recreate the event ring or the results won't serialize */ { int i; ASSERT (dst->cpu_timer.seconds_per_clock); elog_alloc (dst, vec_len (dst->events)); for (i = 0; i < vec_len (dst->events); i++) { elog_event_t *es, *ed; es = dst->events + i; ed = dst->event_ring + i; ed[0] = es[0]; /* Invert elog_peek_events calculation */ ed->time_cycles = (es->time / dst->cpu_timer.seconds_per_clock) + dst->init_time.cpu; } dst->n_total_events = vec_len (dst->events); } } static void serialize_elog_event (serialize_main_t * m, va_list * va) { elog_main_t *em = va_arg (*va, elog_main_t *); elog_event_t *e = va_arg (*va, elog_event_t *); elog_event_type_t *t = vec_elt_at_index (em->event_types, e->type); u8 *d = e->data; u8 *p = (u8 *) t->format_args; serialize_integer (m, e->type, sizeof (e->type)); serialize_integer (m, e->track, sizeof (e->track)); serialize (m, serialize_f64, e->time); while (*p) { uword n_digits, n_bytes = 0; n_digits = parse_2digit_decimal ((char *) p + 1, &n_bytes); switch (p[0]) { case 'i': case 't': case 'T': if (n_bytes == 1) serialize_integer (m, d[0], sizeof (u8)); else if (n_bytes == 2) serialize_integer (m, clib_mem_unaligned (d, u16), sizeof (u16)); else if (n_bytes == 4) serialize_integer (m, clib_mem_unaligned (d, u32), sizeof (u32)); else if (n_bytes == 8) serialize (m, serialize_64, clib_mem_unaligned (d, u64)); else ASSERT (0); break; case 's': serialize_cstring (m, (char *) d); if (n_bytes == 0) n_bytes = strlen ((char *) d) + 1; break; case 'f': if (n_bytes == 4) serialize (m, serialize_f32, clib_mem_unaligned (d, f32)); else if (n_bytes == 8) serialize (m, serialize_f64, clib_mem_unaligned (d, f64)); else ASSERT (0); break; default: ASSERT (0); break; } p += 1 + n_digits; d += n_bytes; } } static void unserialize_elog_event (serialize_main_t * m, va_list * va) { elog_main_t *em = va_arg (*va, elog_main_t *); elog_event_t *e = va_arg (*va, elog_event_t *); elog_event_type_t *t; u8 *p, *d; { u16 tmp[2]; unserialize_integer (m, &tmp[0], sizeof (e->type)); unserialize_integer (m, &tmp[1], sizeof (e->track)); e->type = tmp[0]; e->track = tmp[1]; /* Make sure it fits. */ ASSERT (e->type == tmp[0]); ASSERT (e->track == tmp[1]); } t = vec_elt_at_index (em->event_types, e->type); unserialize (m, unserialize_f64, &e->time); d = e->data; p = (u8 *) t->format_args; while (p && *p) { uword n_digits, n_bytes = 0; u32 tmp; n_digits = parse_2digit_decimal ((char *) p + 1, &n_bytes); switch (p[0]) { case 'i': case 't': case 'T': if (n_bytes == 1) { unserialize_integer (m, &tmp, sizeof (u8)); d[0] = tmp; } else if (n_bytes == 2) { unserialize_integer (m, &tmp, sizeof (u16)); clib_mem_unaligned (d, u16) = tmp; } else if (n_bytes == 4) { unserialize_integer (m, &tmp, sizeof (u32)); clib_mem_unaligned (d, u32) = tmp; } else if (n_bytes == 8) { u64 x; unserialize (m, unserialize_64, &x); clib_mem_unaligned (d, u64) = x; } else ASSERT (0); break; case 's': { char *t; unserialize_cstring (m, &t); if (n_bytes == 0) n_bytes = strlen (t) + 1; clib_memcpy (d, t, clib_min (n_bytes, vec_len (t))); vec_free (t); break; } case 'f': if (n_bytes == 4) { f32 x; unserialize (m, unserialize_f32, &x); clib_mem_unaligned (d, f32) = x; } else if (n_bytes == 8) { f64 x; unserialize (m, unserialize_f64, &x); clib_mem_unaligned (d, f64) = x; } else ASSERT (0); break; default: ASSERT (0); break; } p += 1 + n_digits; d += n_bytes; } } static void serialize_elog_event_type (serialize_main_t * m, va_list * va) { elog_event_type_t *t = va_arg (*va, elog_event_type_t *); int n = va_arg (*va, int); int i, j; for (i = 0; i < n; i++) { serialize_cstring (m, t[i].format); serialize_cstring (m, t[i].format_args); serialize_integer (m, t[i].type_index_plus_one, sizeof (t->type_index_plus_one)); serialize_integer (m, t[i].n_enum_strings, sizeof (t[i].n_enum_strings)); for (j = 0; j < t[i].n_enum_strings; j++) serialize_cstring (m, t[i].enum_strings_vector[j]); } } static void unserialize_elog_event_type (serialize_main_t * m, va_list * va) { elog_event_type_t *t = va_arg (*va, elog_event_type_t *); int n = va_arg (*va, int); int i, j; for (i = 0; i < n; i++) { unserialize_cstring (m, &t[i].format); unserialize_cstring (m, &t[i].format_args); unserialize_integer (m, &t[i].type_index_plus_one, sizeof (t->type_index_plus_one)); unserialize_integer (m, &t[i].n_enum_strings, sizeof (t[i].n_enum_strings)); vec_resize (t[i].enum_strings_vector, t[i].n_enum_strings); for (j = 0; j < t[i].n_enum_strings; j++) unserialize_cstring (m, &t[i].enum_strings_vector[j]); } } static void serialize_elog_track (serialize_main_t * m, va_list * va) { elog_track_t *t = va_arg (*va, elog_track_t *); int n = va_arg (*va, int); int i; for (i = 0; i < n; i++) { serialize_cstring (m, t[i].name); } } static void unserialize_elog_track (serialize_main_t * m, va_list * va) { elog_track_t *t = va_arg (*va, elog_track_t *); int n = va_arg (*va, int); int i; for (i = 0; i < n; i++) { unserialize_cstring (m, &t[i].name); } } static void serialize_elog_time_stamp (serialize_main_t * m, va_list * va) { elog_time_stamp_t *st = va_arg (*va, elog_time_stamp_t *); serialize (m, serialize_64, st->os_nsec); serialize (m, serialize_64, st->cpu); } static void unserialize_elog_time_stamp (serialize_main_t * m, va_list * va) { elog_time_stamp_t *st = va_arg (*va, elog_time_stamp_t *); unserialize (m, unserialize_64, &st->os_nsec); unserialize (m, unserialize_64, &st->cpu); } static char *elog_serialize_magic = "elog v0"; void serialize_elog_main (serialize_main_t * m, va_list * va) { elog_main_t *em = va_arg (*va, elog_main_t *); elog_event_t *e; serialize_magic (m, elog_serialize_magic, strlen (elog_serialize_magic)); serialize_integer (m, em->event_ring_size, sizeof (u32)); elog_time_now (&em->serialize_time); serialize (m, serialize_elog_time_stamp, &em->serialize_time); serialize (m, serialize_elog_time_stamp, &em->init_time); vec_serialize (m, em->event_types, serialize_elog_event_type); vec_serialize (m, em->tracks, serialize_elog_track); vec_serialize (m, em->string_table, serialize_vec_8); /* Free old events (cached) in case they have changed. */ vec_free (em->events); elog_get_events (em); serialize_integer (m, vec_len (em->events), sizeof (u32)); /* SMP logs can easily have local time paradoxes... */ vec_sort_with_function (em->events, elog_cmp); vec_foreach (e, em->events) serialize (m, serialize_elog_event, em, e); } void unserialize_elog_main (serialize_main_t * m, va_list * va) { elog_main_t *em = va_arg (*va, elog_main_t *); uword i; u32 rs; unserialize_check_magic (m, elog_serialize_magic, strlen (elog_serialize_magic)); unserialize_integer (m, &rs, sizeof (u32)); em->event_ring_size = rs; elog_init (em, em->event_ring_size); unserialize (m, unserialize_elog_time_stamp, &em->serialize_time); unserialize (m, unserialize_elog_time_stamp, &em->init_time); em->nsec_per_cpu_clock = elog_nsec_per_clock (em); vec_unserialize (m, &em->event_types, unserialize_elog_event_type); for (i = 0; i < vec_len (em->event_types); i++) new_event_type (em, i); vec_unserialize (m, &em->tracks, unserialize_elog_track); vec_unserialize (m, &em->string_table, unserialize_vec_8); { u32 ne; elog_event_t *e; unserialize_integer (m, &ne, sizeof (u32)); vec_resize (em->events, ne); vec_foreach (e, em->events) unserialize (m, unserialize_elog_event, em, e); } } /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */