| 1 |
<?% config.freshness.reviewed = '2022-04-12' %?> |
| 2 |
|
| 3 |
# upb vs. C++ Protobuf Design |
| 4 |
|
| 5 |
[upb](https://github.com/protocolbuffers/upb) is a small C protobuf library. |
| 6 |
While some of the design follows in the footsteps of the C++ Protobuf Library, |
| 7 |
upb departs from C++'s design in several key ways. This document compares |
| 8 |
and contrasts the two libraries on several design points. |
| 9 |
|
| 10 |
## Design Goals |
| 11 |
|
| 12 |
Before we begin, it is worth calling out that upb and C++ have different design |
| 13 |
goals, and this motivates some of the differences we will see. |
| 14 |
|
| 15 |
C++ protobuf is a user-level library: it is designed to be used directly by C++ |
| 16 |
applications. These applications will expect a full-featured C++ API surface |
| 17 |
that uses C++ idioms. The C++ library is also willing to add features to |
| 18 |
increase server performance, even if these features would add size or complexity |
| 19 |
to the library. Because C++ protobuf is a user-level library, API stability is |
| 20 |
of utmost importance: breaking API changes are rare and carefully managed when |
| 21 |
they do occur. The focus on C++ also means that ABI compatibility with C is not |
| 22 |
a priority. |
| 23 |
|
| 24 |
upb, on the other hand, is designed primarily to be wrapped by other languages. |
| 25 |
It is a C protobuf kernel that forms the basis on which a user-level protobuf |
| 26 |
library can be built. This means we prefer to keep the API surface as small and |
| 27 |
orthogonal as possible. While upb supports all protobuf features required for |
| 28 |
full conformance, upb prioritizes simplicity and small code size, and avoids |
| 29 |
adding features like lazy fields that can accelerate some use cases but at great |
| 30 |
cost in terms of complexity. As upb is not aimed directly at users, there is |
| 31 |
much more freedom to make API-breaking changes when necessary, which helps the |
| 32 |
core to stay small and simple. We want to be compatible with all FFI |
| 33 |
interfaces, so C ABI compatibility is a must. |
| 34 |
|
| 35 |
Despite these differences, C++ protos and upb offer [roughly the same core set |
| 36 |
of features](https://github.com/protocolbuffers/upb#features). |
| 37 |
|
| 38 |
## Arenas |
| 39 |
|
| 40 |
upb and C++ protos both offer arena allocation, but there are some key |
| 41 |
differences. |
| 42 |
|
| 43 |
### C++ |
| 44 |
|
| 45 |
As a matter of history, when C++ protos were open-sourced in 2008, they did not |
| 46 |
support arenas. Originally there was only unique ownership, whereby each |
| 47 |
message uniquely owns all child messages and will free them when the parent is |
| 48 |
freed. |
| 49 |
|
| 50 |
Arena allocation was added as a feature in 2014 as a way of dramatically |
| 51 |
reducing allocation and (especially) deallocation costs. But the library was |
| 52 |
not at liberty to remove the unique ownership model, because it would break far |
| 53 |
too many users. As a result, C++ has supported a **hybrid allocation model** |
| 54 |
ever since, allowing users to allocate messages either directly from the |
| 55 |
stack/heap or from an arena. The library attempts to ensure that there are |
| 56 |
no dangling pointers by performing automatic copies in some cases (for example |
| 57 |
`a->set_allocated_b(b)`, where `a` and `b` are on different arenas). |
| 58 |
|
| 59 |
C++'s arena object itself `google::protobuf::Arena` is **thread-safe** by |
| 60 |
design, which allows users to allocate from multiple threads simultaneously |
| 61 |
without external synchronization. The user can supply an initial block of |
| 62 |
memory to the arena, and can choose some parameters to control the arena block |
| 63 |
size. The user can also supply block alloc/dealloc functions, but the alloc |
| 64 |
function is expected to always return some memory. The C++ library in general |
| 65 |
does not attempt to handle out of memory conditions. |
| 66 |
|
| 67 |
### upb |
| 68 |
|
| 69 |
upb uses **arena allocation exclusively**. All messages must be allocated from |
| 70 |
an arena, and can only be freed by freeing the arena. It is entirely the user's |
| 71 |
responsibility to ensure that there are no dangling pointers: when a user sets a |
| 72 |
message field, this will always trivially overwrite the pointer and will never |
| 73 |
perform an implicit copy. |
| 74 |
|
| 75 |
upb's `upb::Arena` is **thread-compatible**, which means it cannot be used |
| 76 |
concurrently without synchronization. The arena can be seeded with an initial |
| 77 |
block of memory, but it does not explicitly support any parameters for choosing |
| 78 |
block size. It support a custom alloc/dealloc function, and this function is |
| 79 |
allowed to return `NULL` if no dynamic memory is available. This allows upb |
| 80 |
arenas to have a max/fixed size, and makes it possible in theory to write code |
| 81 |
that is tolerant to out-of-memory errors. |
| 82 |
|
| 83 |
upb's arena also supports a novel operation known as **fuse**, which joins two |
| 84 |
arenas together into a single lifetime. Though both arenas must still be freed |
| 85 |
separately, none of the memory will actually be freed until *both* arenas have |
| 86 |
been freed. This is useful for avoiding dangling pointers when reparenting a |
| 87 |
message with one that may be on a different arena. |
| 88 |
|
| 89 |
### Comparison |
| 90 |
|
| 91 |
**hybrid allocation vs. arena-only**: |
| 92 |
* The C++ hybrid allocation model introduces a great deal of complexity and |
| 93 |
unpredictability into the library. upb benefits from having a much simpler |
| 94 |
and more predictable design. |
| 95 |
* Some of the complexity in C++'s hybrid model arises from the fact that arenas |
| 96 |
were added after the fact. Designing for a hybrid model from the outset |
| 97 |
would likely yield a simpler result. |
| 98 |
* Unique ownership does support some usage patterns that arenas cannot directly |
| 99 |
accommodate. For example, you can reparent a message and the child will precisely |
| 100 |
follow the lifetime of its new parent. An arena would require you to either |
| 101 |
perform a deep copy or extend the lifetime. |
| 102 |
|
| 103 |
**thread-compatible vs. thread-safe arena** |
| 104 |
* A thread-safe arena (as in C++) is safer and easier to use. A thread-compatible |
| 105 |
arena requires that the user prove that the arena cannot be used concurrently. |
| 106 |
* [Thread Sanitizer](https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual) |
| 107 |
is far more accessible than it was in 2014 (when C++ introduced a thread-safe |
| 108 |
arena). We now have more tools at our disposal to ensure that we do not trigger |
| 109 |
data races in a thread-compatible arena like upb. |
| 110 |
* Thread-compatible arenas are more performant. |
| 111 |
* Thread-compatible arenas have a far simpler implementation. The C++ thread-safe |
| 112 |
arena relies on thread-local variables, which introduce complications on some |
| 113 |
platforms. It also requires far more subtle reasoning for correctness and |
| 114 |
performance. |
| 115 |
|
| 116 |
**fuse vs. no fuse** |
| 117 |
* The `upb_Arena_Fuse()` operation is a key part of how upb supports reparenting |
| 118 |
of messages when the parent may be on a different arena. Without this, upb has |
| 119 |
no way of supporting `foo.bar = bar` in dynamic languages without performing a |
| 120 |
deep copy. |
| 121 |
* A downside of `upb_Arena_Fuse()` is that passing an arena to a function can allow |
| 122 |
that function to extend the lifetime of the arena in potentially |
| 123 |
unpredictable ways. This can be prevented if necessary, as fuse can fail, eg. if |
| 124 |
one arena has an initial block. But this adds some complexity by requiring callers |
| 125 |
to handle the case where fuse fails. |
| 126 |
|
| 127 |
## Code Generation vs. Tables |
| 128 |
|
| 129 |
The C++ protobuf library has always been built around code generation, while upb |
| 130 |
generates only tables. In other words, `foo.pb.cc` files contain functions, |
| 131 |
whereas `foo.upb.c` files emit only data structures. |
| 132 |
|
| 133 |
### C++ |
| 134 |
|
| 135 |
C++ generated code emits a large number of functions into `foo.pb.cc` files. |
| 136 |
An incomplete list: |
| 137 |
|
| 138 |
* `FooMsg::FooMsg()` (constructor): initializes all fields to their default value. |
| 139 |
* `FooMsg::~FooMsg()` (destructor): frees any present child messages. |
| 140 |
* `FooMsg::Clear()`: clears all fields back to their default/empty value. |
| 141 |
* `FooMsg::_InternalParse()`: generated code for parsing a message. |
| 142 |
* `FooMsg::_InternalSerialize()`: generated code for serializing a message. |
| 143 |
* `FooMsg::ByteSizeLong()`: calculates serialized size, as a first pass before serializing. |
| 144 |
* `FooMsg::MergeFrom()`: copies/appends present fields from another message. |
| 145 |
* `FooMsg::IsInitialized()`: checks whether required fields are set. |
| 146 |
|
| 147 |
This code lives in the `.text` section and contains function calls to the generated |
| 148 |
classes for child messages. |
| 149 |
|
| 150 |
### upb |
| 151 |
|
| 152 |
upb does not generate any code into `foo.upb.c` files, only data structures. upb uses a |
| 153 |
compact data table known as a *mini table* to represent the schema and all fields. |
| 154 |
|
| 155 |
upb uses mini tables to perform all of the operations that would traditionally be done |
| 156 |
with generated code. Revisiting the list from the previous section: |
| 157 |
|
| 158 |
* `FooMsg::FooMsg()` (constructor): upb instead initializes all messages with `memset(msg, 0, size)`. |
| 159 |
Non-zero defaults are injected in the accessors. |
| 160 |
* `FooMsg::~FooMsg()` (destructor): upb messages are freed by freeing the arena. |
| 161 |
* `FooMsg::Clear()`: can be performed with `memset(msg, 0, size)`. |
| 162 |
* `FooMsg::_InternalParse()`: upb's parser uses mini tables as data, instead of generating code. |
| 163 |
* `FooMsg::_InternalSerialize()`: upb's serializer also uses mini-tables instead of generated code. |
| 164 |
* `FooMsg::ByteSizeLong()`: upb performs serialization in reverse so that an initial pass is not required. |
| 165 |
* `FooMsg::MergeFrom()`: upb supports this via serialize+parse from the other message. |
| 166 |
* `FooMsg::IsInitialized()`: upb's encoder and decoder have special flags to check for required fields. |
| 167 |
A util library `upb/util/required_fields.h` handles the corner cases. |
| 168 |
|
| 169 |
### Comparison |
| 170 |
|
| 171 |
If we compare compiled code size, upb is far smaller. Here is a comparison of the code |
| 172 |
size of a trivial binary that does nothing but a parse and serialize of `descriptor.proto`. |
| 173 |
This means we are seeing both the overhead of the core library itself as well as the |
| 174 |
generated code (or table) for `descriptor.proto`. (For extra clarity we should break this |
| 175 |
down by generated code vs core library in the future). |
| 176 |
|
| 177 |
|
| 178 |
| Library | `.text` | `.data` | `.bss` | |
| 179 |
|------------ |---------|---------|--------| |
| 180 |
| upb | 26Ki | 0.6Ki | 0.01Ki | |
| 181 |
| C++ (lite) | 187Ki | 2.8Ki | 1.25Ki | |
| 182 |
| C++ (code size) | 904Ki | 6.1Ki | 1.88Ki | |
| 183 |
| C++ (full) | 983Ki | 6.1Ki | 1.88Ki | |
| 184 |
|
| 185 |
"C++ (code size)" refers to protos compiled with `optimize_for = CODE_SIZE`, a mode |
| 186 |
in which generated code contains reflection only, in an attempt to make the |
| 187 |
generated code size smaller (however it requires the full runtime instead |
| 188 |
of the lite runtime). |
| 189 |
|
| 190 |
## Bifurcated vs. Optional Reflection |
| 191 |
|
| 192 |
upb and C++ protos both offer reflection without making it mandatory. However |
| 193 |
the models for enabling/disabling reflection are very different. |
| 194 |
|
| 195 |
### C++ |
| 196 |
|
| 197 |
C++ messages offer full reflection by default. Messages in C++ generally |
| 198 |
derive from `Message`, and the base class provides a member function |
| 199 |
`Reflection* Message::GetReflection()` which returns the reflection object. |
| 200 |
|
| 201 |
It follows that any message deriving from `Message` will always have reflection |
| 202 |
linked into the binary, whether or not the reflection object is ever used. |
| 203 |
Because `GetReflection()` is a function on the base class, it is not possible |
| 204 |
to statically determine if a given message's reflection is used: |
| 205 |
|
| 206 |
```c++ |
| 207 |
Reflection* GetReflection(const Message& message) { |
| 208 |
// Can refer to any message in the whole binary. |
| 209 |
return message.GetReflection(); |
| 210 |
} |
| 211 |
``` |
| 212 |
|
| 213 |
The C++ library does provide a way of omitting reflection: `MessageLite`. We can |
| 214 |
cause a message to be lite in two different ways: |
| 215 |
|
| 216 |
* `optimize_for = LITE_RUNTIME` in a `.proto` file will cause all messages in that |
| 217 |
file to be lite. |
| 218 |
* `lite` as a codegen param: this will force all messages to lite, even if the |
| 219 |
`.proto` file does not have `optimize_for = LITE_RUNTIME`. |
| 220 |
|
| 221 |
A lite message will derive from `MessageLite` instead of `Message`. Since |
| 222 |
`MessageLite` has no `GetReflection()` function, this means no reflection is |
| 223 |
available, so we can avoid taking the code size hit. |
| 224 |
|
| 225 |
### upb |
| 226 |
|
| 227 |
upb does not have the `Message` vs. `MessageLite` bifurcation. There is only one |
| 228 |
kind of message type `upb_Message`, which means there is no need to configure in |
| 229 |
a `.proto` file which messages will need reflection and which will not. |
| 230 |
Every message has the *option* to link in reflection from a separate `foo.upbdefs.o` |
| 231 |
file, without needing to change the message itself in any way. |
| 232 |
|
| 233 |
upb does not provide the equivalent of `Message::GetReflection()`: there is no |
| 234 |
facility for retrieving the reflection of a message whose type is not known statically. |
| 235 |
It would be possible to layer such a facility on top of the upb core, though this |
| 236 |
would probably require some kind of code generation. |
| 237 |
|
| 238 |
### Comparison |
| 239 |
|
| 240 |
* Most messages in C++ will not bother to declare themselves as "lite". This means |
| 241 |
that many C++ messages will link in reflection even when it is never used, bloating |
| 242 |
binaries unnecessarily. |
| 243 |
* `optimize_for = LITE_RUNTIME` is difficult to use in practice, because it prevents |
| 244 |
any non-lite protos from `import`ing that file. |
| 245 |
* Forcing all protos to lite via a codegen parameter (for example, when building for |
| 246 |
mobile) is more practical than `optimize_for = LITE_RUNTIME`. But this will break |
| 247 |
the compile for any code that tries to upcast to `Message`, or tries to use a |
| 248 |
non-lite method. |
| 249 |
* The one major advantage of the C++ model is that it can support `msg.DebugString()` |
| 250 |
on a type-erased proto. For upb you have to explicitly pass the `upb_MessageDef*` |
| 251 |
separately if you want to perform an operation like printing a proto to text format. |
| 252 |
|
| 253 |
## Explicit Registration vs. Globals |
| 254 |
|
| 255 |
TODO |