1 /*
2  * Copyright (c) 2008-2018, Dave Benson and the protobuf-c authors.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *
12  *     * Redistributions in binary form must reproduce the above
13  * copyright notice, this list of conditions and the following disclaimer
14  * in the documentation and/or other materials provided with the
15  * distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 /*! \file
31  * \mainpage Introduction
32  *
33  * This is [protobuf-c], a C implementation of [Protocol Buffers].
34  *
35  * This file defines the public API for the `libprotobuf-c` support library.
36  * This API includes interfaces that can be used directly by client code as well
37  * as the interfaces used by the code generated by the `protoc-c` compiler.
38  *
39  * The `libprotobuf-c` support library performs the actual serialization and
40  * deserialization of Protocol Buffers messages. It interacts with structures,
41  * definitions, and metadata generated by the `protoc-c` compiler from .proto
42  * files.
43  *
44  * \authors Dave Benson and the `protobuf-c` authors.
45  *
46  * \copyright 2008-2014. Licensed under the terms of the [BSD-2-Clause] license.
47  *
48  * [protobuf-c]:       https://github.com/protobuf-c/protobuf-c
49  * [Protocol Buffers]: https://developers.google.com/protocol-buffers/
50  * [BSD-2-Clause]:     http://opensource.org/licenses/BSD-2-Clause
51  *
52  * \page gencode Generated Code
53  *
54  * For each enum, we generate a C enum. For each message, we generate a C
55  * structure which can be cast to a `ProtobufCMessage`.
56  *
57  * For each enum and message, we generate a descriptor object that allows us to
58  * implement a kind of reflection on the structures.
59  *
60  * First, some naming conventions:
61  *
62  * - The name of the type for enums and messages and services is camel case
63  *   (meaning WordsAreCrammedTogether) except that double underscores are used
64  *   to delimit scopes. For example, the following `.proto` file:
65  *
66 ~~~{.proto}
67         package foo.bar;
68         message BazBah {
69             optional int32 val = 1;
70         }
71 ~~~
72  *
73  * would generate a C type `Foo__Bar__BazBah`.
74  *
75  * - Identifiers for functions and globals are all lowercase, with camel case
76  *   words separated by single underscores. For example, one of the function
77  *   prototypes generated by `protoc-c` for the above example:
78  *
79 ~~~{.c}
80 Foo__Bar__BazBah *
81        foo__bar__baz_bah__unpack
82                      (ProtobufCAllocator  *allocator,
83                       size_t               len,
84                       const uint8_t       *data);
85 ~~~
86  *
87  * - Identifiers for enum values contain an uppercase prefix which embeds the
88  *   package name and the enum type name.
89  *
90  * - A double underscore is used to separate further components of identifier
91  *   names.
92  *
93  * For example, in the name of the unpack function above, the package name
94  * `foo.bar` has become `foo__bar`, the message name BazBah has become
95  * `baz_bah`, and the method name is `unpack`. These are all joined with double
96  * underscores to form the C identifier `foo__bar__baz_bah__unpack`.
97  *
98  * We also generate descriptor objects for messages and enums. These are
99  * declared in the `.pb-c.h` files:
100  *
101 ~~~{.c}
102 extern const ProtobufCMessageDescriptor foo__bar__baz_bah__descriptor;
103 ~~~
104  *
105  * The message structures all begin with `ProtobufCMessageDescriptor *` which is
106  * sufficient to allow them to be cast to `ProtobufCMessage`.
107  *
108  * For each message defined in a `.proto` file, we generate a number of
109  * functions and macros. Each function name contains a prefix based on the
110  * package name and message name in order to make it a unique C identifier.
111  *
112  * - `INIT`. Statically initializes a message object, initializing its
113  *   descriptor and setting its fields to default values. Uninitialized
114  *   messages cannot be processed by the protobuf-c library.
115  *
116 ~~~{.c}
117 #define FOO__BAR__BAZ_BAH__INIT \
118  { PROTOBUF_C_MESSAGE_INIT (&foo__bar__baz_bah__descriptor), 0 }
119 ~~~
120  * - `init()`. Initializes a message object, initializing its descriptor and
121  *   setting its fields to default values. Uninitialized messages cannot be
122  *   processed by the protobuf-c library.
123  *
124 ~~~{.c}
125 void foo__bar__baz_bah__init
126                      (Foo__Bar__BazBah *message);
127 ~~~
128  * - `unpack()`. Unpacks data for a particular message format. Note that the
129  *   `allocator` parameter is usually `NULL` to indicate that the system's
130  *   `malloc()` and `free()` functions should be used for dynamically allocating
131  *   memory.
132  *
133 ~~~{.c}
134 Foo__Bar__BazBah *
135        foo__bar__baz_bah__unpack
136                      (ProtobufCAllocator  *allocator,
137                       size_t               len,
138                       const uint8_t       *data);
139 ~~~
140  *
141  * - `free_unpacked()`. Frees a message object obtained with the `unpack()`
142  *   method. Freeing `NULL` is allowed (the same as with `free()`).
143  *
144 ~~~{.c}
145 void   foo__bar__baz_bah__free_unpacked
146                      (Foo__Bar__BazBah *message,
147                       ProtobufCAllocator *allocator);
148 ~~~
149  *
150  * - `get_packed_size()`. Calculates the length in bytes of the serialized
151  *   representation of the message object.
152  *
153 ~~~{.c}
154 size_t foo__bar__baz_bah__get_packed_size
155                      (const Foo__Bar__BazBah   *message);
156 ~~~
157  *
158  * - `pack()`. Pack a message object into a preallocated buffer. Assumes that
159  *   the buffer is large enough. (Use `get_packed_size()` first.)
160  *
161 ~~~{.c}
162 size_t foo__bar__baz_bah__pack
163                      (const Foo__Bar__BazBah   *message,
164                       uint8_t             *out);
165 ~~~
166  *
167  * - `pack_to_buffer()`. Packs a message into a "virtual buffer". This is an
168  *   object which defines an "append bytes" callback to consume data as it is
169  *   serialized.
170  *
171 ~~~{.c}
172 size_t foo__bar__baz_bah__pack_to_buffer
173                      (const Foo__Bar__BazBah   *message,
174                       ProtobufCBuffer     *buffer);
175 ~~~
176  *
177  * \page pack Packing and unpacking messages
178  *
179  * To pack a message, first compute the packed size of the message with
180  * protobuf_c_message_get_packed_size(), then allocate a buffer of at least
181  * that size, then call protobuf_c_message_pack().
182  *
183  * Alternatively, a message can be serialized without calculating the final size
184  * first. Use the protobuf_c_message_pack_to_buffer() function and provide a
185  * ProtobufCBuffer object which implements an "append" method that consumes
186  * data.
187  *
188  * To unpack a message, call the protobuf_c_message_unpack() function. The
189  * result can be cast to an object of the type that matches the descriptor for
190  * the message.
191  *
192  * The result of unpacking a message should be freed with
193  * protobuf_c_message_free_unpacked().
194  */
195 
196 #ifndef PROTOBUF_C_H
197 #define PROTOBUF_C_H
198 
199 #include <assert.h>
200 #include <limits.h>
201 #include <stddef.h>
202 #include <inttypes.h>	/* stdint.h not present on older systems */
203 
204 #ifdef __cplusplus
205 # define PROTOBUF_C__BEGIN_DECLS	extern "C" {
206 # define PROTOBUF_C__END_DECLS		}
207 #else
208 # define PROTOBUF_C__BEGIN_DECLS
209 # define PROTOBUF_C__END_DECLS
210 #endif
211 
212 PROTOBUF_C__BEGIN_DECLS
213 
214 #if defined(_WIN32) && defined(PROTOBUF_C_USE_SHARED_LIB)
215 # ifdef PROTOBUF_C_EXPORT
216 #  define PROTOBUF_C__API __declspec(dllexport)
217 # else
218 #  define PROTOBUF_C__API __declspec(dllimport)
219 # endif
220 #else
221 # define PROTOBUF_C__API
222 #endif
223 
224 #if !defined(PROTOBUF_C__NO_DEPRECATED) && \
225 	((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
226 # define PROTOBUF_C__DEPRECATED __attribute__((__deprecated__))
227 #else
228 # define PROTOBUF_C__DEPRECATED
229 #endif
230 
231 #ifndef PROTOBUF_C__FORCE_ENUM_TO_BE_INT_SIZE
232  #define PROTOBUF_C__FORCE_ENUM_TO_BE_INT_SIZE(enum_name) \
233   , _##enum_name##_IS_INT_SIZE = INT_MAX
234 #endif
235 
236 #define PROTOBUF_C__SERVICE_DESCRIPTOR_MAGIC    0x14159bc3
237 #define PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC    0x28aaeef9
238 #define PROTOBUF_C__ENUM_DESCRIPTOR_MAGIC       0x114315af
239 
240 /* Empty string used for initializers */
241 extern const char protobuf_c_empty_string[];
242 
243 /**
244  * \defgroup api Public API
245  *
246  * This is the public API for `libprotobuf-c`. These interfaces are stable and
247  * subject to Semantic Versioning guarantees.
248  *
249  * @{
250  */
251 
252 /**
253  * Values for the `flags` word in `ProtobufCFieldDescriptor`.
254  */
255 typedef enum {
256 	/** Set if the field is repeated and marked with the `packed` option. */
257 	PROTOBUF_C_FIELD_FLAG_PACKED		= (1 << 0),
258 
259 	/** Set if the field is marked with the `deprecated` option. */
260 	PROTOBUF_C_FIELD_FLAG_DEPRECATED	= (1 << 1),
261 
262 	/** Set if the field is a member of a oneof (union). */
263 	PROTOBUF_C_FIELD_FLAG_ONEOF		= (1 << 2),
264 } ProtobufCFieldFlag;
265 
266 /**
267  * Message field rules.
268  *
269  * \see [Defining A Message Type] in the Protocol Buffers documentation.
270  *
271  * [Defining A Message Type]:
272  *      https://developers.google.com/protocol-buffers/docs/proto#simple
273  */
274 typedef enum {
275 	/** A well-formed message must have exactly one of this field. */
276 	PROTOBUF_C_LABEL_REQUIRED,
277 
278 	/**
279 	 * A well-formed message can have zero or one of this field (but not
280 	 * more than one).
281 	 */
282 	PROTOBUF_C_LABEL_OPTIONAL,
283 
284 	/**
285 	 * This field can be repeated any number of times (including zero) in a
286 	 * well-formed message. The order of the repeated values will be
287 	 * preserved.
288 	 */
289 	PROTOBUF_C_LABEL_REPEATED,
290 
291 	/**
292 	 * This field has no label. This is valid only in proto3 and is
293 	 * equivalent to OPTIONAL but no "has" quantifier will be consulted.
294 	 */
295 	PROTOBUF_C_LABEL_NONE,
296 } ProtobufCLabel;
297 
298 /**
299  * Field value types.
300  *
301  * \see [Scalar Value Types] in the Protocol Buffers documentation.
302  *
303  * [Scalar Value Types]:
304  *      https://developers.google.com/protocol-buffers/docs/proto#scalar
305  */
306 typedef enum {
307 	PROTOBUF_C_TYPE_INT32,      /**< int32 */
308 	PROTOBUF_C_TYPE_SINT32,     /**< signed int32 */
309 	PROTOBUF_C_TYPE_SFIXED32,   /**< signed int32 (4 bytes) */
310 	PROTOBUF_C_TYPE_INT64,      /**< int64 */
311 	PROTOBUF_C_TYPE_SINT64,     /**< signed int64 */
312 	PROTOBUF_C_TYPE_SFIXED64,   /**< signed int64 (8 bytes) */
313 	PROTOBUF_C_TYPE_UINT32,     /**< unsigned int32 */
314 	PROTOBUF_C_TYPE_FIXED32,    /**< unsigned int32 (4 bytes) */
315 	PROTOBUF_C_TYPE_UINT64,     /**< unsigned int64 */
316 	PROTOBUF_C_TYPE_FIXED64,    /**< unsigned int64 (8 bytes) */
317 	PROTOBUF_C_TYPE_FLOAT,      /**< float */
318 	PROTOBUF_C_TYPE_DOUBLE,     /**< double */
319 	PROTOBUF_C_TYPE_BOOL,       /**< boolean */
320 	PROTOBUF_C_TYPE_ENUM,       /**< enumerated type */
321 	PROTOBUF_C_TYPE_STRING,     /**< UTF-8 or ASCII string */
322 	PROTOBUF_C_TYPE_BYTES,      /**< arbitrary byte sequence */
323 	PROTOBUF_C_TYPE_MESSAGE,    /**< nested message */
324 } ProtobufCType;
325 
326 /**
327  * Field wire types.
328  *
329  * \see [Message Structure] in the Protocol Buffers documentation.
330  *
331  * [Message Structure]:
332  *      https://developers.google.com/protocol-buffers/docs/encoding#structure
333  */
334 typedef enum {
335 	PROTOBUF_C_WIRE_TYPE_VARINT = 0,
336 	PROTOBUF_C_WIRE_TYPE_64BIT = 1,
337 	PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED = 2,
338 	/* "Start group" and "end group" wire types are unsupported. */
339 	PROTOBUF_C_WIRE_TYPE_32BIT = 5,
340 } ProtobufCWireType;
341 
342 struct ProtobufCAllocator;
343 struct ProtobufCBinaryData;
344 struct ProtobufCBuffer;
345 struct ProtobufCBufferSimple;
346 struct ProtobufCEnumDescriptor;
347 struct ProtobufCEnumValue;
348 struct ProtobufCEnumValueIndex;
349 struct ProtobufCFieldDescriptor;
350 struct ProtobufCIntRange;
351 struct ProtobufCMessage;
352 struct ProtobufCMessageDescriptor;
353 struct ProtobufCMessageUnknownField;
354 struct ProtobufCMethodDescriptor;
355 struct ProtobufCService;
356 struct ProtobufCServiceDescriptor;
357 
358 typedef struct ProtobufCAllocator ProtobufCAllocator;
359 typedef struct ProtobufCBinaryData ProtobufCBinaryData;
360 typedef struct ProtobufCBuffer ProtobufCBuffer;
361 typedef struct ProtobufCBufferSimple ProtobufCBufferSimple;
362 typedef struct ProtobufCEnumDescriptor ProtobufCEnumDescriptor;
363 typedef struct ProtobufCEnumValue ProtobufCEnumValue;
364 typedef struct ProtobufCEnumValueIndex ProtobufCEnumValueIndex;
365 typedef struct ProtobufCFieldDescriptor ProtobufCFieldDescriptor;
366 typedef struct ProtobufCIntRange ProtobufCIntRange;
367 typedef struct ProtobufCMessage ProtobufCMessage;
368 typedef struct ProtobufCMessageDescriptor ProtobufCMessageDescriptor;
369 typedef struct ProtobufCMessageUnknownField ProtobufCMessageUnknownField;
370 typedef struct ProtobufCMethodDescriptor ProtobufCMethodDescriptor;
371 typedef struct ProtobufCService ProtobufCService;
372 typedef struct ProtobufCServiceDescriptor ProtobufCServiceDescriptor;
373 
374 /** Boolean type. */
375 typedef int protobuf_c_boolean;
376 
377 typedef void (*ProtobufCClosure)(const ProtobufCMessage *, void *closure_data);
378 typedef void (*ProtobufCMessageInit)(ProtobufCMessage *);
379 typedef void (*ProtobufCServiceDestroy)(ProtobufCService *);
380 
381 /**
382  * Structure for defining a custom memory allocator.
383  */
384 struct ProtobufCAllocator {
385 	/** Function to allocate memory. */
386 	void		*(*alloc)(void *allocator_data, size_t size);
387 
388 	/** Function to free memory. */
389 	void		(*free)(void *allocator_data, void *pointer);
390 
391 	/** Opaque pointer passed to `alloc` and `free` functions. */
392 	void		*allocator_data;
393 };
394 
395 /**
396  * Structure for the protobuf `bytes` scalar type.
397  *
398  * The data contained in a `ProtobufCBinaryData` is an arbitrary sequence of
399  * bytes. It may contain embedded `NUL` characters and is not required to be
400  * `NUL`-terminated.
401  */
402 struct ProtobufCBinaryData {
403 	size_t	len;        /**< Number of bytes in the `data` field. */
404 	uint8_t	*data;      /**< Data bytes. */
405 };
406 
407 /**
408  * Structure for defining a virtual append-only buffer. Used by
409  * protobuf_c_message_pack_to_buffer() to abstract the consumption of serialized
410  * bytes.
411  *
412  * `ProtobufCBuffer` "subclasses" may be defined on the stack. For example, to
413  * write to a `FILE` object:
414  *
415 ~~~{.c}
416 typedef struct {
417         ProtobufCBuffer base;
418         FILE *fp;
419 } BufferAppendToFile;
420 
421 static void
422 my_buffer_file_append(ProtobufCBuffer *buffer,
423                       size_t len,
424                       const uint8_t *data)
425 {
426         BufferAppendToFile *file_buf = (BufferAppendToFile *) buffer;
427         fwrite(data, len, 1, file_buf->fp); // XXX: No error handling!
428 }
429 ~~~
430  *
431  * To use this new type of ProtobufCBuffer, it could be called as follows:
432  *
433 ~~~{.c}
434 ...
435 BufferAppendToFile tmp = {0};
436 tmp.base.append = my_buffer_file_append;
437 tmp.fp = fp;
438 protobuf_c_message_pack_to_buffer(&message, &tmp);
439 ...
440 ~~~
441  */
442 struct ProtobufCBuffer {
443 	/** Append function. Consumes the `len` bytes stored at `data`. */
444 	void		(*append)(ProtobufCBuffer *buffer,
445 				  size_t len,
446 				  const uint8_t *data);
447 };
448 
449 /**
450  * Simple buffer "subclass" of `ProtobufCBuffer`.
451  *
452  * A `ProtobufCBufferSimple` object is declared on the stack and uses a
453  * scratch buffer provided by the user for the initial allocation. It performs
454  * exponential resizing, using dynamically allocated memory. A
455  * `ProtobufCBufferSimple` object can be created and used as follows:
456  *
457 ~~~{.c}
458 uint8_t pad[128];
459 ProtobufCBufferSimple simple = PROTOBUF_C_BUFFER_SIMPLE_INIT(pad);
460 ProtobufCBuffer *buffer = (ProtobufCBuffer *) &simple;
461 ~~~
462  *
463  * `buffer` can now be used with `protobuf_c_message_pack_to_buffer()`. Once a
464  * message has been serialized to a `ProtobufCBufferSimple` object, the
465  * serialized data bytes can be accessed from the `.data` field.
466  *
467  * To free the memory allocated by a `ProtobufCBufferSimple` object, if any,
468  * call PROTOBUF_C_BUFFER_SIMPLE_CLEAR() on the object, for example:
469  *
470 ~~~{.c}
471 PROTOBUF_C_BUFFER_SIMPLE_CLEAR(&simple);
472 ~~~
473  *
474  * \see PROTOBUF_C_BUFFER_SIMPLE_INIT
475  * \see PROTOBUF_C_BUFFER_SIMPLE_CLEAR
476  */
477 struct ProtobufCBufferSimple {
478 	/** "Base class". */
479 	ProtobufCBuffer		base;
480 	/** Number of bytes allocated in `data`. */
481 	size_t			alloced;
482 	/** Number of bytes currently stored in `data`. */
483 	size_t			len;
484 	/** Data bytes. */
485 	uint8_t			*data;
486 	/** Whether `data` must be freed. */
487 	protobuf_c_boolean	must_free_data;
488 	/** Allocator to use. May be NULL to indicate the system allocator. */
489 	ProtobufCAllocator	*allocator;
490 };
491 
492 /**
493  * Describes an enumeration as a whole, with all of its values.
494  */
495 struct ProtobufCEnumDescriptor {
496 	/** Magic value checked to ensure that the API is used correctly. */
497 	uint32_t			magic;
498 
499 	/** The qualified name (e.g., "namespace.Type"). */
500 	const char			*name;
501 	/** The unqualified name as given in the .proto file (e.g., "Type"). */
502 	const char			*short_name;
503 	/** Identifier used in generated C code. */
504 	const char			*c_name;
505 	/** The dot-separated namespace. */
506 	const char			*package_name;
507 
508 	/** Number elements in `values`. */
509 	unsigned			n_values;
510 	/** Array of distinct values, sorted by numeric value. */
511 	const ProtobufCEnumValue	*values;
512 
513 	/** Number of elements in `values_by_name`. */
514 	unsigned			n_value_names;
515 	/** Array of named values, including aliases, sorted by name. */
516 	const ProtobufCEnumValueIndex	*values_by_name;
517 
518 	/** Number of elements in `value_ranges`. */
519 	unsigned			n_value_ranges;
520 	/** Value ranges, for faster lookups by numeric value. */
521 	const ProtobufCIntRange		*value_ranges;
522 
523 	/** Reserved for future use. */
524 	void				*reserved1;
525 	/** Reserved for future use. */
526 	void				*reserved2;
527 	/** Reserved for future use. */
528 	void				*reserved3;
529 	/** Reserved for future use. */
530 	void				*reserved4;
531 };
532 
533 /**
534  * Represents a single value of an enumeration.
535  */
536 struct ProtobufCEnumValue {
537 	/** The string identifying this value in the .proto file. */
538 	const char	*name;
539 
540 	/** The string identifying this value in generated C code. */
541 	const char	*c_name;
542 
543 	/** The numeric value assigned in the .proto file. */
544 	int		value;
545 };
546 
547 /**
548  * Used by `ProtobufCEnumDescriptor` to look up enum values.
549  */
550 struct ProtobufCEnumValueIndex {
551 	/** Name of the enum value. */
552 	const char      *name;
553 	/** Index into values[] array. */
554 	unsigned        index;
555 };
556 
557 /**
558  * Describes a single field in a message.
559  */
560 struct ProtobufCFieldDescriptor {
561 	/** Name of the field as given in the .proto file. */
562 	const char		*name;
563 
564 	/** Tag value of the field as given in the .proto file. */
565 	uint32_t		id;
566 
567 	/** Whether the field is `REQUIRED`, `OPTIONAL`, or `REPEATED`. */
568 	ProtobufCLabel		label;
569 
570 	/** The type of the field. */
571 	ProtobufCType		type;
572 
573 	/**
574 	 * The offset in bytes of the message's C structure's quantifier field
575 	 * (the `has_MEMBER` field for optional members or the `n_MEMBER` field
576 	 * for repeated members or the case enum for oneofs).
577 	 */
578 	unsigned		quantifier_offset;
579 
580 	/**
581 	 * The offset in bytes into the message's C structure for the member
582 	 * itself.
583 	 */
584 	unsigned		offset;
585 
586 	/**
587 	 * A type-specific descriptor.
588 	 *
589 	 * If `type` is `PROTOBUF_C_TYPE_ENUM`, then `descriptor` points to the
590 	 * corresponding `ProtobufCEnumDescriptor`.
591 	 *
592 	 * If `type` is `PROTOBUF_C_TYPE_MESSAGE`, then `descriptor` points to
593 	 * the corresponding `ProtobufCMessageDescriptor`.
594 	 *
595 	 * Otherwise this field is NULL.
596 	 */
597 	const void		*descriptor; /* for MESSAGE and ENUM types */
598 
599 	/** The default value for this field, if defined. May be NULL. */
600 	const void		*default_value;
601 
602 	/**
603 	 * A flag word. Zero or more of the bits defined in the
604 	 * `ProtobufCFieldFlag` enum may be set.
605 	 */
606 	uint32_t		flags;
607 
608 	/** Reserved for future use. */
609 	unsigned		reserved_flags;
610 	/** Reserved for future use. */
611 	void			*reserved2;
612 	/** Reserved for future use. */
613 	void			*reserved3;
614 };
615 
616 /**
617  * Helper structure for optimizing int => index lookups in the case
618  * where the keys are mostly consecutive values, as they presumably are for
619  * enums and fields.
620  *
621  * The data structures requires that the values in the original array are
622  * sorted.
623  */
624 struct ProtobufCIntRange {
625 	int             start_value;
626 	unsigned        orig_index;
627 	/*
628 	 * NOTE: the number of values in the range can be inferred by looking
629 	 * at the next element's orig_index. A dummy element is added to make
630 	 * this simple.
631 	 */
632 };
633 
634 /**
635  * An instance of a message.
636  *
637  * `ProtobufCMessage` is a light-weight "base class" for all messages.
638  *
639  * In particular, `ProtobufCMessage` doesn't have any allocation policy
640  * associated with it. That's because it's common to create `ProtobufCMessage`
641  * objects on the stack. In fact, that's what we recommend for sending messages.
642  * If the object is allocated from the stack, you can't really have a memory
643  * leak.
644  *
645  * This means that calls to functions like protobuf_c_message_unpack() which
646  * return a `ProtobufCMessage` must be paired with a call to a free function,
647  * like protobuf_c_message_free_unpacked().
648  */
649 struct ProtobufCMessage {
650 	/** The descriptor for this message type. */
651 	const ProtobufCMessageDescriptor	*descriptor;
652 	/** The number of elements in `unknown_fields`. */
653 	unsigned				n_unknown_fields;
654 	/** The fields that weren't recognized by the parser. */
655 	ProtobufCMessageUnknownField		*unknown_fields;
656 };
657 
658 /**
659  * Describes a message.
660  */
661 struct ProtobufCMessageDescriptor {
662 	/** Magic value checked to ensure that the API is used correctly. */
663 	uint32_t			magic;
664 
665 	/** The qualified name (e.g., "namespace.Type"). */
666 	const char			*name;
667 	/** The unqualified name as given in the .proto file (e.g., "Type"). */
668 	const char			*short_name;
669 	/** Identifier used in generated C code. */
670 	const char			*c_name;
671 	/** The dot-separated namespace. */
672 	const char			*package_name;
673 
674 	/**
675 	 * Size in bytes of the C structure representing an instance of this
676 	 * type of message.
677 	 */
678 	size_t				sizeof_message;
679 
680 	/** Number of elements in `fields`. */
681 	unsigned			n_fields;
682 	/** Field descriptors, sorted by tag number. */
683 	const ProtobufCFieldDescriptor	*fields;
684 	/** Used for looking up fields by name. */
685 	const unsigned			*fields_sorted_by_name;
686 
687 	/** Number of elements in `field_ranges`. */
688 	unsigned			n_field_ranges;
689 	/** Used for looking up fields by id. */
690 	const ProtobufCIntRange		*field_ranges;
691 
692 	/** Message initialisation function. */
693 	ProtobufCMessageInit		message_init;
694 
695 	/** Reserved for future use. */
696 	void				*reserved1;
697 	/** Reserved for future use. */
698 	void				*reserved2;
699 	/** Reserved for future use. */
700 	void				*reserved3;
701 };
702 
703 /**
704  * An unknown message field.
705  */
706 struct ProtobufCMessageUnknownField {
707 	/** The tag number. */
708 	uint32_t		tag;
709 	/** The wire type of the field. */
710 	ProtobufCWireType	wire_type;
711 	/** Number of bytes in `data`. */
712 	size_t			len;
713 	/** Field data. */
714 	uint8_t			*data;
715 };
716 
717 /**
718  * Method descriptor.
719  */
720 struct ProtobufCMethodDescriptor {
721 	/** Method name. */
722 	const char				*name;
723 	/** Input message descriptor. */
724 	const ProtobufCMessageDescriptor	*input;
725 	/** Output message descriptor. */
726 	const ProtobufCMessageDescriptor	*output;
727 };
728 
729 /**
730  * Service.
731  */
732 struct ProtobufCService {
733 	/** Service descriptor. */
734 	const ProtobufCServiceDescriptor *descriptor;
735 	/** Function to invoke the service. */
736 	void (*invoke)(ProtobufCService *service,
737 		       unsigned method_index,
738 		       const ProtobufCMessage *input,
739 		       ProtobufCClosure closure,
740 		       void *closure_data);
741 	/** Function to destroy the service. */
742 	void (*destroy)(ProtobufCService *service);
743 };
744 
745 /**
746  * Service descriptor.
747  */
748 struct ProtobufCServiceDescriptor {
749 	/** Magic value checked to ensure that the API is used correctly. */
750 	uint32_t			magic;
751 
752 	/** Service name. */
753 	const char			*name;
754 	/** Short version of service name. */
755 	const char			*short_name;
756 	/** C identifier for the service name. */
757 	const char			*c_name;
758 	/** Package name. */
759 	const char			*package;
760 	/** Number of elements in `methods`. */
761 	unsigned			n_methods;
762 	/** Method descriptors, in the order defined in the .proto file. */
763 	const ProtobufCMethodDescriptor	*methods;
764 	/** Sort index of methods. */
765 	const unsigned			*method_indices_by_name;
766 };
767 
768 /**
769  * Get the version of the protobuf-c library. Note that this is the version of
770  * the library linked against, not the version of the headers compiled against.
771  *
772  * \return A string containing the version number of protobuf-c.
773  */
774 PROTOBUF_C__API
775 const char *
776 protobuf_c_version(void);
777 
778 /**
779  * Get the version of the protobuf-c library. Note that this is the version of
780  * the library linked against, not the version of the headers compiled against.
781  *
782  * \return A 32 bit unsigned integer containing the version number of
783  *      protobuf-c, represented in base-10 as (MAJOR*1E6) + (MINOR*1E3) + PATCH.
784  */
785 PROTOBUF_C__API
786 uint32_t
787 protobuf_c_version_number(void);
788 
789 /**
790  * The version of the protobuf-c headers, represented as a string using the same
791  * format as protobuf_c_version().
792  */
793 #define PROTOBUF_C_VERSION		"1.3.3"
794 
795 /**
796  * The version of the protobuf-c headers, represented as an integer using the
797  * same format as protobuf_c_version_number().
798  */
799 #define PROTOBUF_C_VERSION_NUMBER	1003003
800 
801 /**
802  * The minimum protoc-c version which works with the current version of the
803  * protobuf-c headers.
804  */
805 #define PROTOBUF_C_MIN_COMPILER_VERSION	1000000
806 
807 /**
808  * Look up a `ProtobufCEnumValue` from a `ProtobufCEnumDescriptor` by name.
809  *
810  * \param desc
811  *      The `ProtobufCEnumDescriptor` object.
812  * \param name
813  *      The `name` field from the corresponding `ProtobufCEnumValue` object to
814  *      match.
815  * \return
816  *      A `ProtobufCEnumValue` object.
817  * \retval NULL
818  *      If not found or if the optimize_for = CODE_SIZE option was set.
819  */
820 PROTOBUF_C__API
821 const ProtobufCEnumValue *
822 protobuf_c_enum_descriptor_get_value_by_name(
823 	const ProtobufCEnumDescriptor *desc,
824 	const char *name);
825 
826 /**
827  * Look up a `ProtobufCEnumValue` from a `ProtobufCEnumDescriptor` by numeric
828  * value.
829  *
830  * \param desc
831  *      The `ProtobufCEnumDescriptor` object.
832  * \param value
833  *      The `value` field from the corresponding `ProtobufCEnumValue` object to
834  *      match.
835  *
836  * \return
837  *      A `ProtobufCEnumValue` object.
838  * \retval NULL
839  *      If not found.
840  */
841 PROTOBUF_C__API
842 const ProtobufCEnumValue *
843 protobuf_c_enum_descriptor_get_value(
844 	const ProtobufCEnumDescriptor *desc,
845 	int value);
846 
847 /**
848  * Look up a `ProtobufCFieldDescriptor` from a `ProtobufCMessageDescriptor` by
849  * the name of the field.
850  *
851  * \param desc
852  *      The `ProtobufCMessageDescriptor` object.
853  * \param name
854  *      The name of the field.
855  * \return
856  *      A `ProtobufCFieldDescriptor` object.
857  * \retval NULL
858  *      If not found or if the optimize_for = CODE_SIZE option was set.
859  */
860 PROTOBUF_C__API
861 const ProtobufCFieldDescriptor *
862 protobuf_c_message_descriptor_get_field_by_name(
863 	const ProtobufCMessageDescriptor *desc,
864 	const char *name);
865 
866 /**
867  * Look up a `ProtobufCFieldDescriptor` from a `ProtobufCMessageDescriptor` by
868  * the tag value of the field.
869  *
870  * \param desc
871  *      The `ProtobufCMessageDescriptor` object.
872  * \param value
873  *      The tag value of the field.
874  * \return
875  *      A `ProtobufCFieldDescriptor` object.
876  * \retval NULL
877  *      If not found.
878  */
879 PROTOBUF_C__API
880 const ProtobufCFieldDescriptor *
881 protobuf_c_message_descriptor_get_field(
882 	const ProtobufCMessageDescriptor *desc,
883 	unsigned value);
884 
885 /**
886  * Determine the number of bytes required to store the serialised message.
887  *
888  * \param message
889  *      The message object to serialise.
890  * \return
891  *      Number of bytes.
892  */
893 PROTOBUF_C__API
894 size_t
895 protobuf_c_message_get_packed_size(const ProtobufCMessage *message);
896 
897 /**
898  * Serialise a message from its in-memory representation.
899  *
900  * This function stores the serialised bytes of the message in a pre-allocated
901  * buffer.
902  *
903  * \param message
904  *      The message object to serialise.
905  * \param[out] out
906  *      Buffer to store the bytes of the serialised message. This buffer must
907  *      have enough space to store the packed message. Use
908  *      protobuf_c_message_get_packed_size() to determine the number of bytes
909  *      required.
910  * \return
911  *      Number of bytes stored in `out`.
912  */
913 PROTOBUF_C__API
914 size_t
915 protobuf_c_message_pack(const ProtobufCMessage *message, uint8_t *out);
916 
917 /**
918  * Serialise a message from its in-memory representation to a virtual buffer.
919  *
920  * This function calls the `append` method of a `ProtobufCBuffer` object to
921  * consume the bytes generated by the serialiser.
922  *
923  * \param message
924  *      The message object to serialise.
925  * \param buffer
926  *      The virtual buffer object.
927  * \return
928  *      Number of bytes passed to the virtual buffer.
929  */
930 PROTOBUF_C__API
931 size_t
932 protobuf_c_message_pack_to_buffer(
933 	const ProtobufCMessage *message,
934 	ProtobufCBuffer *buffer);
935 
936 /**
937  * Unpack a serialised message into an in-memory representation.
938  *
939  * \param descriptor
940  *      The message descriptor.
941  * \param allocator
942  *      `ProtobufCAllocator` to use for memory allocation. May be NULL to
943  *      specify the default allocator.
944  * \param len
945  *      Length in bytes of the serialised message.
946  * \param data
947  *      Pointer to the serialised message.
948  * \return
949  *      An unpacked message object.
950  * \retval NULL
951  *      If an error occurred during unpacking.
952  */
953 PROTOBUF_C__API
954 ProtobufCMessage *
955 protobuf_c_message_unpack(
956 	const ProtobufCMessageDescriptor *descriptor,
957 	ProtobufCAllocator *allocator,
958 	size_t len,
959 	const uint8_t *data);
960 
961 /**
962  * Free an unpacked message object.
963  *
964  * This function should be used to deallocate the memory used by a call to
965  * protobuf_c_message_unpack().
966  *
967  * \param message
968  *      The message object to free. May be NULL.
969  * \param allocator
970  *      `ProtobufCAllocator` to use for memory deallocation. May be NULL to
971  *      specify the default allocator.
972  */
973 PROTOBUF_C__API
974 void
975 protobuf_c_message_free_unpacked(
976 	ProtobufCMessage *message,
977 	ProtobufCAllocator *allocator);
978 
979 /**
980  * Check the validity of a message object.
981  *
982  * Makes sure all required fields (`PROTOBUF_C_LABEL_REQUIRED`) are present.
983  * Recursively checks nested messages.
984  *
985  * \retval TRUE
986  *      Message is valid.
987  * \retval FALSE
988  *      Message is invalid.
989  */
990 PROTOBUF_C__API
991 protobuf_c_boolean
992 protobuf_c_message_check(const ProtobufCMessage *);
993 
994 /** Message initialiser. */
995 #define PROTOBUF_C_MESSAGE_INIT(descriptor) { descriptor, 0, NULL }
996 
997 /**
998  * Initialise a message object from a message descriptor.
999  *
1000  * \param descriptor
1001  *      Message descriptor.
1002  * \param message
1003  *      Allocated block of memory of size `descriptor->sizeof_message`.
1004  */
1005 PROTOBUF_C__API
1006 void
1007 protobuf_c_message_init(
1008 	const ProtobufCMessageDescriptor *descriptor,
1009 	void *message);
1010 
1011 /**
1012  * Free a service.
1013  *
1014  * \param service
1015  *      The service object to free.
1016  */
1017 PROTOBUF_C__API
1018 void
1019 protobuf_c_service_destroy(ProtobufCService *service);
1020 
1021 /**
1022  * Look up a `ProtobufCMethodDescriptor` by name.
1023  *
1024  * \param desc
1025  *      Service descriptor.
1026  * \param name
1027  *      Name of the method.
1028  *
1029  * \return
1030  *      A `ProtobufCMethodDescriptor` object.
1031  * \retval NULL
1032  *      If not found or if the optimize_for = CODE_SIZE option was set.
1033  */
1034 PROTOBUF_C__API
1035 const ProtobufCMethodDescriptor *
1036 protobuf_c_service_descriptor_get_method_by_name(
1037 	const ProtobufCServiceDescriptor *desc,
1038 	const char *name);
1039 
1040 /**
1041  * Initialise a `ProtobufCBufferSimple` object.
1042  */
1043 #define PROTOBUF_C_BUFFER_SIMPLE_INIT(array_of_bytes)                   \
1044 {                                                                       \
1045 	{ protobuf_c_buffer_simple_append },                            \
1046 	sizeof(array_of_bytes),                                         \
1047 	0,                                                              \
1048 	(array_of_bytes),                                               \
1049 	0,                                                              \
1050 	NULL                                                            \
1051 }
1052 
1053 /**
1054  * Clear a `ProtobufCBufferSimple` object, freeing any allocated memory.
1055  */
1056 #define PROTOBUF_C_BUFFER_SIMPLE_CLEAR(simp_buf)                        \
1057 do {                                                                    \
1058 	if ((simp_buf)->must_free_data) {                               \
1059 		if ((simp_buf)->allocator != NULL)                      \
1060 			(simp_buf)->allocator->free(                    \
1061 				(simp_buf)->allocator,                  \
1062 				(simp_buf)->data);			\
1063 		else                                                    \
1064 			free((simp_buf)->data);                         \
1065 	}                                                               \
1066 } while (0)
1067 
1068 /**
1069  * The `append` method for `ProtobufCBufferSimple`.
1070  *
1071  * \param buffer
1072  *      The buffer object to append to. Must actually be a
1073  *      `ProtobufCBufferSimple` object.
1074  * \param len
1075  *      Number of bytes in `data`.
1076  * \param data
1077  *      Data to append.
1078  */
1079 PROTOBUF_C__API
1080 void
1081 protobuf_c_buffer_simple_append(
1082 	ProtobufCBuffer *buffer,
1083 	size_t len,
1084 	const unsigned char *data);
1085 
1086 PROTOBUF_C__API
1087 void
1088 protobuf_c_service_generated_init(
1089 	ProtobufCService *service,
1090 	const ProtobufCServiceDescriptor *descriptor,
1091 	ProtobufCServiceDestroy destroy);
1092 
1093 PROTOBUF_C__API
1094 void
1095 protobuf_c_service_invoke_internal(
1096 	ProtobufCService *service,
1097 	unsigned method_index,
1098 	const ProtobufCMessage *input,
1099 	ProtobufCClosure closure,
1100 	void *closure_data);
1101 
1102 /**@}*/
1103 
1104 PROTOBUF_C__END_DECLS
1105 
1106 #endif /* PROTOBUF_C_H */
1107