1 # Coding conventions for Tor
5 - Run configure with `--enable-fatal-warnings`
6 - Document your functions
8 - Run `make check` before submitting a patch
9 - Run `make distcheck` if you have made changes to build system components
10 - Add a file in `changes` for your branch.
14 If possible, send your patch as one of these (in descending order of
17 - A git branch we can pull from
18 - Patches generated by git format-patch
23 - To build your code while configured with `--enable-fatal-warnings`?
24 - To run `make check-docs` to see whether all new options are on
26 - To write unit tests, as possible?
27 - To run `make test-full` to test against all unit and integration tests (or
28 `make test-full-online` if you have a working connection to the internet)?
29 - To test that the distribution will actually work via `make distcheck`?
30 - To base your code on the appropriate branch?
31 - To include a file in the `changes` directory as appropriate?
33 If you are submitting a major patch or new feature, or want to in the future...
35 - Set up Chutney and Stem, see `doc/HACKING/WritingTests.md`
36 - Run `make test-full` to test against all unit and integration tests.
38 If you have changed build system components:
39 - Please run `make distcheck`
40 - For example, if you have changed Makefiles, autoconf files, or anything
41 else that affects the build system.
45 Tor is distributed under the license terms in the LICENSE -- in
46 brief, the "3-clause BSD license". If you send us code to
47 distribute with Tor, it needs to be code that we can distribute
48 under those terms. Please don't send us patches unless you agree
51 Some compatible licenses include:
55 - CC0 Public Domain Dedication
57 ## How we use Git branches
59 Each main development series (like 0.2.1, 0.2.2, etc) has its main work
60 applied to a single branch. At most one series can be the development series
61 at a time; all other series are maintenance series that get bug-fixes only.
62 The development series is built in a git branch called "main"; the
63 maintenance series are built in branches called "maint-0.2.0", "maint-0.2.1",
64 and so on. We regularly merge the active maint branches forward.
66 For all series except the development series, we also have a "release" branch
67 (as in "release-0.2.1"). The release series is based on the corresponding
68 maintenance series, except that it deliberately lags the maint series for
69 most of its patches, so that bugfix patches are not typically included in a
70 maintenance release until they've been tested for a while in a development
71 release. Occasionally, we'll merge an urgent bugfix into the release branch
72 before it gets merged into maint, but that's rare.
74 If you're working on a bugfix for a bug that occurs in a particular version,
75 base your bugfix branch on the "maint" branch for the first supported series
76 that has that bug. (As of June 2013, we're supporting 0.2.3 and later.)
78 If you're working on a new feature, base it on the main branch. If you're
79 working on a new feature and it will take a while to implement and/or you'd
80 like to avoid the possibility of unrelated bugs in Tor while you're
81 implementing your feature, consider branching off of the latest maint- branch.
82 _Never_ branch off a relase- branch. Don't branch off a tag either: they come
83 from release branches. Doing so will likely produce a nightmare of merge
84 conflicts in the ChangeLog when it comes time to merge your branch into Tor.
85 Best advice: don't try to keep an independent branch forked for more than 6
86 months and expect it to merge cleanly. Try to merge pieces early and often.
90 When you do a commit that needs a ChangeLog entry, add a new file to
91 the `changes` toplevel subdirectory. It should have the format of a
92 one-entry changelog section from the current ChangeLog file, as in
94 o Major bugfixes (security):
95 - Fix a potential buffer overflow. Fixes bug 99999; bugfix on
97 o Minor features (performance):
98 - Make tor faster. Closes ticket 88888.
100 To write a changes file, first categorize the change. Some common categories
102 o Minor bugfixes (subheading):
103 o Major bugfixes (subheading):
104 o Minor features (subheading):
105 o Major features (subheading):
106 o Code simplifications and refactoring:
110 The subheading is a particular area within Tor. See the ChangeLog for
113 Then say what the change does. If it's a bugfix, mention what bug it fixes
114 and when the bug was introduced. To find out which Git tag the change was
115 introduced in, you can use `git describe --contains <sha1 of commit>`.
116 If you don't know the commit, you can search the git diffs (-S) for the first
117 instance of the feature (--reverse).
119 For example, for #30224, we wanted to know when the bridge-distribution-request
120 feature was introduced into Tor:
123 $ git log -S bridge-distribution-request --reverse commit ebab521525
124 Author: Roger Dingledine <arma@torproject.org>
125 Date: Sun Nov 13 02:39:16 2016 -0500
127 Add new BridgeDistribution config option
129 $ git describe --contains ebab521525
130 tor-0.3.2.3-alpha~15^2~4
133 If you need to know all the Tor versions that contain a commit, use:
136 $ git tag --contains 9f2efd02a1 | sort -V
148 If a bug was introduced before the oldest currently supported release series
149 of Tor, and it's hard to track down where it was introduced, you may say
150 "bugfix on all supported versions of Tor."
152 If at all possible, try to create the changes file in the same commit where
153 you are making the change. Please give it a distinctive name that no other
154 branch will use for the lifetime of your change. We usually use "ticketNNNNN"
155 or "bugNNNNN", where NNNNN is the ticket number. To verify the format of the
156 changes file, you can use `make check-changes`. This is run automatically as
157 part of `make check` -- if it fails, we must fix it as soon as possible, so
158 that our CI passes. These checks are implemented in
159 `scripts/maint/lintChanges.py`.
161 Changes file style guide:
162 * Make everything terse.
164 * Write from the user's point of view: describe the user-visible changes
167 * Mention configuration options by name. If they're rare or unusual,
168 remind people what they're for.
170 * Describe changes in the present tense and in the imperative: not past.
172 * Every bugfix should have a sentence of the form "Fixes bug 1234; bugfix
173 on 0.1.2.3-alpha", describing what bug was fixed and where it came from.
175 * "Relays", not "servers", "nodes", or "Tor relays".
177 When we go to make a release, we will concatenate all the entries
178 in changes to make a draft changelog, and clear the directory. We'll
179 then edit the draft changelog into a nice readable format.
181 What needs a changes file?
183 * A not-exhaustive list: Anything that might change user-visible
184 behavior. Anything that changes internals, documentation, or the build
185 system enough that somebody could notice. Big or interesting code
186 rewrites. Anything about which somebody might plausibly wonder "when
187 did that happen, and/or why did we do that" 6 months down the line.
189 What does not need a changes file?
191 * Bugfixes for code that hasn't shipped in any released version of Tor
192 * Any change to a file that is not distributed in the tarball. This
194 * Any change to our CI configuration that does not affect the distributed
196 * Any change to developer-only tools, unless those tools are distributed
198 * Non-functional code movement.
199 * Identifier re-namings, comment edits, spelling fixes, and so on.
201 Why use changes files instead of Git commit messages?
203 * Git commit messages are written for developers, not users, and they
204 are nigh-impossible to revise after the fact.
206 Why use changes files instead of entries in the ChangeLog?
208 * Having every single commit touch the ChangeLog file tended to create
209 zillions of merge conflicts.
211 ## Whitespace and C conformance
213 Tor's C code is written in accordance with the C99 standard. Invoke `make
214 check-spaces` from time to time, so it can tell you about deviations from our C
215 whitespace style. Generally, we use:
217 - Unix-style line endings
218 - K&R-style indentation
219 - No space before newlines
220 - Never more than one blank line in a row
221 - Always spaces, never tabs
222 - No more than 79-columns per line.
223 - Two spaces per indent.
224 - A space between control keywords and their corresponding paren
225 `if (x)`, `while (x)`, and `switch (x)`, never `if(x)`, `while(x)`, or
227 - A space between anything and an open brace.
228 - No space between a function name and an opening paren. `puts(x)`, not
230 - Function declarations at the start of the line.
231 - Use `void foo(void)` to declare a function with no arguments. Saying
232 `void foo()` is C++ syntax.
233 - Use `const` for new APIs.
234 - Variables should be initialized when declared, rather than declared at the
237 If you use an editor that has plugins for editorconfig.org, the file
238 `.editorconfig` will help you to conform this coding style.
240 We try hard to build without warnings everywhere. In particular, if
241 you're using gcc, you should invoke the configure script with the
242 option `--enable-fatal-warnings`. This will tell the compiler
243 to make all warnings into errors.
245 ## Functions to use; functions not to use
247 We have some wrapper functions like `tor_malloc`, `tor_free`, `tor_strdup`, and
248 `tor_gettimeofday;` use them instead of their generic equivalents. (They
249 always succeed or exit.)
251 Specifically, Don't use `malloc`, `realloc`, `calloc`, `free`, or
252 `strdup`. Use `tor_malloc`, `tor_realloc`, `tor_calloc`, `tor_free`, or
255 Don't use `tor_realloc(x, y\*z)`. Use `tor_reallocarray(x, y, z)` instead.;
257 You can get a full list of the compatibility functions that Tor provides by
258 looking through `src/lib/*/*.h`. You can see the
259 available containers in `src/lib/containers/*.h`. You should probably
260 familiarize yourself with these modules before you write too much code, or
261 else you'll wind up reinventing the wheel.
263 We don't use `strcat` or `strcpy` or `sprintf` of any of those notoriously
264 broken old C functions. We also avoid `strncat` and `strncpy`. Use
265 `strlcat`, `strlcpy`, or `tor_snprintf/tor_asprintf` instead.
267 We don't call `memcmp()` directly. Use `fast_memeq()`, `fast_memneq()`,
268 `tor_memeq()`, or `tor_memneq()` for most purposes. If you really need a
269 tristate return value, use `tor_memcmp()` or `fast_memcmp()`.
271 Don't call `assert()` directly. For hard asserts, use `tor_assert()`. For
272 soft asserts, use `tor_assert_nonfatal()` or `BUG()`. If you need to print
273 debug information in assert error message, consider using `tor_assertf()` and
274 `tor_assertf_nonfatal()`. If you are writing code that is too low-level to
275 use the logging subsystem, use `raw_assert()`.
277 Don't use `toupper()` and `tolower()` functions. Use `TOR_TOUPPER` and
278 `TOR_TOLOWER` macros instead. Similarly, use `TOR_ISALPHA`, `TOR_ISALNUM` et.
279 al. instead of `isalpha()`, `isalnum()`, etc.
281 When allocating new string to be added to a smartlist, use
282 `smartlist_add_asprintf()` to do both at once.
284 Avoid calling BSD socket functions directly. Use portable wrappers to work
285 with sockets and socket addresses. Also, sockets should be of type
288 Don't use any of these functions: they aren't portable. Use the
289 version prefixed with `tor_` instead: strtok_r, memmem, memstr,
290 asprintf, localtime_r, gmtime_r, inet_aton, inet_ntop, inet_pton,
291 getpass, ntohll, htonll. (This list is incomplete.)
293 ## What code can use what other code?
295 We're trying to simplify Tor's structure over time. In the long run, we want
296 Tor to be structured as a set of modules with *no circular dependencies*.
298 This property is currently provided by the modules in src/lib, but not
299 throughout the rest of Tor. In general, higher-level libraries may use
300 lower-level libraries, but never the reverse.
302 To prevent new circular dependencies from landing, we have a tool that
303 you can invoke with `make check-includes`, and which is run
304 automatically as part of `make check`. This tool will verify that, for
305 every source directory with a `.may_include` file, no local headers are
306 included except those specifically permitted by the `.may_include` file.
307 When editing one of these files, please make sure that you are not
308 introducing any cycles into Tor's dependency graph.
310 ## Floating point math is hard
312 Floating point arithmetic as typically implemented by computers is
313 very counterintuitive. Failure to adequately analyze floating point
314 usage can result in surprising behavior and even security
319 - Don't use floating point.
320 - If you must use floating point, document how the limits of
321 floating point precision and calculation accuracy affect function
323 - Try to do as much as possible of your calculations using integers
324 (possibly acting as fixed-point numbers) and convert to floating
326 - If you must send floating point numbers on the wire, serialize
327 them in a platform-independent way. Tor avoids exchanging
328 floating-point values, but when it does, it uses ASCII numerals,
329 with a decimal point (".").
330 - Binary fractions behave very differently from decimal fractions.
331 Make sure you understand how these differences affect your
333 - Every floating point arithmetic operation is an opportunity to
334 lose precision, overflow, underflow, or otherwise produce
335 undesired results. Addition and subtraction tend to be worse
336 than multiplication and division (due to things like catastrophic
337 cancellation). Try to arrange your calculations to minimize such
339 - Changing the order of operations changes the results of many
340 floating-point calculations. Be careful when you simplify
341 calculations! If the order is significant, document it using a
343 - Comparing most floating point values for equality is unreliable.
344 Avoid using `==`, instead, use `>=` or `<=`. If you use an
345 epsilon value, make sure it's appropriate for the ranges in
347 - Different environments (including compiler flags and per-thread
348 state on a single platform!) can get different results from the
349 same floating point calculations. This means you can't use
350 floats in anything that needs to be deterministic, like consensus
351 generation. This also makes reliable unit tests of
352 floating-point outputs hard to write.
354 For additional useful advice (and a little bit of background), see
355 [What Every Programmer Should Know About Floating-Point
356 Arithmetic](https://floating-point-gui.de/).
358 A list of notable (and surprising) facts about floating point
359 arithmetic is at [Floating-point
360 complexities](https://randomascii.wordpress.com/2012/04/05/floating-point-complexities/).
361 Most of that [series of posts on floating
362 point](https://randomascii.wordpress.com/category/floating-point/) is
365 For more detailed (and math-intensive) background, see [What Every
366 Computer Scientist Should Know About Floating-Point
367 Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html).
369 ## Other C conventions
371 The `a ? b : c` trinary operator only goes inside other expressions;
372 don't use it as a replacement for if. (You can ignore this inside macro
373 definitions when necessary.)
375 Assignment operators shouldn't nest inside other expressions. (You can
376 ignore this inside macro definitions when necessary.)
378 ## Binary data and wire formats
380 Use pointer to `char` when representing NUL-terminated string. To represent
381 arbitrary binary data, use pointer to `uint8_t`. (Many older Tor APIs ignore
384 Refrain from attempting to encode integers by casting their pointers to byte
385 arrays. Use something like `set_uint32()`/`get_uint32()` instead and don't
386 forget about endianness.
388 Try to never hand-write new code to parse or generate binary
389 formats. Instead, use trunnel if at all possible. See
391 https://gitweb.torproject.org/trunnel.git/tree
393 for more information about trunnel.
395 For information on adding new trunnel code to Tor, see src/trunnel/README
397 ## Calling and naming conventions
399 Whenever possible, functions should return -1 on error and 0 on success.
401 For multi-word identifiers, use lowercase words combined with
402 underscores. (e.g., `multi_word_identifier`). Use ALL_CAPS for macros and
405 Typenames should end with `_t`.
407 Function names should be prefixed with a module name or object name. (In
408 general, code to manipulate an object should be a module with the same name
409 as the object, so it's hard to tell which convention is used.)
411 Functions that do things should have imperative-verb names
412 (e.g. `buffer_clear`, `buffer_resize`); functions that return booleans should
413 have predicate names (e.g. `buffer_is_empty`, `buffer_needs_resizing`).
415 If you find that you have four or more possible return code values, it's
416 probably time to create an enum. If you find that you are passing three or
417 more flags to a function, it's probably time to create a flags argument that
422 Don't optimize anything if it's not in the critical path. Right now, the
423 critical path seems to be AES, logging, and the network itself. Feel free to
424 do your own profiling to determine otherwise.
428 [FAQ - Log Levels](https://www.torproject.org/docs/faq#LogLevel)
430 No error or warning messages should be expected during normal OR or OP
433 If a library function is currently called such that failure always means ERR,
434 then the library function should log WARN and let the caller log ERR.
436 Every message of severity INFO or higher should either (A) be intelligible
437 to end-users who don't know the Tor source; or (B) somehow inform the
438 end-users that they aren't expected to understand the message (perhaps
439 with a string like "internal error"). Option (A) is to be preferred to
444 Assertions should be used for bug-detection only. Don't use assertions to
445 detect bad user inputs, network errors, resource exhaustion, or similar
448 Tor is always built with assertions enabled, so try to only use
449 `tor_assert()` for cases where you are absolutely sure that crashing is the
450 least bad option. Many bugs have been caused by use of `tor_assert()` when
451 another kind of check would have been safer.
453 If you're writing an assertion to test for a bug that you _can_ recover from,
454 use `tor_assert_nonfatal()` in place of `tor_assert()`. If you'd like to
455 write a conditional that incorporates a nonfatal assertion, use the `BUG()`
459 if (BUG(ptr == NULL))
463 ## Allocator conventions
465 By convention, any tor type with a name like `abc_t` should be allocated
466 by a function named `abc_new()`. This function should never return
469 Also, a type named `abc_t` should be freed by a function named `abc_free_()`.
470 Don't call this `abc_free_()` function directly -- instead, wrap it in a
471 macro called `abc_free()`, using the `FREE_AND_NULL` macro:
474 void abc_free_(abc_t *obj);
475 #define abc_free(obj) FREE_AND_NULL(abc_t, abc_free_, (obj))
478 This macro will free the underlying `abc_t` object, and will also set
479 the object pointer to NULL.
481 You should define all `abc_free_()` functions to accept NULL inputs:
485 abc_free_(abc_t *obj)
490 thing_free(obj->thing);
495 If you need a free function that takes a `void *` argument (for example,
496 to use it as a function callback), define it with a name like
501 abc_free_void_(void *obj)
507 When deallocating, don't say e.g. `if (x) tor_free(x)`. The convention is to
508 have deallocators do nothing when NULL pointer is passed.
510 ## Doxygen comment conventions
512 Say what functions do as a series of one or more imperative sentences, as
513 though you were telling somebody how to be the function. In other words, DO
517 /** The strtol function parses a number.
519 * nptr -- the string to parse. It can include whitespace.
520 * endptr -- a string pointer to hold the first thing that is not part
521 * of the number, if present.
522 * base -- the numeric base.
523 * returns: the resulting number.
525 long strtol(const char *nptr, char **nptr, int base);
528 Instead, please DO say:
531 /** Parse a number in radix <b>base</b> from the string <b>nptr</b>,
532 * and return the result. Skip all leading whitespace. If
533 * <b>endptr</b> is not NULL, set *<b>endptr</b> to the first character
534 * after the number parsed.
536 long strtol(const char *nptr, char **nptr, int base);
539 Doxygen comments are the contract in our abstraction-by-contract world: if
540 the functions that call your function rely on it doing something, then your
541 function should mention that it does that something in the documentation. If
542 you rely on a function doing something beyond what is in its documentation,
543 then you should watch out, or it might do something else later.