cannam@147
|
1 ---
|
cannam@147
|
2 layout: page
|
cannam@147
|
3 title: C++ Serialization
|
cannam@147
|
4 ---
|
cannam@147
|
5
|
cannam@147
|
6 # C++ Serialization
|
cannam@147
|
7
|
cannam@147
|
8 The Cap'n Proto C++ runtime implementation provides an easy-to-use interface for manipulating
|
cannam@147
|
9 messages backed by fast pointer arithmetic. This page discusses the serialization layer of
|
cannam@147
|
10 the runtime; see [C++ RPC](cxxrpc.html) for information about the RPC layer.
|
cannam@147
|
11
|
cannam@147
|
12 ## Example Usage
|
cannam@147
|
13
|
cannam@147
|
14 For the Cap'n Proto definition:
|
cannam@147
|
15
|
cannam@147
|
16 {% highlight capnp %}
|
cannam@147
|
17 struct Person {
|
cannam@147
|
18 id @0 :UInt32;
|
cannam@147
|
19 name @1 :Text;
|
cannam@147
|
20 email @2 :Text;
|
cannam@147
|
21 phones @3 :List(PhoneNumber);
|
cannam@147
|
22
|
cannam@147
|
23 struct PhoneNumber {
|
cannam@147
|
24 number @0 :Text;
|
cannam@147
|
25 type @1 :Type;
|
cannam@147
|
26
|
cannam@147
|
27 enum Type {
|
cannam@147
|
28 mobile @0;
|
cannam@147
|
29 home @1;
|
cannam@147
|
30 work @2;
|
cannam@147
|
31 }
|
cannam@147
|
32 }
|
cannam@147
|
33
|
cannam@147
|
34 employment :union {
|
cannam@147
|
35 unemployed @4 :Void;
|
cannam@147
|
36 employer @5 :Text;
|
cannam@147
|
37 school @6 :Text;
|
cannam@147
|
38 selfEmployed @7 :Void;
|
cannam@147
|
39 # We assume that a person is only one of these.
|
cannam@147
|
40 }
|
cannam@147
|
41 }
|
cannam@147
|
42
|
cannam@147
|
43 struct AddressBook {
|
cannam@147
|
44 people @0 :List(Person);
|
cannam@147
|
45 }
|
cannam@147
|
46 {% endhighlight %}
|
cannam@147
|
47
|
cannam@147
|
48 You might write code like:
|
cannam@147
|
49
|
cannam@147
|
50 {% highlight c++ %}
|
cannam@147
|
51 #include "addressbook.capnp.h"
|
cannam@147
|
52 #include <capnp/message.h>
|
cannam@147
|
53 #include <capnp/serialize-packed.h>
|
cannam@147
|
54 #include <iostream>
|
cannam@147
|
55
|
cannam@147
|
56 void writeAddressBook(int fd) {
|
cannam@147
|
57 ::capnp::MallocMessageBuilder message;
|
cannam@147
|
58
|
cannam@147
|
59 AddressBook::Builder addressBook = message.initRoot<AddressBook>();
|
cannam@147
|
60 ::capnp::List<Person>::Builder people = addressBook.initPeople(2);
|
cannam@147
|
61
|
cannam@147
|
62 Person::Builder alice = people[0];
|
cannam@147
|
63 alice.setId(123);
|
cannam@147
|
64 alice.setName("Alice");
|
cannam@147
|
65 alice.setEmail("alice@example.com");
|
cannam@147
|
66 // Type shown for explanation purposes; normally you'd use auto.
|
cannam@147
|
67 ::capnp::List<Person::PhoneNumber>::Builder alicePhones =
|
cannam@147
|
68 alice.initPhones(1);
|
cannam@147
|
69 alicePhones[0].setNumber("555-1212");
|
cannam@147
|
70 alicePhones[0].setType(Person::PhoneNumber::Type::MOBILE);
|
cannam@147
|
71 alice.getEmployment().setSchool("MIT");
|
cannam@147
|
72
|
cannam@147
|
73 Person::Builder bob = people[1];
|
cannam@147
|
74 bob.setId(456);
|
cannam@147
|
75 bob.setName("Bob");
|
cannam@147
|
76 bob.setEmail("bob@example.com");
|
cannam@147
|
77 auto bobPhones = bob.initPhones(2);
|
cannam@147
|
78 bobPhones[0].setNumber("555-4567");
|
cannam@147
|
79 bobPhones[0].setType(Person::PhoneNumber::Type::HOME);
|
cannam@147
|
80 bobPhones[1].setNumber("555-7654");
|
cannam@147
|
81 bobPhones[1].setType(Person::PhoneNumber::Type::WORK);
|
cannam@147
|
82 bob.getEmployment().setUnemployed();
|
cannam@147
|
83
|
cannam@147
|
84 writePackedMessageToFd(fd, message);
|
cannam@147
|
85 }
|
cannam@147
|
86
|
cannam@147
|
87 void printAddressBook(int fd) {
|
cannam@147
|
88 ::capnp::PackedFdMessageReader message(fd);
|
cannam@147
|
89
|
cannam@147
|
90 AddressBook::Reader addressBook = message.getRoot<AddressBook>();
|
cannam@147
|
91
|
cannam@147
|
92 for (Person::Reader person : addressBook.getPeople()) {
|
cannam@147
|
93 std::cout << person.getName().cStr() << ": "
|
cannam@147
|
94 << person.getEmail().cStr() << std::endl;
|
cannam@147
|
95 for (Person::PhoneNumber::Reader phone: person.getPhones()) {
|
cannam@147
|
96 const char* typeName = "UNKNOWN";
|
cannam@147
|
97 switch (phone.getType()) {
|
cannam@147
|
98 case Person::PhoneNumber::Type::MOBILE: typeName = "mobile"; break;
|
cannam@147
|
99 case Person::PhoneNumber::Type::HOME: typeName = "home"; break;
|
cannam@147
|
100 case Person::PhoneNumber::Type::WORK: typeName = "work"; break;
|
cannam@147
|
101 }
|
cannam@147
|
102 std::cout << " " << typeName << " phone: "
|
cannam@147
|
103 << phone.getNumber().cStr() << std::endl;
|
cannam@147
|
104 }
|
cannam@147
|
105 Person::Employment::Reader employment = person.getEmployment();
|
cannam@147
|
106 switch (employment.which()) {
|
cannam@147
|
107 case Person::Employment::UNEMPLOYED:
|
cannam@147
|
108 std::cout << " unemployed" << std::endl;
|
cannam@147
|
109 break;
|
cannam@147
|
110 case Person::Employment::EMPLOYER:
|
cannam@147
|
111 std::cout << " employer: "
|
cannam@147
|
112 << employment.getEmployer().cStr() << std::endl;
|
cannam@147
|
113 break;
|
cannam@147
|
114 case Person::Employment::SCHOOL:
|
cannam@147
|
115 std::cout << " student at: "
|
cannam@147
|
116 << employment.getSchool().cStr() << std::endl;
|
cannam@147
|
117 break;
|
cannam@147
|
118 case Person::Employment::SELF_EMPLOYED:
|
cannam@147
|
119 std::cout << " self-employed" << std::endl;
|
cannam@147
|
120 break;
|
cannam@147
|
121 }
|
cannam@147
|
122 }
|
cannam@147
|
123 }
|
cannam@147
|
124 {% endhighlight %}
|
cannam@147
|
125
|
cannam@147
|
126 ## C++ Feature Usage: C++11, Exceptions
|
cannam@147
|
127
|
cannam@147
|
128 This implementation makes use of C++11 features. If you are using GCC, you will need at least
|
cannam@147
|
129 version 4.7 to compile Cap'n Proto. If you are using Clang, you will need at least version 3.2.
|
cannam@147
|
130 These compilers required the flag `-std=c++11` to enable C++11 features -- your code which
|
cannam@147
|
131 `#include`s Cap'n Proto headers will need to be compiled with this flag. Other compilers have not
|
cannam@147
|
132 been tested at this time.
|
cannam@147
|
133
|
cannam@147
|
134 This implementation prefers to handle errors using exceptions. Exceptions are only used in
|
cannam@147
|
135 circumstances that should never occur in normal operation. For example, exceptions are thrown
|
cannam@147
|
136 on assertion failures (indicating bugs in the code), network failures, and invalid input.
|
cannam@147
|
137 Exceptions thrown by Cap'n Proto are never part of the interface and never need to be caught in
|
cannam@147
|
138 correct usage. The purpose of throwing exceptions is to allow higher-level code a chance to
|
cannam@147
|
139 recover from unexpected circumstances without disrupting other work happening in the same process.
|
cannam@147
|
140 For example, a server that handles requests from multiple clients should, on exception, return an
|
cannam@147
|
141 error to the client that caused the exception and close that connection, but should continue
|
cannam@147
|
142 handling other connections normally.
|
cannam@147
|
143
|
cannam@147
|
144 When Cap'n Proto code might throw an exception from a destructor, it first checks
|
cannam@147
|
145 `std::uncaught_exception()` to ensure that this is safe. If another exception is already active,
|
cannam@147
|
146 the new exception is assumed to be a side-effect of the main exception, and is either silently
|
cannam@147
|
147 swallowed or reported on a side channel.
|
cannam@147
|
148
|
cannam@147
|
149 In recognition of the fact that some teams prefer not to use exceptions, and that even enabling
|
cannam@147
|
150 exceptions in the compiler introduces overhead, Cap'n Proto allows you to disable them entirely
|
cannam@147
|
151 by registering your own exception callback. The callback will be called in place of throwing an
|
cannam@147
|
152 exception. The callback may abort the process, and is required to do so in certain circumstances
|
cannam@147
|
153 (when a fatal bug is detected). If the callback returns normally, Cap'n Proto will attempt
|
cannam@147
|
154 to continue by inventing "safe" values. This will lead to garbage output, but at least the program
|
cannam@147
|
155 will not crash. Your exception callback should set some sort of a flag indicating that an error
|
cannam@147
|
156 occurred, and somewhere up the stack you should check for that flag and cancel the operation.
|
cannam@147
|
157 See the header `kj/exception.h` for details on how to register an exception callback.
|
cannam@147
|
158
|
cannam@147
|
159 ## KJ Library
|
cannam@147
|
160
|
cannam@147
|
161 Cap'n Proto is built on top of a basic utility library called KJ. The two were actually developed
|
cannam@147
|
162 together -- KJ is simply the stuff which is not specific to Cap'n Proto serialization, and may be
|
cannam@147
|
163 useful to others independently of Cap'n Proto. For now, the the two are distributed together. The
|
cannam@147
|
164 name "KJ" has no particular meaning; it was chosen to be short and easy-to-type.
|
cannam@147
|
165
|
cannam@147
|
166 As of v0.3, KJ is distributed with Cap'n Proto but built as a separate library. You may need
|
cannam@147
|
167 to explicitly link against libraries: `-lcapnp -lkj`
|
cannam@147
|
168
|
cannam@147
|
169 ## Generating Code
|
cannam@147
|
170
|
cannam@147
|
171 To generate C++ code from your `.capnp` [interface definition](language.html), run:
|
cannam@147
|
172
|
cannam@147
|
173 capnp compile -oc++ myproto.capnp
|
cannam@147
|
174
|
cannam@147
|
175 This will create `myproto.capnp.h` and `myproto.capnp.c++` in the same directory as `myproto.capnp`.
|
cannam@147
|
176
|
cannam@147
|
177 To use this code in your app, you must link against both `libcapnp` and `libkj`. If you use
|
cannam@147
|
178 `pkg-config`, Cap'n Proto provides the `capnp` module to simplify discovery of compiler and linker
|
cannam@147
|
179 flags.
|
cannam@147
|
180
|
cannam@147
|
181 If you use [RPC](cxxrpc.html) (i.e., your schema defines [interfaces](language.html#interfaces)),
|
cannam@147
|
182 then you will additionally nead to link against `libcapnp-rpc` and `libkj-async`, or use the
|
cannam@147
|
183 `capnp-rpc` `pkg-config` module.
|
cannam@147
|
184
|
cannam@147
|
185 ### Setting a Namespace
|
cannam@147
|
186
|
cannam@147
|
187 You probably want your generated types to live in a C++ namespace. You will need to import
|
cannam@147
|
188 `/capnp/c++.capnp` and use the `namespace` annotation it defines:
|
cannam@147
|
189
|
cannam@147
|
190 {% highlight capnp %}
|
cannam@147
|
191 using Cxx = import "/capnp/c++.capnp";
|
cannam@147
|
192 $Cxx.namespace("foo::bar::baz");
|
cannam@147
|
193 {% endhighlight %}
|
cannam@147
|
194
|
cannam@147
|
195 Note that `capnp/c++.capnp` is installed in `$PREFIX/include` (`/usr/local/include` by default)
|
cannam@147
|
196 when you install the C++ runtime. The `capnp` tool automatically searches `/usr/include` and
|
cannam@147
|
197 `/usr/local/include` for imports that start with a `/`, so it should "just work". If you installed
|
cannam@147
|
198 somewhere else, you may need to add it to the search path with the `-I` flag to `capnp compile`,
|
cannam@147
|
199 which works much like the compiler flag of the same name.
|
cannam@147
|
200
|
cannam@147
|
201 ## Types
|
cannam@147
|
202
|
cannam@147
|
203 ### Primitive Types
|
cannam@147
|
204
|
cannam@147
|
205 Primitive types map to the obvious C++ types:
|
cannam@147
|
206
|
cannam@147
|
207 * `Bool` -> `bool`
|
cannam@147
|
208 * `IntNN` -> `intNN_t`
|
cannam@147
|
209 * `UIntNN` -> `uintNN_t`
|
cannam@147
|
210 * `Float32` -> `float`
|
cannam@147
|
211 * `Float64` -> `double`
|
cannam@147
|
212 * `Void` -> `::capnp::Void` (An empty struct; its only value is `::capnp::VOID`)
|
cannam@147
|
213
|
cannam@147
|
214 ### Structs
|
cannam@147
|
215
|
cannam@147
|
216 For each struct `Foo` in your interface, a C++ type named `Foo` generated. This type itself is
|
cannam@147
|
217 really just a namespace; it contains two important inner classes: `Reader` and `Builder`.
|
cannam@147
|
218
|
cannam@147
|
219 `Reader` represents a read-only instance of `Foo` while `Builder` represents a writable instance
|
cannam@147
|
220 (usually, one that you are building). Both classes behave like pointers, in that you can pass them
|
cannam@147
|
221 by value and they do not own the underlying data that they operate on. In other words,
|
cannam@147
|
222 `Foo::Builder` is like a pointer to a `Foo` while `Foo::Reader` is like a const pointer to a `Foo`.
|
cannam@147
|
223
|
cannam@147
|
224 For every field `bar` defined in `Foo`, `Foo::Reader` has a method `getBar()`. For primitive types,
|
cannam@147
|
225 `get` just returns the type, but for structs, lists, and blobs, it returns a `Reader` for the
|
cannam@147
|
226 type.
|
cannam@147
|
227
|
cannam@147
|
228 {% highlight c++ %}
|
cannam@147
|
229 // Example Reader methods:
|
cannam@147
|
230
|
cannam@147
|
231 // myPrimitiveField @0 :Int32;
|
cannam@147
|
232 int32_t getMyPrimitiveField();
|
cannam@147
|
233
|
cannam@147
|
234 // myTextField @1 :Text;
|
cannam@147
|
235 ::capnp::Text::Reader getMyTextField();
|
cannam@147
|
236 // (Note that Text::Reader may be implicitly cast to const char* and
|
cannam@147
|
237 // std::string.)
|
cannam@147
|
238
|
cannam@147
|
239 // myStructField @2 :MyStruct;
|
cannam@147
|
240 MyStruct::Reader getMyStructField();
|
cannam@147
|
241
|
cannam@147
|
242 // myListField @3 :List(Float64);
|
cannam@147
|
243 ::capnp::List<double> getMyListField();
|
cannam@147
|
244 {% endhighlight %}
|
cannam@147
|
245
|
cannam@147
|
246 `Foo::Builder`, meanwhile, has several methods for each field `bar`:
|
cannam@147
|
247
|
cannam@147
|
248 * `getBar()`: For primitives, returns the value. For composites, returns a Builder for the
|
cannam@147
|
249 composite. If a composite field has not been initialized (i.e. this is the first time it has
|
cannam@147
|
250 been accessed), it will be initialized to a copy of the field's default value before returning.
|
cannam@147
|
251 * `setBar(x)`: For primitives, sets the value to x. For composites, sets the value to a deep copy
|
cannam@147
|
252 of x, which must be a Reader for the type.
|
cannam@147
|
253 * `initBar(n)`: Only for lists and blobs. Sets the field to a newly-allocated list or blob
|
cannam@147
|
254 of size n and returns a Builder for it. The elements of the list are initialized to their empty
|
cannam@147
|
255 state (zero for numbers, default values for structs).
|
cannam@147
|
256 * `initBar()`: Only for structs. Sets the field to a newly-allocated struct and returns a
|
cannam@147
|
257 Builder for it. Note that the newly-allocated struct is initialized to the default value for
|
cannam@147
|
258 the struct's _type_ (i.e., all-zero) rather than the default value for the field `bar` (if it
|
cannam@147
|
259 has one).
|
cannam@147
|
260 * `hasBar()`: Only for pointer fields (e.g. structs, lists, blobs). Returns true if the pointer
|
cannam@147
|
261 has been initialized (non-null). (This method is also available on readers.)
|
cannam@147
|
262 * `adoptBar(x)`: Only for pointer fields. Adopts the orphaned object x, linking it into the field
|
cannam@147
|
263 `bar` without copying. See the section on orphans.
|
cannam@147
|
264 * `disownBar()`: Disowns the value pointed to by `bar`, setting the pointer to null and returning
|
cannam@147
|
265 its previous value as an orphan. See the section on orphans.
|
cannam@147
|
266
|
cannam@147
|
267 {% highlight c++ %}
|
cannam@147
|
268 // Example Builder methods:
|
cannam@147
|
269
|
cannam@147
|
270 // myPrimitiveField @0 :Int32;
|
cannam@147
|
271 int32_t getMyPrimitiveField();
|
cannam@147
|
272 void setMyPrimitiveField(int32_t value);
|
cannam@147
|
273
|
cannam@147
|
274 // myTextField @1 :Text;
|
cannam@147
|
275 ::capnp::Text::Builder getMyTextField();
|
cannam@147
|
276 void setMyTextField(::capnp::Text::Reader value);
|
cannam@147
|
277 ::capnp::Text::Builder initMyTextField(size_t size);
|
cannam@147
|
278 // (Note that Text::Reader is implicitly constructable from const char*
|
cannam@147
|
279 // and std::string, and Text::Builder can be implicitly cast to
|
cannam@147
|
280 // these types.)
|
cannam@147
|
281
|
cannam@147
|
282 // myStructField @2 :MyStruct;
|
cannam@147
|
283 MyStruct::Builder getMyStructField();
|
cannam@147
|
284 void setMyStructField(MyStruct::Reader value);
|
cannam@147
|
285 MyStruct::Builder initMyStructField();
|
cannam@147
|
286
|
cannam@147
|
287 // myListField @3 :List(Float64);
|
cannam@147
|
288 ::capnp::List<double>::Builder getMyListField();
|
cannam@147
|
289 void setMyListField(::capnp::List<double>::Reader value);
|
cannam@147
|
290 ::capnp::List<double>::Builder initMyListField(size_t size);
|
cannam@147
|
291 {% endhighlight %}
|
cannam@147
|
292
|
cannam@147
|
293 ### Groups
|
cannam@147
|
294
|
cannam@147
|
295 Groups look a lot like a combination of a nested type and a field of that type, except that you
|
cannam@147
|
296 cannot set, adopt, or disown a group -- you can only get and init it.
|
cannam@147
|
297
|
cannam@147
|
298 ### Unions
|
cannam@147
|
299
|
cannam@147
|
300 A named union (as opposed to an unnamed one) works just like a group, except with some additions:
|
cannam@147
|
301
|
cannam@147
|
302 * For each field `foo`, the union reader and builder have a method `isFoo()` which returns true
|
cannam@147
|
303 if `foo` is the currently-set field in the union.
|
cannam@147
|
304 * The union reader and builder also have a method `which()` that returns an enum value indicating
|
cannam@147
|
305 which field is currently set.
|
cannam@147
|
306 * Calling the set, init, or adopt accessors for a field makes it the currently-set field.
|
cannam@147
|
307 * Calling the get or disown accessors on a field that isn't currently set will throw an
|
cannam@147
|
308 exception in debug mode or return garbage when `NDEBUG` is defined.
|
cannam@147
|
309
|
cannam@147
|
310 Unnamed unions differ from named unions only in that the accessor methods from the union's members
|
cannam@147
|
311 are added directly to the containing type's reader and builder, rather than generating a nested
|
cannam@147
|
312 type.
|
cannam@147
|
313
|
cannam@147
|
314 See the [example](#example-usage) at the top of the page for an example of unions.
|
cannam@147
|
315
|
cannam@147
|
316 ### Lists
|
cannam@147
|
317
|
cannam@147
|
318 Lists are represented by the type `capnp::List<T>`, where `T` is any of the primitive types,
|
cannam@147
|
319 any Cap'n Proto user-defined type, `capnp::Text`, `capnp::Data`, or `capnp::List<U>`
|
cannam@147
|
320 (to form a list of lists).
|
cannam@147
|
321
|
cannam@147
|
322 The type `List<T>` itself is not instantiatable, but has two inner classes: `Reader` and `Builder`.
|
cannam@147
|
323 As with structs, these types behave like pointers to read-only and read-write data, respectively.
|
cannam@147
|
324
|
cannam@147
|
325 Both `Reader` and `Builder` implement `size()`, `operator[]`, `begin()`, and `end()`, as good C++
|
cannam@147
|
326 containers should. Note, though, that `operator[]` is read-only -- you cannot use it to assign
|
cannam@147
|
327 the element, because that would require returning a reference, which is impossible because the
|
cannam@147
|
328 underlying data may not be in your CPU's native format (e.g., wrong byte order). Instead, to
|
cannam@147
|
329 assign an element of a list, you must use `builder.set(index, value)`.
|
cannam@147
|
330
|
cannam@147
|
331 For `List<Foo>` where `Foo` is a non-primitive type, the type returned by `operator[]` and
|
cannam@147
|
332 `iterator::operator*()` is `Foo::Reader` (for `List<Foo>::Reader`) or `Foo::Builder`
|
cannam@147
|
333 (for `List<Foo>::Builder`). The builder's `set` method takes a `Foo::Reader` as its second
|
cannam@147
|
334 parameter.
|
cannam@147
|
335
|
cannam@147
|
336 For lists of lists or lists of blobs, the builder also has a method `init(index, size)` which sets
|
cannam@147
|
337 the element at the given index to a newly-allocated value with the given size and returns a builder
|
cannam@147
|
338 for it. Struct lists do not have an `init` method because all elements are initialized to empty
|
cannam@147
|
339 values when the list is created.
|
cannam@147
|
340
|
cannam@147
|
341 ### Enums
|
cannam@147
|
342
|
cannam@147
|
343 Cap'n Proto enums become C++11 "enum classes". That means they behave like any other enum, but
|
cannam@147
|
344 the enum's values are scoped within the type. E.g. for an enum `Foo` with value `bar`, you must
|
cannam@147
|
345 refer to the value as `Foo::BAR`.
|
cannam@147
|
346
|
cannam@147
|
347 To match prevaling C++ style, an enum's value names are converted to UPPERCASE_WITH_UNDERSCORES
|
cannam@147
|
348 (whereas in the schema language you'd write them in camelCase).
|
cannam@147
|
349
|
cannam@147
|
350 Keep in mind when writing `switch` blocks that an enum read off the wire may have a numeric
|
cannam@147
|
351 value that is not listed in its definition. This may be the case if the sender is using a newer
|
cannam@147
|
352 version of the protocol, or if the message is corrupt or malicious. In C++11, enums are allowed
|
cannam@147
|
353 to have any value that is within the range of their base type, which for Cap'n Proto enums is
|
cannam@147
|
354 `uint16_t`.
|
cannam@147
|
355
|
cannam@147
|
356 ### Blobs (Text and Data)
|
cannam@147
|
357
|
cannam@147
|
358 Blobs are manipulated using the classes `capnp::Text` and `capnp::Data`. These classes are,
|
cannam@147
|
359 again, just containers for inner classes `Reader` and `Builder`. These classes are iterable and
|
cannam@147
|
360 implement `size()` and `operator[]` methods. `Builder::operator[]` even returns a reference
|
cannam@147
|
361 (unlike with `List<T>`). `Text::Reader` additionally has a method `cStr()` which returns a
|
cannam@147
|
362 NUL-terminated `const char*`.
|
cannam@147
|
363
|
cannam@147
|
364 As a special convenience, if you are using GCC 4.8+ or Clang, `Text::Reader` (and its underlying
|
cannam@147
|
365 type, `kj::StringPtr`) can be implicitly converted to and from `std::string` format. This is
|
cannam@147
|
366 accomplished without actually `#include`ing `<string>`, since some clients do not want to rely
|
cannam@147
|
367 on this rather-bulky header. In fact, any class which defines a `.c_str()` method will be
|
cannam@147
|
368 implicitly convertible in this way. Unfortunately, this trick doesn't work on GCC 4.7.
|
cannam@147
|
369
|
cannam@147
|
370 ### Interfaces
|
cannam@147
|
371
|
cannam@147
|
372 [Interfaces (RPC) have their own page.](cxxrpc.html)
|
cannam@147
|
373
|
cannam@147
|
374 ### Generics
|
cannam@147
|
375
|
cannam@147
|
376 [Generic types](language.html#generic-types) become templates in C++. The outer type (the one whose
|
cannam@147
|
377 name matches the schema declaration's name) is templatized; the inner `Reader` and `Builder` types
|
cannam@147
|
378 are not, because they inherit the parameters from the outer type. Similarly, template parameters
|
cannam@147
|
379 should refer to outer types, not `Reader` or `Builder` types.
|
cannam@147
|
380
|
cannam@147
|
381 For example, given:
|
cannam@147
|
382
|
cannam@147
|
383 {% highlight capnp %}
|
cannam@147
|
384 struct Map(Key, Value) {
|
cannam@147
|
385 entries @0 :List(Entry);
|
cannam@147
|
386 struct Entry {
|
cannam@147
|
387 key @0 :Key;
|
cannam@147
|
388 value @1 :Value;
|
cannam@147
|
389 }
|
cannam@147
|
390 }
|
cannam@147
|
391
|
cannam@147
|
392 struct People {
|
cannam@147
|
393 byName @0 :Map(Text, Person);
|
cannam@147
|
394 # Maps names to Person instances.
|
cannam@147
|
395 }
|
cannam@147
|
396 {% endhighlight %}
|
cannam@147
|
397
|
cannam@147
|
398 You might write code like:
|
cannam@147
|
399
|
cannam@147
|
400 {% highlight c++ %}
|
cannam@147
|
401 void processPeople(People::Reader people) {
|
cannam@147
|
402 Map<Text, Person>::Reader reader = people.getByName();
|
cannam@147
|
403 capnp::List<Map<Text, Person>::Entry>::Reader entries =
|
cannam@147
|
404 reader.getEntries()
|
cannam@147
|
405 for (auto entry: entries) {
|
cannam@147
|
406 processPerson(entry);
|
cannam@147
|
407 }
|
cannam@147
|
408 }
|
cannam@147
|
409 {% endhighlight %}
|
cannam@147
|
410
|
cannam@147
|
411 Note that all template parameters will be specified with a default value of `AnyPointer`.
|
cannam@147
|
412 Therefore, the type `Map<>` is equivalent to `Map<capnp::AnyPointer, capnp::AnyPointer>`.
|
cannam@147
|
413
|
cannam@147
|
414 ### Constants
|
cannam@147
|
415
|
cannam@147
|
416 Constants are exposed with their names converted to UPPERCASE_WITH_UNDERSCORES naming style
|
cannam@147
|
417 (whereas in the schema language you’d write them in camelCase). Primitive constants are just
|
cannam@147
|
418 `constexpr` values. Pointer-type constants (e.g. structs, lists, and blobs) are represented
|
cannam@147
|
419 using a proxy object that can be converted to the relevant `Reader` type, either implicitly or
|
cannam@147
|
420 using the unary `*` or `->` operators.
|
cannam@147
|
421
|
cannam@147
|
422 ## Messages and I/O
|
cannam@147
|
423
|
cannam@147
|
424 To create a new message, you must start by creating a `capnp::MessageBuilder`
|
cannam@147
|
425 (`capnp/message.h`). This is an abstract type which you can implement yourself, but most users
|
cannam@147
|
426 will want to use `capnp::MallocMessageBuilder`. Once your message is constructed, write it to
|
cannam@147
|
427 a file descriptor with `capnp::writeMessageToFd(fd, builder)` (`capnp/serialize.h`) or
|
cannam@147
|
428 `capnp::writePackedMessageToFd(fd, builder)` (`capnp/serialize-packed.h`).
|
cannam@147
|
429
|
cannam@147
|
430 To read a message, you must create a `capnp::MessageReader`, which is another abstract type.
|
cannam@147
|
431 Implementations are specific to the data source. You can use `capnp::StreamFdMessageReader`
|
cannam@147
|
432 (`capnp/serialize.h`) or `capnp::PackedFdMessageReader` (`capnp/serialize-packed.h`)
|
cannam@147
|
433 to read from file descriptors; both take the file descriptor as a constructor argument.
|
cannam@147
|
434
|
cannam@147
|
435 Note that if your stream contains additional data after the message, `PackedFdMessageReader` may
|
cannam@147
|
436 accidentally read some of that data, since it does buffered I/O. To make this work correctly, you
|
cannam@147
|
437 will need to set up a multi-use buffered stream. Buffered I/O may also be a good idea with
|
cannam@147
|
438 `StreamFdMessageReader` and also when writing, for performance reasons. See `capnp/io.h` for
|
cannam@147
|
439 details.
|
cannam@147
|
440
|
cannam@147
|
441 There is an [example](#example-usage) of all this at the beginning of this page.
|
cannam@147
|
442
|
cannam@147
|
443 ### Using mmap
|
cannam@147
|
444
|
cannam@147
|
445 Cap'n Proto can be used together with `mmap()` (or Win32's `MapViewOfFile()`) for extremely fast
|
cannam@147
|
446 reads, especially when you only need to use a subset of the data in the file. Currently,
|
cannam@147
|
447 Cap'n Proto is not well-suited for _writing_ via `mmap()`, only reading, but this is only because
|
cannam@147
|
448 we have not yet invented a mutable segment framing format -- the underlying design should
|
cannam@147
|
449 eventually work for both.
|
cannam@147
|
450
|
cannam@147
|
451 To take advantage of `mmap()` at read time, write your file in regular serialized (but NOT packed)
|
cannam@147
|
452 format -- that is, use `writeMessageToFd()`, _not_ `writePackedMessageToFd()`. Now, `mmap()` in
|
cannam@147
|
453 the entire file, and then pass the mapped memory to the constructor of
|
cannam@147
|
454 `capnp::FlatArrayMessageReader` (defined in `capnp/serialize.h`). That's it. You can use the
|
cannam@147
|
455 reader just like a normal `StreamFdMessageReader`. The operating system will automatically page
|
cannam@147
|
456 in data from disk as you read it.
|
cannam@147
|
457
|
cannam@147
|
458 `mmap()` works best when reading from flash media, or when the file is already hot in cache.
|
cannam@147
|
459 It works less well with slow rotating disks. Here, disk seeks make random access relatively
|
cannam@147
|
460 expensive. Also, if I/O throughput is your bottleneck, then the fact that mmaped data cannot
|
cannam@147
|
461 be packed or compressed may hurt you. However, it all depends on what fraction of the file you're
|
cannam@147
|
462 actually reading -- if you only pull one field out of one deeply-nested struct in a huge tree, it
|
cannam@147
|
463 may still be a win. The only way to know for sure is to do benchmarks! (But be careful to make
|
cannam@147
|
464 sure your benchmark is actually interacting with disk and not cache.)
|
cannam@147
|
465
|
cannam@147
|
466 ## Dynamic Reflection
|
cannam@147
|
467
|
cannam@147
|
468 Sometimes you want to write generic code that operates on arbitrary types, iterating over the
|
cannam@147
|
469 fields or looking them up by name. For example, you might want to write code that encodes
|
cannam@147
|
470 arbitrary Cap'n Proto types in JSON format. This requires something like "reflection", but C++
|
cannam@147
|
471 does not offer reflection. Also, you might even want to operate on types that aren't compiled
|
cannam@147
|
472 into the binary at all, but only discovered at runtime.
|
cannam@147
|
473
|
cannam@147
|
474 The C++ API supports inspecting schemas at runtime via the interface defined in
|
cannam@147
|
475 `capnp/schema.h`, and dynamically reading and writing instances of arbitrary types via
|
cannam@147
|
476 `capnp/dynamic.h`. Here's the example from the beginning of this file rewritten in terms
|
cannam@147
|
477 of the dynamic API:
|
cannam@147
|
478
|
cannam@147
|
479 {% highlight c++ %}
|
cannam@147
|
480 #include "addressbook.capnp.h"
|
cannam@147
|
481 #include <capnp/message.h>
|
cannam@147
|
482 #include <capnp/serialize-packed.h>
|
cannam@147
|
483 #include <iostream>
|
cannam@147
|
484 #include <capnp/schema.h>
|
cannam@147
|
485 #include <capnp/dynamic.h>
|
cannam@147
|
486
|
cannam@147
|
487 using ::capnp::DynamicValue;
|
cannam@147
|
488 using ::capnp::DynamicStruct;
|
cannam@147
|
489 using ::capnp::DynamicEnum;
|
cannam@147
|
490 using ::capnp::DynamicList;
|
cannam@147
|
491 using ::capnp::List;
|
cannam@147
|
492 using ::capnp::Schema;
|
cannam@147
|
493 using ::capnp::StructSchema;
|
cannam@147
|
494 using ::capnp::EnumSchema;
|
cannam@147
|
495
|
cannam@147
|
496 using ::capnp::Void;
|
cannam@147
|
497 using ::capnp::Text;
|
cannam@147
|
498 using ::capnp::MallocMessageBuilder;
|
cannam@147
|
499 using ::capnp::PackedFdMessageReader;
|
cannam@147
|
500
|
cannam@147
|
501 void dynamicWriteAddressBook(int fd, StructSchema schema) {
|
cannam@147
|
502 // Write a message using the dynamic API to set each
|
cannam@147
|
503 // field by text name. This isn't something you'd
|
cannam@147
|
504 // normally want to do; it's just for illustration.
|
cannam@147
|
505
|
cannam@147
|
506 MallocMessageBuilder message;
|
cannam@147
|
507
|
cannam@147
|
508 // Types shown for explanation purposes; normally you'd
|
cannam@147
|
509 // use auto.
|
cannam@147
|
510 DynamicStruct::Builder addressBook =
|
cannam@147
|
511 message.initRoot<DynamicStruct>(schema);
|
cannam@147
|
512
|
cannam@147
|
513 DynamicList::Builder people =
|
cannam@147
|
514 addressBook.init("people", 2).as<DynamicList>();
|
cannam@147
|
515
|
cannam@147
|
516 DynamicStruct::Builder alice =
|
cannam@147
|
517 people[0].as<DynamicStruct>();
|
cannam@147
|
518 alice.set("id", 123);
|
cannam@147
|
519 alice.set("name", "Alice");
|
cannam@147
|
520 alice.set("email", "alice@example.com");
|
cannam@147
|
521 auto alicePhones = alice.init("phones", 1).as<DynamicList>();
|
cannam@147
|
522 auto phone0 = alicePhones[0].as<DynamicStruct>();
|
cannam@147
|
523 phone0.set("number", "555-1212");
|
cannam@147
|
524 phone0.set("type", "mobile");
|
cannam@147
|
525 alice.get("employment").as<DynamicStruct>()
|
cannam@147
|
526 .set("school", "MIT");
|
cannam@147
|
527
|
cannam@147
|
528 auto bob = people[1].as<DynamicStruct>();
|
cannam@147
|
529 bob.set("id", 456);
|
cannam@147
|
530 bob.set("name", "Bob");
|
cannam@147
|
531 bob.set("email", "bob@example.com");
|
cannam@147
|
532
|
cannam@147
|
533 // Some magic: We can convert a dynamic sub-value back to
|
cannam@147
|
534 // the native type with as<T>()!
|
cannam@147
|
535 List<Person::PhoneNumber>::Builder bobPhones =
|
cannam@147
|
536 bob.init("phones", 2).as<List<Person::PhoneNumber>>();
|
cannam@147
|
537 bobPhones[0].setNumber("555-4567");
|
cannam@147
|
538 bobPhones[0].setType(Person::PhoneNumber::Type::HOME);
|
cannam@147
|
539 bobPhones[1].setNumber("555-7654");
|
cannam@147
|
540 bobPhones[1].setType(Person::PhoneNumber::Type::WORK);
|
cannam@147
|
541 bob.get("employment").as<DynamicStruct>()
|
cannam@147
|
542 .set("unemployed", ::capnp::VOID);
|
cannam@147
|
543
|
cannam@147
|
544 writePackedMessageToFd(fd, message);
|
cannam@147
|
545 }
|
cannam@147
|
546
|
cannam@147
|
547 void dynamicPrintValue(DynamicValue::Reader value) {
|
cannam@147
|
548 // Print an arbitrary message via the dynamic API by
|
cannam@147
|
549 // iterating over the schema. Look at the handling
|
cannam@147
|
550 // of STRUCT in particular.
|
cannam@147
|
551
|
cannam@147
|
552 switch (value.getType()) {
|
cannam@147
|
553 case DynamicValue::VOID:
|
cannam@147
|
554 std::cout << "";
|
cannam@147
|
555 break;
|
cannam@147
|
556 case DynamicValue::BOOL:
|
cannam@147
|
557 std::cout << (value.as<bool>() ? "true" : "false");
|
cannam@147
|
558 break;
|
cannam@147
|
559 case DynamicValue::INT:
|
cannam@147
|
560 std::cout << value.as<int64_t>();
|
cannam@147
|
561 break;
|
cannam@147
|
562 case DynamicValue::UINT:
|
cannam@147
|
563 std::cout << value.as<uint64_t>();
|
cannam@147
|
564 break;
|
cannam@147
|
565 case DynamicValue::FLOAT:
|
cannam@147
|
566 std::cout << value.as<double>();
|
cannam@147
|
567 break;
|
cannam@147
|
568 case DynamicValue::TEXT:
|
cannam@147
|
569 std::cout << '\"' << value.as<Text>().cStr() << '\"';
|
cannam@147
|
570 break;
|
cannam@147
|
571 case DynamicValue::LIST: {
|
cannam@147
|
572 std::cout << "[";
|
cannam@147
|
573 bool first = true;
|
cannam@147
|
574 for (auto element: value.as<DynamicList>()) {
|
cannam@147
|
575 if (first) {
|
cannam@147
|
576 first = false;
|
cannam@147
|
577 } else {
|
cannam@147
|
578 std::cout << ", ";
|
cannam@147
|
579 }
|
cannam@147
|
580 dynamicPrintValue(element);
|
cannam@147
|
581 }
|
cannam@147
|
582 std::cout << "]";
|
cannam@147
|
583 break;
|
cannam@147
|
584 }
|
cannam@147
|
585 case DynamicValue::ENUM: {
|
cannam@147
|
586 auto enumValue = value.as<DynamicEnum>();
|
cannam@147
|
587 KJ_IF_MAYBE(enumerant, enumValue.getEnumerant()) {
|
cannam@147
|
588 std::cout <<
|
cannam@147
|
589 enumerant->getProto().getName().cStr();
|
cannam@147
|
590 } else {
|
cannam@147
|
591 // Unknown enum value; output raw number.
|
cannam@147
|
592 std::cout << enumValue.getRaw();
|
cannam@147
|
593 }
|
cannam@147
|
594 break;
|
cannam@147
|
595 }
|
cannam@147
|
596 case DynamicValue::STRUCT: {
|
cannam@147
|
597 std::cout << "(";
|
cannam@147
|
598 auto structValue = value.as<DynamicStruct>();
|
cannam@147
|
599 bool first = true;
|
cannam@147
|
600 for (auto field: structValue.getSchema().getFields()) {
|
cannam@147
|
601 if (!structValue.has(field)) continue;
|
cannam@147
|
602 if (first) {
|
cannam@147
|
603 first = false;
|
cannam@147
|
604 } else {
|
cannam@147
|
605 std::cout << ", ";
|
cannam@147
|
606 }
|
cannam@147
|
607 std::cout << field.getProto().getName().cStr()
|
cannam@147
|
608 << " = ";
|
cannam@147
|
609 dynamicPrintValue(structValue.get(field));
|
cannam@147
|
610 }
|
cannam@147
|
611 std::cout << ")";
|
cannam@147
|
612 break;
|
cannam@147
|
613 }
|
cannam@147
|
614 default:
|
cannam@147
|
615 // There are other types, we aren't handling them.
|
cannam@147
|
616 std::cout << "?";
|
cannam@147
|
617 break;
|
cannam@147
|
618 }
|
cannam@147
|
619 }
|
cannam@147
|
620
|
cannam@147
|
621 void dynamicPrintMessage(int fd, StructSchema schema) {
|
cannam@147
|
622 PackedFdMessageReader message(fd);
|
cannam@147
|
623 dynamicPrintValue(message.getRoot<DynamicStruct>(schema));
|
cannam@147
|
624 std::cout << std::endl;
|
cannam@147
|
625 }
|
cannam@147
|
626 {% endhighlight %}
|
cannam@147
|
627
|
cannam@147
|
628 Notes about the dynamic API:
|
cannam@147
|
629
|
cannam@147
|
630 * You can implicitly cast any compiled Cap'n Proto struct reader/builder type directly to
|
cannam@147
|
631 `DynamicStruct::Reader`/`DynamicStruct::Builder`. Similarly with `List<T>` and `DynamicList`,
|
cannam@147
|
632 and even enum types and `DynamicEnum`. Finally, all valid Cap'n Proto field types may be
|
cannam@147
|
633 implicitly converted to `DynamicValue`.
|
cannam@147
|
634
|
cannam@147
|
635 * You can load schemas dynamically at runtime using `SchemaLoader` (`capnp/schema-loader.h`) and
|
cannam@147
|
636 use the Dynamic API to manipulate objects of these types. `MessageBuilder` and `MessageReader`
|
cannam@147
|
637 have methods for accessing the message root using a dynamic schema.
|
cannam@147
|
638
|
cannam@147
|
639 * While `SchemaLoader` loads binary schemas, you can also parse directly from text using
|
cannam@147
|
640 `SchemaParser` (`capnp/schema-parser.h`). However, this requires linking against `libcapnpc`
|
cannam@147
|
641 (in addition to `libcapnp` and `libkj`) -- this code is bulky and not terribly efficient. If
|
cannam@147
|
642 you can arrange to use only binary schemas at runtime, you'll be better off.
|
cannam@147
|
643
|
cannam@147
|
644 * Unlike with Protobufs, there is no "global registry" of compiled-in types. To get the schema
|
cannam@147
|
645 for a compiled-in type, use `capnp::Schema::from<MyType>()`.
|
cannam@147
|
646
|
cannam@147
|
647 * Unlike with Protobufs, the overhead of supporting reflection is small. Generated `.capnp.c++`
|
cannam@147
|
648 files contain only some embedded const data structures describing the schema, no code at all,
|
cannam@147
|
649 and the runtime library support code is relatively small. Moreover, if you do not use the
|
cannam@147
|
650 dynamic API or the schema API, you do not even need to link their implementations into your
|
cannam@147
|
651 executable.
|
cannam@147
|
652
|
cannam@147
|
653 * The dynamic API performs type checks at runtime. In case of error, it will throw an exception.
|
cannam@147
|
654 If you compile with `-fno-exceptions`, it will crash instead. Correct usage of the API should
|
cannam@147
|
655 never throw, but bugs happen. Enabling and catching exceptions will make your code more robust.
|
cannam@147
|
656
|
cannam@147
|
657 * Loading user-provided schemas has security implications: it greatly increases the attack
|
cannam@147
|
658 surface of the Cap'n Proto library. In particular, it is easy for an attacker to trigger
|
cannam@147
|
659 exceptions. To protect yourself, you are strongly advised to enable exceptions and catch them.
|
cannam@147
|
660
|
cannam@147
|
661 ## Orphans
|
cannam@147
|
662
|
cannam@147
|
663 An "orphan" is a Cap'n Proto object that is disconnected from the message structure. That is,
|
cannam@147
|
664 it is not the root of a message, and there is no other Cap'n Proto object holding a pointer to it.
|
cannam@147
|
665 Thus, it has no parents. Orphans are an advanced feature that can help avoid copies and make it
|
cannam@147
|
666 easier to use Cap'n Proto objects as part of your application's internal state. Typical
|
cannam@147
|
667 applications probably won't use orphans.
|
cannam@147
|
668
|
cannam@147
|
669 The class `capnp::Orphan<T>` (defined in `<capnp/orphan.h>`) represents a pointer to an orphaned
|
cannam@147
|
670 object of type `T`. `T` can be any struct type, `List<T>`, `Text`, or `Data`. E.g.
|
cannam@147
|
671 `capnp::Orphan<Person>` would be an orphaned `Person` structure. `Orphan<T>` is a move-only class,
|
cannam@147
|
672 similar to `std::unique_ptr<T>`. This prevents two different objects from adopting the same
|
cannam@147
|
673 orphan, which would result in an invalid message.
|
cannam@147
|
674
|
cannam@147
|
675 An orphan can be "adopted" by another object to link it into the message structure. Conversely,
|
cannam@147
|
676 an object can "disown" one of its pointers, causing the pointed-to object to become an orphan.
|
cannam@147
|
677 Every pointer-typed field `foo` provides builder methods `adoptFoo()` and `disownFoo()` for these
|
cannam@147
|
678 purposes. Again, these methods use C++11 move semantics. To use them, you will need to be
|
cannam@147
|
679 familiar with `std::move()` (or the equivalent but shorter-named `kj::mv()`).
|
cannam@147
|
680
|
cannam@147
|
681 Even though an orphan is unlinked from the message tree, it still resides inside memory allocated
|
cannam@147
|
682 for a particular message (i.e. a particular `MessageBuilder`). An orphan can only be adopted by
|
cannam@147
|
683 objects that live in the same message. To move objects between messages, you must perform a copy.
|
cannam@147
|
684 If the message is serialized while an `Orphan<T>` living within it still exists, the orphan's
|
cannam@147
|
685 content will be part of the serialized message, but the only way the receiver could find it is by
|
cannam@147
|
686 investigating the raw message; the Cap'n Proto API provides no way to detect or read it.
|
cannam@147
|
687
|
cannam@147
|
688 To construct an orphan from scratch (without having some other object disown it), you need an
|
cannam@147
|
689 `Orphanage`, which is essentially an orphan factory associated with some message. You can get one
|
cannam@147
|
690 by calling the `MessageBuilder`'s `getOrphanage()` method, or by calling the static method
|
cannam@147
|
691 `Orphanage::getForMessageContaining(builder)` and passing it any struct or list builder.
|
cannam@147
|
692
|
cannam@147
|
693 Note that when an `Orphan<T>` goes out-of-scope without being adopted, the underlying memory that
|
cannam@147
|
694 it occupied is overwritten with zeros. If you use packed serialization, these zeros will take very
|
cannam@147
|
695 little bandwidth on the wire, but will still waste memory on the sending and receiving ends.
|
cannam@147
|
696 Generally, you should avoid allocating message objects that won't be used, or if you cannot avoid
|
cannam@147
|
697 it, arrange to copy the entire message over to a new `MessageBuilder` before serializing, since
|
cannam@147
|
698 only the reachable objects will be copied.
|
cannam@147
|
699
|
cannam@147
|
700 ## Reference
|
cannam@147
|
701
|
cannam@147
|
702 The runtime library contains lots of useful features not described on this page. For now, the
|
cannam@147
|
703 best reference is the header files. See:
|
cannam@147
|
704
|
cannam@147
|
705 capnp/list.h
|
cannam@147
|
706 capnp/blob.h
|
cannam@147
|
707 capnp/message.h
|
cannam@147
|
708 capnp/serialize.h
|
cannam@147
|
709 capnp/serialize-packed.h
|
cannam@147
|
710 capnp/schema.h
|
cannam@147
|
711 capnp/schema-loader.h
|
cannam@147
|
712 capnp/dynamic.h
|
cannam@147
|
713
|
cannam@147
|
714 ## Tips and Best Practices
|
cannam@147
|
715
|
cannam@147
|
716 Here are some tips for using the C++ Cap'n Proto runtime most effectively:
|
cannam@147
|
717
|
cannam@147
|
718 * Accessor methods for primitive (non-pointer) fields are fast and inline. They should be just
|
cannam@147
|
719 as fast as accessing a struct field through a pointer.
|
cannam@147
|
720
|
cannam@147
|
721 * Accessor methods for pointer fields, on the other hand, are not inline, as they need to validate
|
cannam@147
|
722 the pointer. If you intend to access the same pointer multiple times, it is a good idea to
|
cannam@147
|
723 save the value to a local variable to avoid repeating this work. This is generally not a
|
cannam@147
|
724 problem given C++11's `auto`.
|
cannam@147
|
725
|
cannam@147
|
726 Example:
|
cannam@147
|
727
|
cannam@147
|
728 // BAD
|
cannam@147
|
729 frob(foo.getBar().getBaz(),
|
cannam@147
|
730 foo.getBar().getQux(),
|
cannam@147
|
731 foo.getBar().getCorge());
|
cannam@147
|
732
|
cannam@147
|
733 // GOOD
|
cannam@147
|
734 auto bar = foo.getBar();
|
cannam@147
|
735 frob(bar.getBaz(), bar.getQux(), bar.getCorge());
|
cannam@147
|
736
|
cannam@147
|
737 It is especially important to use this style when reading messages, for another reason: as
|
cannam@147
|
738 described under the "security tips" section, below, every time you `get` a pointer, Cap'n Proto
|
cannam@147
|
739 increments a counter by the size of the target object. If that counter hits a pre-defined limit,
|
cannam@147
|
740 an exception is thrown (or a default value is returned, if exceptions are disabled), to prevent
|
cannam@147
|
741 a malicious client from sending your server into an infinite loop with a specially-crafted
|
cannam@147
|
742 message. If you repeatedly `get` the same object, you are repeatedly counting the same bytes,
|
cannam@147
|
743 and so you may hit the limit prematurely. (Since Cap'n Proto readers are backed directly by
|
cannam@147
|
744 the underlying message buffer and do not have anywhere else to store per-object information, it
|
cannam@147
|
745 is impossible to remember whether you've seen a particular object already.)
|
cannam@147
|
746
|
cannam@147
|
747 * Internally, all pointer fields start out "null", even if they have default values. When you have
|
cannam@147
|
748 a pointer field `foo` and you call `getFoo()` on the containing struct's `Reader`, if the field
|
cannam@147
|
749 is "null", you will receive a reader for that field's default value. This reader is backed by
|
cannam@147
|
750 read-only memory; nothing is allocated. However, when you call `get` on a _builder_, and the
|
cannam@147
|
751 field is null, then the implementation must make a _copy_ of the default value to return to you.
|
cannam@147
|
752 Thus, you've caused the field to become non-null, just by "reading" it. On the other hand, if
|
cannam@147
|
753 you call `init` on that field, you are explicitly replacing whatever value is already there
|
cannam@147
|
754 (null or not) with a newly-allocated instance, and that newly-allocated instance is _not_ a
|
cannam@147
|
755 copy of the field's default value, but just a completely-uninitialized instance of the
|
cannam@147
|
756 appropriate type.
|
cannam@147
|
757
|
cannam@147
|
758 * It is possible to receive a struct value constructed from a newer version of the protocol than
|
cannam@147
|
759 the one your binary was built with, and that struct might have extra fields that you don't know
|
cannam@147
|
760 about. The Cap'n Proto implementation tries to avoid discarding this extra data. If you copy
|
cannam@147
|
761 the struct from one message to another (e.g. by calling a set() method on a parent object), the
|
cannam@147
|
762 extra fields will be preserved. This makes it possible to build proxies that receive messages
|
cannam@147
|
763 and forward them on without having to rebuild the proxy every time a new field is added. You
|
cannam@147
|
764 must be careful, however: in some cases, it's not possible to retain the extra fields, because
|
cannam@147
|
765 they need to be copied into a space that is allocated before the expected content is known.
|
cannam@147
|
766 In particular, lists of structs are represented as a flat array, not as an array of pointers.
|
cannam@147
|
767 Therefore, all memory for all structs in the list must be allocated upfront. Hence, copying
|
cannam@147
|
768 a struct value from another message into an element of a list will truncate the value. Because
|
cannam@147
|
769 of this, the setter method for struct lists is called `setWithCaveats()` rather than just `set()`.
|
cannam@147
|
770
|
cannam@147
|
771 * Messages are built in "arena" or "region" style: each object is allocated sequentially in
|
cannam@147
|
772 memory, until there is no more room in the segment, in which case a new segment is allocated,
|
cannam@147
|
773 and objects continue to be allocated sequentially in that segment. This design is what makes
|
cannam@147
|
774 Cap'n Proto possible at all, and it is very fast compared to other allocation strategies.
|
cannam@147
|
775 However, it has the disadvantage that if you allocate an object and then discard it, that memory
|
cannam@147
|
776 is lost. In fact, the empty space will still become part of the serialized message, even though
|
cannam@147
|
777 it is unreachable. The implementation will try to zero it out, so at least it should pack well,
|
cannam@147
|
778 but it's still better to avoid this situation. Some ways that this can happen include:
|
cannam@147
|
779 * If you `init` a field that is already initialized, the previous value is discarded.
|
cannam@147
|
780 * If you create an orphan that is never adopted into the message tree.
|
cannam@147
|
781 * If you use `adoptWithCaveats` to adopt an orphaned struct into a struct list, then a shallow
|
cannam@147
|
782 copy is necessary, since the struct list requires that its elements are sequential in memory.
|
cannam@147
|
783 The previous copy of the struct is discarded (although child objects are transferred properly).
|
cannam@147
|
784 * If you copy a struct value from another message using a `set` method, the copy will have the
|
cannam@147
|
785 same size as the original. However, the original could have been built with an older version
|
cannam@147
|
786 of the protocol which lacked some fields compared to the version your program was built with.
|
cannam@147
|
787 If you subsequently `get` that struct, the implementation will be forced to allocate a new
|
cannam@147
|
788 (shallow) copy which is large enough to hold all known fields, and the old copy will be
|
cannam@147
|
789 discarded. Child objects will be transferred over without being copied -- though they might
|
cannam@147
|
790 suffer from the same problem if you `get` them later on.
|
cannam@147
|
791 Sometimes, avoiding these problems is too inconvenient. Fortunately, it's also possible to
|
cannam@147
|
792 clean up the mess after-the-fact: if you copy the whole message tree into a fresh
|
cannam@147
|
793 `MessageBuilder`, only the reachable objects will be copied, leaving out all of the unreachable
|
cannam@147
|
794 dead space.
|
cannam@147
|
795
|
cannam@147
|
796 In the future, Cap'n Proto may be improved such that it can re-use dead space in a message.
|
cannam@147
|
797 However, this will only improve things, not fix them entirely: fragementation could still leave
|
cannam@147
|
798 dead space.
|
cannam@147
|
799
|
cannam@147
|
800 ### Build Tips
|
cannam@147
|
801
|
cannam@147
|
802 * If you are worried about the binary footprint of the Cap'n Proto library, consider statically
|
cannam@147
|
803 linking with the `--gc-sections` linker flag. This will allow the linker to drop pieces of the
|
cannam@147
|
804 library that you do not actually use. For example, many users do not use the dynamic schema and
|
cannam@147
|
805 reflection APIs, which contribute a large fraction of the Cap'n Proto library's overall
|
cannam@147
|
806 footprint. Keep in mind that if you ever stringify a Cap'n Proto type, the stringification code
|
cannam@147
|
807 depends on the dynamic API; consider only using stringification in debug builds.
|
cannam@147
|
808
|
cannam@147
|
809 If you are dynamically linking against the system's shared copy of `libcapnp`, don't worry about
|
cannam@147
|
810 its binary size. Remember that only the code which you actually use will be paged into RAM, and
|
cannam@147
|
811 those pages are shared with other applications on the system.
|
cannam@147
|
812
|
cannam@147
|
813 Also remember to strip your binary. In particular, `libcapnpc` (the schema parser) has
|
cannam@147
|
814 excessively large symbol names caused by its use of template-based parser combinators. Stripping
|
cannam@147
|
815 the binary greatly reduces its size.
|
cannam@147
|
816
|
cannam@147
|
817 * The Cap'n Proto library has lots of debug-only asserts that are removed if you `#define NDEBUG`,
|
cannam@147
|
818 including in headers. If you care at all about performance, you should compile your production
|
cannam@147
|
819 binaries with the `-DNDEBUG` compiler flag. In fact, if Cap'n Proto detects that you have
|
cannam@147
|
820 optimization enabled but have not defined `NDEBUG`, it will define it for you (with a warning),
|
cannam@147
|
821 unless you define `DEBUG` or `KJ_DEBUG` to explicitly request debugging.
|
cannam@147
|
822
|
cannam@147
|
823 ### Security Tips
|
cannam@147
|
824
|
cannam@147
|
825 Cap'n Proto has not yet undergone security review. It most likely has some vulnerabilities. You
|
cannam@147
|
826 should not attempt to decode Cap'n Proto messages from sources you don't trust at this time.
|
cannam@147
|
827
|
cannam@147
|
828 However, assuming the Cap'n Proto implementation hardens up eventually, then the following security
|
cannam@147
|
829 tips will apply.
|
cannam@147
|
830
|
cannam@147
|
831 * It is highly recommended that you enable exceptions. When compiled with `-fno-exceptions`,
|
cannam@147
|
832 Cap'n Proto categorizes exceptions into "fatal" and "recoverable" varieties. Fatal exceptions
|
cannam@147
|
833 cause the server to crash, while recoverable exceptions are handled by logging an error and
|
cannam@147
|
834 returning a "safe" garbage value. Fatal is preferred in cases where it's unclear what kind of
|
cannam@147
|
835 garbage value would constitute "safe". The more of the library you use, the higher the chance
|
cannam@147
|
836 that you will leave yourself open to the possibility that an attacker could trigger a fatal
|
cannam@147
|
837 exception somewhere. If you enable exceptions, then you can catch the exception instead of
|
cannam@147
|
838 crashing, and return an error just to the attacker rather than to everyone using your server.
|
cannam@147
|
839
|
cannam@147
|
840 Basic parsing of Cap'n Proto messages shouldn't ever trigger fatal exceptions (assuming the
|
cannam@147
|
841 implementation is not buggy). However, the dynamic API -- especially if you are loading schemas
|
cannam@147
|
842 controlled by the attacker -- is much more exception-happy. If you cannot use exceptions, then
|
cannam@147
|
843 you are advised to avoid the dynamic API when dealing with untrusted data.
|
cannam@147
|
844
|
cannam@147
|
845 * If you need to process schemas from untrusted sources, take them in binary format, not text.
|
cannam@147
|
846 The text parser is a much larger attack surface and not designed to be secure. For instance,
|
cannam@147
|
847 as of this writing, it is trivial to deadlock the parser by simply writing a constant whose value
|
cannam@147
|
848 depends on itself.
|
cannam@147
|
849
|
cannam@147
|
850 * Cap'n Proto automatically applies two artificial limits on messages for security reasons:
|
cannam@147
|
851 a limit on nesting dept, and a limit on total bytes traversed.
|
cannam@147
|
852
|
cannam@147
|
853 * The nesting depth limit is designed to prevent stack overflow when handling a deeply-nested
|
cannam@147
|
854 recursive type, and defaults to 64. If your types aren't recursive, it is highly unlikely
|
cannam@147
|
855 that you would ever hit this limit, and even if they are recursive, it's still unlikely.
|
cannam@147
|
856
|
cannam@147
|
857 * The traversal limit is designed to defend against maliciously-crafted messages which use
|
cannam@147
|
858 pointer cycles or overlapping objects to make a message appear much larger than it looks off
|
cannam@147
|
859 the wire. While cycles and overlapping objects are illegal, they are hard to detect reliably.
|
cannam@147
|
860 Instead, Cap'n Proto places a limit on how many bytes worth of objects you can _dereference_
|
cannam@147
|
861 before it throws an exception. This limit is assessed every time you follow a pointer. By
|
cannam@147
|
862 default, the limit is 64MiB (this may change in the future). `StreamFdMessageReader` will
|
cannam@147
|
863 actually reject upfront any message which is larger than the traversal limit, even before you
|
cannam@147
|
864 start reading it.
|
cannam@147
|
865
|
cannam@147
|
866 If you need to write your code in such a way that you might frequently re-read the same
|
cannam@147
|
867 pointers, instead of increasing the traversal limit to the point where it is no longer useful,
|
cannam@147
|
868 consider simply copying the message into a new `MallocMessageBuilder` before starting. Then,
|
cannam@147
|
869 the traversal limit will be enforced only during the copy. There is no traversal limit on
|
cannam@147
|
870 objects once they live in a `MessageBuilder`, even if you use `.asReader()` to convert a
|
cannam@147
|
871 particular object's builder to the corresponding reader type.
|
cannam@147
|
872
|
cannam@147
|
873 Both limits may be increased using `capnp::ReaderOptions`, defined in `capnp/message.h`.
|
cannam@147
|
874
|
cannam@147
|
875 * Remember that enums on the wire may have a numeric value that does not match any value defined
|
cannam@147
|
876 in the schema. Your `switch()` statements must always have a safe default case.
|
cannam@147
|
877
|
cannam@147
|
878 ## Lessons Learned from Protocol Buffers
|
cannam@147
|
879
|
cannam@147
|
880 The author of Cap'n Proto's C++ implementation also wrote (in the past) verison 2 of Google's
|
cannam@147
|
881 Protocol Buffers. As a result, Cap'n Proto's implementation benefits from a number of lessons
|
cannam@147
|
882 learned the hard way:
|
cannam@147
|
883
|
cannam@147
|
884 * Protobuf generated code is enormous due to the parsing and serializing code generated for every
|
cannam@147
|
885 class. This actually poses a significant problem in practice -- there exist server binaries
|
cannam@147
|
886 containing literally hundreds of megabytes of compiled protobuf code. Cap'n Proto generated code,
|
cannam@147
|
887 on the other hand, is almost entirely inlined accessors. The only things that go into `.capnp.o`
|
cannam@147
|
888 files are default values for pointer fields (if needed, which is rare) and the encoded schema
|
cannam@147
|
889 (just the raw bytes of a Cap'n-Proto-encoded schema structure). The latter could even be removed
|
cannam@147
|
890 if you don't use dynamic reflection.
|
cannam@147
|
891
|
cannam@147
|
892 * The C++ Protobuf implementation used lots of dynamic initialization code (that runs before
|
cannam@147
|
893 `main()`) to do things like register types in global tables. This proved problematic for
|
cannam@147
|
894 programs which linked in lots of protocols but needed to start up quickly. Cap'n Proto does not
|
cannam@147
|
895 use any dynamic initializers anywhere, period.
|
cannam@147
|
896
|
cannam@147
|
897 * The C++ Protobuf implementation makes heavy use of STL in its interface and implementation.
|
cannam@147
|
898 The proliferation of template instantiations gives the Protobuf runtime library a large footprint,
|
cannam@147
|
899 and using STL in the interface can lead to weird ABI problems and slow compiles. Cap'n Proto
|
cannam@147
|
900 does not use any STL containers in its interface and makes sparing use in its implementation.
|
cannam@147
|
901 As a result, the Cap'n Proto runtime library is smaller, and code that uses it compiles quickly.
|
cannam@147
|
902
|
cannam@147
|
903 * The in-memory representation of messages in Protobuf-C++ involves many heap objects. Each
|
cannam@147
|
904 message (struct) is an object, each non-primitive repeated field allocates an array of pointers
|
cannam@147
|
905 to more objects, and each string may actually add two heap objects. Cap'n Proto by its nature
|
cannam@147
|
906 uses arena allocation, so the entire message is allocated in a few contiguous segments. This
|
cannam@147
|
907 means Cap'n Proto spends very little time allocating memory, stores messages more compactly, and
|
cannam@147
|
908 avoids memory fragmentation.
|
cannam@147
|
909
|
cannam@147
|
910 * Related to the last point, Protobuf-C++ relies heavily on object reuse for performance.
|
cannam@147
|
911 Building or parsing into a newly-allocated Protobuf object is significantly slower than using
|
cannam@147
|
912 an existing one. However, the memory usage of a Protobuf object will tend to grow the more times
|
cannam@147
|
913 it is reused, particularly if it is used to parse messages of many different "shapes", so the
|
cannam@147
|
914 objects need to be deleted and re-allocated from time to time. All this makes tuning Protobufs
|
cannam@147
|
915 fairly tedious. In contrast, enabling memory reuse with Cap'n Proto is as simple as providing
|
cannam@147
|
916 a byte buffer to use as scratch space when you build or read in a message. Provide enough scratch
|
cannam@147
|
917 space to hold the entire message and Cap'n Proto won't allocate any memory. Or don't -- since
|
cannam@147
|
918 Cap'n Proto doesn't do much allocation in the first place, the benefits of scratch space are
|
cannam@147
|
919 small.
|