]> git.ipfire.org Git - thirdparty/lldpd.git/blob - src/marshal.c
marshal: avoid NULL pointer arithmetic
[thirdparty/lldpd.git] / src / marshal.c
1 /* -*- mode: c; c-file-style: "openbsd" -*- */
2 /*
3 * Copyright (c) 2012 Vincent Bernat <bernat@luffy.cx>
4 *
5 * Permission to use, copy, modify, and/or distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
18 #define MARSHAL_EXPORT
19 #include "marshal.h"
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <sys/types.h>
24 #include <sys/queue.h>
25 #include <string.h>
26
27 #include "compat/compat.h"
28 #include "log.h"
29
30 #include "lldpd-structs.h"
31
32 /* Stolen from CCAN */
33 #if HAVE_ALIGNOF
34 # define ALIGNOF(t) (__alignof__(t))
35 #else
36 # define ALIGNOF(t) ((sizeof(t) > 1)?((char *)(&((struct { char c; t _h; } *)0)->_h) - (char *)0):1)
37 #endif
38
39 /* A serialized object */
40 struct marshal_serialized {
41 void *orig; /* Original reference. Also enforce alignment. */
42 size_t size;
43 unsigned char object[0];
44 };
45
46 struct marshal_info marshal_info_string = {
47 .name = "null string",
48 .size = 0,
49 .pointers = {MARSHAL_SUBINFO_NULL},
50 };
51 struct marshal_info marshal_info_fstring = {
52 .name = "fixed string",
53 .size = 0,
54 .pointers = {MARSHAL_SUBINFO_NULL},
55 };
56 struct marshal_info marshal_info_ignore = {
57 .name = "ignored",
58 .size = 0,
59 .pointers = {MARSHAL_SUBINFO_NULL},
60 };
61
62 /* List of already seen pointers */
63 struct ref {
64 TAILQ_ENTRY(ref) next;
65 void *pointer;
66 uintptr_t dummy; /* To renumerate pointers */
67 };
68 TAILQ_HEAD(ref_l, ref);
69
70 /* Serialize the given object. */
71 ssize_t
72 marshal_serialize_(struct marshal_info *mi, void *unserialized, void **input,
73 int skip, void *_refs, int osize)
74 {
75 struct ref_l *refs = _refs;
76 struct ref *cref;
77 int size;
78 size_t len;
79 struct marshal_subinfo *current;
80 struct marshal_serialized *new = NULL, *serialized = NULL;
81 uintptr_t dummy = 1;
82
83 log_debug("marshal", "start serialization of %s", mi->name);
84
85 /* Check if we have already serialized this one. */
86 if (!refs) {
87 refs = calloc(1, sizeof(struct ref_l));
88 if (!refs) {
89 log_warnx("marshal", "unable to allocate memory for list of references");
90 return -1;
91 }
92 TAILQ_INIT(refs);
93 }
94 TAILQ_FOREACH(cref, refs, next) {
95 if (unserialized == cref->pointer)
96 return 0;
97 /* dummy should be higher than any existing dummy */
98 if (cref->dummy >= dummy) dummy = cref->dummy + 1;
99 }
100
101 /* Handle special cases. */
102 size = mi->size;
103 if (!strcmp(mi->name, "null string"))
104 /* We know we can't be called with NULL */
105 size = strlen((char *)unserialized) + 1;
106 else if (!strcmp(mi->name, "fixed string"))
107 size = osize;
108
109 /* Allocate serialized structure */
110 len = sizeof(struct marshal_serialized) + (skip?0:size);
111 serialized = calloc(1, len);
112 if (!serialized) {
113 log_warnx("marshal", "unable to allocate memory to serialize structure %s",
114 mi->name);
115 len = -1;
116 goto marshal_error;
117 }
118 /* We don't use the original pointer but a dummy one. */
119 serialized->orig = (unsigned char*)dummy;
120
121 /* Append the new reference */
122 if (!(cref = calloc(1, sizeof(struct ref)))) {
123 log_warnx("marshal", "unable to allocate memory for list of references");
124 free(serialized);
125 len = -1;
126 goto marshal_error;
127 }
128 cref->pointer = unserialized;
129 cref->dummy = dummy;
130 TAILQ_INSERT_TAIL(refs, cref, next);
131
132 /* First, serialize the main structure */
133 if (!skip)
134 memcpy(serialized->object, unserialized, size);
135
136 /* Then, serialize inner structures */
137 for (current = mi->pointers; current->mi; current++) {
138 size_t sublen;
139 size_t padlen;
140 void *source;
141 void *target = NULL;
142 if (current->kind == ignore) continue;
143 if (current->kind == pointer) {
144 memcpy(&source,
145 (unsigned char *)unserialized + current->offset,
146 sizeof(void *));
147 if (source == NULL) continue;
148 } else
149 source = (void *)((unsigned char *)unserialized + current->offset);
150 if (current->offset2)
151 memcpy(&osize, (unsigned char*)unserialized + current->offset2, sizeof(int));
152 target = NULL;
153 sublen = marshal_serialize_(current->mi,
154 source, &target,
155 current->kind == substruct, refs, osize);
156 if (sublen == -1) {
157 log_warnx("marshal", "unable to serialize substructure %s for %s",
158 current->mi->name, mi->name);
159 free(serialized);
160 return -1;
161 }
162 /* We want to put the renumerated pointer instead of the real one. */
163 if (current->kind == pointer && !skip) {
164 TAILQ_FOREACH(cref, refs, next) {
165 if (source == cref->pointer) {
166 void *fakepointer = (unsigned char*)cref->dummy;
167 memcpy((unsigned char *)serialized->object + current->offset,
168 &fakepointer, sizeof(void *));
169 break;
170 }
171 }
172 }
173 if (sublen == 0) continue; /* This was already serialized */
174 /* Append the result, force alignment to be able to unserialize it */
175 padlen = ALIGNOF(struct marshal_serialized);
176 padlen = (padlen - (len % padlen)) % padlen;
177 new = realloc(serialized, len + padlen + sublen);
178 if (!new) {
179 log_warnx("marshal", "unable to allocate more memory to serialize structure %s",
180 mi->name);
181 free(serialized);
182 free(target);
183 len = -1;
184 goto marshal_error;
185 }
186 memset((unsigned char *)new + len, 0, padlen);
187 memcpy((unsigned char *)new + len + padlen, target, sublen);
188 free(target);
189 len += sublen + padlen;
190 serialized = (struct marshal_serialized *)new;
191 }
192
193 serialized->size = len;
194 *input = serialized;
195 marshal_error:
196 if (refs && !_refs) {
197 struct ref *cref, *cref_next;
198 for (cref = TAILQ_FIRST(refs);
199 cref != NULL;
200 cref = cref_next) {
201 cref_next = TAILQ_NEXT(cref, next);
202 TAILQ_REMOVE(refs, cref, next);
203 free(cref);
204 }
205 free(refs);
206 }
207 return len;
208 }
209
210 /* This structure is used to track memory allocation when serializing */
211 struct gc {
212 TAILQ_ENTRY(gc) next;
213 void *pointer;
214 void *orig; /* Original reference (not valid anymore !) */
215 };
216 TAILQ_HEAD(gc_l, gc);
217
218 static void*
219 marshal_alloc(struct gc_l *pointers, size_t len, void *orig)
220 {
221 struct gc *gpointer = NULL;
222
223 void *result = calloc(1, len);
224 if (!result) return NULL;
225 if ((gpointer = (struct gc *)calloc(1,
226 sizeof(struct gc))) == NULL) {
227 free(result);
228 return NULL;
229 }
230 gpointer->pointer = result;
231 gpointer->orig = orig;
232 TAILQ_INSERT_TAIL(pointers, gpointer, next);
233 return result;
234 }
235 static void
236 marshal_free(struct gc_l *pointers, int gconly)
237 {
238 struct gc *pointer, *pointer_next;
239 for (pointer = TAILQ_FIRST(pointers);
240 pointer != NULL;
241 pointer = pointer_next) {
242 pointer_next = TAILQ_NEXT(pointer, next);
243 TAILQ_REMOVE(pointers, pointer, next);
244 if (!gconly)
245 free(pointer->pointer);
246 free(pointer);
247 }
248 }
249
250
251 /* Unserialize the given object. */
252 size_t
253 marshal_unserialize_(struct marshal_info *mi, void *buffer, size_t len, void **output,
254 void *_pointers, int skip, int osize)
255 {
256 int total_len = sizeof(struct marshal_serialized) + (skip?0:mi->size);
257 struct marshal_serialized *serialized = buffer;
258 struct gc_l *pointers = _pointers;
259 int size, already, extra = 0;
260 void *new;
261 struct marshal_subinfo *current;
262 struct gc *apointer;
263
264 log_debug("marshal", "start unserialization of %s", mi->name);
265
266 if (len < sizeof(struct marshal_serialized) || len < total_len) {
267 log_warnx("marshal", "data to deserialize is too small (%zu) for structure %s",
268 len, mi->name);
269 return 0;
270 }
271
272 /* Initialize garbage collection */
273 if (!pointers) {
274 pointers = calloc(1, sizeof(struct gc_l));
275 if (!pointers) {
276 log_warnx("marshal", "unable to allocate memory for garbage collection");
277 return 0;
278 }
279 TAILQ_INIT(pointers);
280 }
281
282 /* Special cases */
283 size = mi->size;
284 if (!strcmp(mi->name, "null string") || !strcmp(mi->name, "fixed string")) {
285 switch (mi->name[0]) {
286 case 'n': size = strnlen((char *)serialized->object,
287 len - sizeof(struct marshal_serialized)) + 1; break;
288 case 'f': size = osize; extra=1; break; /* The extra byte is to ensure that
289 the string is null terminated. */
290 }
291 if (size > len - sizeof(struct marshal_serialized)) {
292 log_warnx("marshal", "data to deserialize contains a string too long");
293 total_len = 0;
294 goto unmarshal_error;
295 }
296 total_len += size;
297 }
298
299 /* First, the main structure */
300 if (!skip) {
301 if ((*output = marshal_alloc(pointers, size + extra, serialized->orig)) == NULL) {
302 log_warnx("marshal", "unable to allocate memory to unserialize structure %s",
303 mi->name);
304 total_len = 0;
305 goto unmarshal_error;
306 }
307 memcpy(*output, serialized->object, size);
308 }
309
310 /* Then, each substructure */
311 for (current = mi->pointers; current->mi; current++) {
312 size_t sublen;
313 size_t padlen;
314 new = (unsigned char *)*output + current->offset;
315 if (current->kind == ignore) {
316 memset((unsigned char *)*output + current->offset,
317 0, sizeof(void *));
318 continue;
319 }
320 if (current->kind == pointer) {
321 if (*(void **)new == NULL) continue;
322
323 /* Did we already see this reference? */
324 already = 0;
325 TAILQ_FOREACH(apointer, pointers, next)
326 if (apointer->orig == *(void **)new) {
327 memcpy((unsigned char *)*output + current->offset,
328 &apointer->pointer, sizeof(void *));
329 already = 1;
330 break;
331 }
332 if (already) continue;
333 }
334 /* Deserialize */
335 if (current->offset2)
336 memcpy(&osize, (unsigned char *)*output + current->offset2, sizeof(int));
337 padlen = ALIGNOF(struct marshal_serialized);
338 padlen = (padlen - (total_len % padlen)) % padlen;
339 if (len < total_len + padlen || ((sublen = marshal_unserialize_(current->mi,
340 (unsigned char *)buffer + total_len + padlen,
341 len - total_len - padlen, &new, pointers,
342 current->kind == substruct, osize)) == 0)) {
343 log_warnx("marshal", "unable to serialize substructure %s for %s",
344 current->mi->name, mi->name);
345 total_len = 0;
346 goto unmarshal_error;
347 }
348 /* Link the result */
349 if (current->kind == pointer)
350 memcpy((unsigned char *)*output + current->offset,
351 &new, sizeof(void *));
352 total_len += sublen + padlen;
353 }
354
355 unmarshal_error:
356 if (pointers && !_pointers) {
357 marshal_free(pointers, (total_len > 0));
358 free(pointers);
359 }
360 return total_len;
361 }