Document callgraph analysis code
[tor.git] / doc / HACKING
blobe92d675a43d8885321203d94084fd3a3fb4cd849
1 Hacking Tor: An Incomplete Guide
2 ================================
4 Getting started
5 ---------------
7 For full information on how Tor is supposed to work, look at the files in
8 https://gitweb.torproject.org/torspec.git/tree
10 For an explanation of how to change Tor's design to work differently, look at
11 https://gitweb.torproject.org/torspec.git/blob_plain/HEAD:/proposals/001-process.txt
13 For the latest version of the code, get a copy of git, and
15    git clone https://git.torproject.org/git/tor
17 We talk about Tor on the tor-talk mailing list.  Design proposals and
18 discussion belong on the tor-dev mailing list.  We hang around on
19 irc.oftc.net, with general discussion happening on #tor and development
20 happening on #tor-dev.
22 How we use Git branches
23 -----------------------
25 Each main development series (like 0.2.1, 0.2.2, etc) has its main work
26 applied to a single branch.  At most one series can be the development series
27 at a time; all other series are maintenance series that get bug-fixes only.
28 The development series is built in a git branch called "master"; the
29 maintenance series are built in branches called "maint-0.2.0", "maint-0.2.1",
30 and so on.  We regularly merge the active maint branches forward.
32 For all series except the development series, we also have a "release" branch
33 (as in "release-0.2.1").  The release series is based on the corresponding
34 maintenance series, except that it deliberately lags the maint series for
35 most of its patches, so that bugfix patches are not typically included in a
36 maintenance release until they've been tested for a while in a development
37 release.  Occasionally, we'll merge an urgent bugfix into the release branch
38 before it gets merged into maint, but that's rare.
40 If you're working on a bugfix for a bug that occurs in a particular version,
41 base your bugfix branch on the "maint" branch for the first supported series
42 that has that bug.  (As of June 2013, we're supporting 0.2.3 and later.) If
43 you're working on a new feature, base it on the master branch.
46 How we log changes
47 ------------------
49 When you do a commit that needs a ChangeLog entry, add a new file to
50 the "changes" toplevel subdirectory.  It should have the format of a
51 one-entry changelog section from the current ChangeLog file, as in
53   o Major bugfixes:
54     - Fix a potential buffer overflow. Fixes bug 99999; bugfix on
55       0.3.1.4-beta.
57 To write a changes file, first categorize the change.  Some common categories
58 are: Minor bugfixes, Major bugfixes, Minor features, Major features, Code
59 simplifications and refactoring.  Then say what the change does.  If
60 it's a bugfix, mention what bug it fixes and when the bug was
61 introduced.  To find out which Git tag the change was introduced in,
62 you can use "git describe --contains <sha1 of commit>".
64 If at all possible, try to create this file in the same commit where you are
65 making the change.  Please give it a distinctive name that no other branch will
66 use for the lifetime of your change. To verify the format of the changes file,
67 you can use "make check-changes".
69 When we go to make a release, we will concatenate all the entries
70 in changes to make a draft changelog, and clear the directory. We'll
71 then edit the draft changelog into a nice readable format.
73 What needs a changes file?::
74    A not-exhaustive list: Anything that might change user-visible
75    behavior. Anything that changes internals, documentation, or the build
76    system enough that somebody could notice.  Big or interesting code
77    rewrites.  Anything about which somebody might plausibly wonder "when
78    did that happen, and/or why did we do that" 6 months down the line.
80 Why use changes files instead of Git commit messages?::
81    Git commit messages are written for developers, not users, and they
82    are nigh-impossible to revise after the fact.
84 Why use changes files instead of entries in the ChangeLog?::
85    Having every single commit touch the ChangeLog file tended to create
86    zillions of merge conflicts.
88 Useful tools
89 ------------
91 These aren't strictly necessary for hacking on Tor, but they can help track
92 down bugs.
94 Jenkins
95 ~~~~~~~
97 https://jenkins.torproject.org
99 Dmalloc
100 ~~~~~~~
102 The dmalloc library will keep track of memory allocation, so you can find out
103 if we're leaking memory, doing any double-frees, or so on.
105   dmalloc -l ~/dmalloc.log
106   (run the commands it tells you)
107   ./configure --with-dmalloc
109 Valgrind
110 ~~~~~~~~
112 valgrind --leak-check=yes --error-limit=no --show-reachable=yes src/or/tor
114 (Note that if you get a zillion openssl warnings, you will also need to
115 pass --undef-value-errors=no to valgrind, or rebuild your openssl
116 with -DPURIFY.)
118 Coverity
119 ~~~~~~~~
121 Nick regularly runs the coverity static analyzer on the Tor codebase.
123 The preprocessor define __COVERITY__ is used to work around instances
124 where coverity picks up behavior that we wish to permit.
126 clang Static Analyzer
127 ~~~~~~~~~~~~~~~~~~~~~
129 The clang static analyzer can be run on the Tor codebase using Xcode (WIP)
130 or a command-line build.
132 The preprocessor define __clang_analyzer__ is used to work around instances
133 where clang picks up behavior that we wish to permit.
135 clang Runtime Sanitizers
136 ~~~~~~~~~~~~~~~~
138 To build the Tor codebase with the clang Address and Undefined Behavior
139 sanitizers, see the file contrib/clang/sanitize_blacklist.txt.
141 Preprocessor workarounds for instances where clang picks up behavior that
142 we wish to permit are also documented in the blacklist file.
144 Running lcov for unit test coverage
145 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
147 Lcov is a utility that generates pretty HTML reports of test code coverage.
148 To generate such a report:
150 -----
151    ./configure --enable-coverage
152    make
153    make coverage-html
154    $BROWSER ./coverage_html/index.html
155 -----
157 This will run the tor unit test suite `./src/test/test` and generate the HTML
158 coverage code report under the directory ./coverage_html/. To change the
159 output directory, use `make coverage-html HTML_COVER_DIR=./funky_new_cov_dir`.
161 Coverage diffs using lcov are not currently implemented, but are being
162 investigated (as of July 2014).
164 Running the unit tests
165 ~~~~~~~~~~~~~~~~~~~~~~
167 To quickly run all the tests distributed with Tor:
168 -----
169    make check
170 -----
172 To run the fast unit tests only:
173 -----
174    make test
175 -----
177 To selectively run just some tests (the following can be combined
178 arbitrarily):
179 -----
180    ./src/test/test <name_of_test> [<name of test 2>] ...
181    ./src/test/test <prefix_of_name_of_test>.. [<prefix_of_name_of_test2>..] ...
182    ./src/test/test :<name_of_excluded_test> [:<name_of_excluded_test2]...
183 -----
185 To run all tests, including those based on Stem or Chutney:
186 -----
187    make test-full
188 -----
190 To run all tests, including those basedd on Stem or Chutney that require a
191 working connection to the internet:
192 -----
193    make test-full-online
194 -----
196 Running gcov for unit test coverage
197 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
199 -----
200    ./configure --enable-coverage
201    make
202    make check
203    # or--- make test-full ? make test-full-online?
204    mkdir coverage-output
205    ./scripts/test/coverage coverage-output
206 -----
208 (On OSX, you'll need to start with "--enable-coverage CC=clang".)
210 Then, look at the .gcov files in coverage-output.  '-' before a line means
211 that the compiler generated no code for that line.  '######' means that the
212 line was never reached.  Lines with numbers were called that number of times.
214 If that doesn't work:
215    * Try configuring Tor with --disable-gcc-hardening
216    * You might need to run 'make clean' after you run './configure'.
218 If you make changes to Tor and want to get another set of coverage results,
219 you can run "make reset-gcov" to clear the intermediary gcov output.
221 If you have two different "coverage-output" directories, and you want to see
222 a meaningful diff between them, you can run:
224 -----
225    ./scripts/test/cov-diff coverage-output1 coverage-output2 | less
226 -----
228 In this diff, any lines that were visited at least once will have coverage
229 "1".  This lets you inspect what you (probably) really want to know: which
230 untested lines were changed?  Are there any new untested lines?
232 Running integration tests
233 ~~~~~~~~~~~~~~~~~~~~~~~~~
235 We have the beginnings of a set of scripts to run integration tests using
236 Chutney. To try them, set CHUTNEY_PATH to your chutney source directory, and
237 run "make test-network".
239 We also have scripts to run integration tests using Stem.  To try them, set
240 STEM_SOURCE_DIR to your Stem source directory, and run "test-stem".
242 Profiling Tor with oprofile
243 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
245 The oprofile tool runs (on Linux only!) to tell you what functions Tor is
246 spending its CPU time in, so we can identify berformance pottlenecks.
248 Here are some basic instructions
250  - Build tor with debugging symbols (you probably already have, unless
251    you messed with CFLAGS during the build process).
252  - Build all the libraries you care about with debugging symbols
253    (probably you only care about libssl, maybe zlib and Libevent).
254  - Copy this tor to a new directory
255  - Copy all the libraries it uses to that dir too (ldd ./tor will
256    tell you)
257  - Set LD_LIBRARY_PATH to include that dir.  ldd ./tor should now
258    show you it's using the libs in that dir
259  - Run that tor
260  - Reset oprofiles counters/start it
261    * "opcontrol --reset; opcontrol --start", if Nick remembers right.
262  - After a while, have it dump the stats on tor and all the libs
263    in that dir you created.
264    * "opcontrol --dump;"
265    * "opreport -l that_dir/*"
266  - Profit
268 Generating and analyzing a callgraph
269 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
271 1. Run ./scripts/maint/generate_callgraph.sh .  This will generate a
272    bunch of files in a new ./callgraph directory.
274 2. Run ./scripts/maint/analyze_callgraph.py callgraph/src/*/* .  This
275    will do a lot of graph operations and then dump out a new
276    "callgraph.pkl" file, containing data in Python's "pickle" format.
278 3. Run ./scripts/maint/display_callgraph.py .  It will display:
279     - the number of functions reachable from each function.
280     - all strongly-connnected components in the Tor callgraph
281     - the largest bottlenecks in the largest SCC in the Tor callgraph.
283 Note that currently the callgraph generator can't detect calls that pass
284 through function pointers.
286 Coding conventions
287 ------------------
289 Patch checklist
290 ~~~~~~~~~~~~~~~
292 If possible, send your patch as one of these (in descending order of
293 preference)
295    - A git branch we can pull from
296    - Patches generated by git format-patch
297    - A unified diff
299 Did you remember...
301    - To build your code while configured with --enable-gcc-warnings?
302    - To run "make check-spaces" on your code?
303    - To run "make check-docs" to see whether all new options are on
304      the manpage?
305    - To write unit tests, as possible?
306    - To base your code on the appropriate branch?
307    - To include a file in the "changes" directory as appropriate?
309 Whitespace and C conformance
310 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
312 Invoke "make check-spaces" from time to time, so it can tell you about
313 deviations from our C whitespace style.  Generally, we use:
315     - Unix-style line endings
316     - K&R-style indentation
317     - No space before newlines
318     - A blank line at the end of each file
319     - Never more than one blank line in a row
320     - Always spaces, never tabs
321     - No more than 79-columns per line.
322     - Two spaces per indent.
323     - A space between control keywords and their corresponding paren
324       "if (x)", "while (x)", and "switch (x)", never "if(x)", "while(x)", or
325       "switch(x)".
326     - A space between anything and an open brace.
327     - No space between a function name and an opening paren. "puts(x)", not
328       "puts (x)".
329     - Function declarations at the start of the line.
331 We try hard to build without warnings everywhere.  In particular, if you're
332 using gcc, you should invoke the configure script with the option
333 "--enable-gcc-warnings".  This will give a bunch of extra warning flags to
334 the compiler, and help us find divergences from our preferred C style.
336 Getting emacs to edit Tor source properly
337 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
339 Nick likes to put the following snippet in his .emacs file:
341 -----
342     (add-hook 'c-mode-hook
343           (lambda ()
344             (font-lock-mode 1)
345             (set-variable 'show-trailing-whitespace t)
347             (let ((fname (expand-file-name (buffer-file-name))))
348               (cond
349                ((string-match "^/home/nickm/src/libevent" fname)
350                 (set-variable 'indent-tabs-mode t)
351                 (set-variable 'c-basic-offset 4)
352                 (set-variable 'tab-width 4))
353                ((string-match "^/home/nickm/src/tor" fname)
354                 (set-variable 'indent-tabs-mode nil)
355                 (set-variable 'c-basic-offset 2))
356                ((string-match "^/home/nickm/src/openssl" fname)
357                 (set-variable 'indent-tabs-mode t)
358                 (set-variable 'c-basic-offset 8)
359                 (set-variable 'tab-width 8))
360             ))))
361 -----
363 You'll note that it defaults to showing all trailing whitespace.  The "cond"
364 test detects whether the file is one of a few C free software projects that I
365 often edit, and sets up the indentation level and tab preferences to match
366 what they want.
368 If you want to try this out, you'll need to change the filename regex
369 patterns to match where you keep your Tor files.
371 If you use emacs for editing Tor and nothing else, you could always just say:
373 -----
374    (add-hook 'c-mode-hook
375           (lambda ()
376             (font-lock-mode 1)
377             (set-variable 'show-trailing-whitespace t)
378             (set-variable 'indent-tabs-mode nil)
379             (set-variable 'c-basic-offset 2)))
380 -----
382 There is probably a better way to do this.  No, we are probably not going
383 to clutter the files with emacs stuff.
386 Functions to use
387 ~~~~~~~~~~~~~~~~
389 We have some wrapper functions like tor_malloc, tor_free, tor_strdup, and
390 tor_gettimeofday; use them instead of their generic equivalents.  (They
391 always succeed or exit.)
393 You can get a full list of the compatibility functions that Tor provides by
394 looking through src/common/util.h and src/common/compat.h.  You can see the
395 available containers in src/common/containers.h.  You should probably
396 familiarize yourself with these modules before you write too much code, or
397 else you'll wind up reinventing the wheel.
399 Use 'INLINE' instead of 'inline', so that we work properly on Windows.
401 Calling and naming conventions
402 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
404 Whenever possible, functions should return -1 on error and 0 on success.
406 For multi-word identifiers, use lowercase words combined with
407 underscores. (e.g., "multi_word_identifier").  Use ALL_CAPS for macros and
408 constants.
410 Typenames should end with "_t".
412 Function names should be prefixed with a module name or object name.  (In
413 general, code to manipulate an object should be a module with the same name
414 as the object, so it's hard to tell which convention is used.)
416 Functions that do things should have imperative-verb names
417 (e.g. buffer_clear, buffer_resize); functions that return booleans should
418 have predicate names (e.g. buffer_is_empty, buffer_needs_resizing).
420 If you find that you have four or more possible return code values, it's
421 probably time to create an enum.  If you find that you are passing three or
422 more flags to a function, it's probably time to create a flags argument that
423 takes a bitfield.
425 What To Optimize
426 ~~~~~~~~~~~~~~~~
428 Don't optimize anything if it's not in the critical path.  Right now, the
429 critical path seems to be AES, logging, and the network itself.  Feel free to
430 do your own profiling to determine otherwise.
432 Log conventions
433 ~~~~~~~~~~~~~~~
435 https://www.torproject.org/docs/faq#LogLevel
437 No error or warning messages should be expected during normal OR or OP
438 operation.
440 If a library function is currently called such that failure always means ERR,
441 then the library function should log WARN and let the caller log ERR.
443 Every message of severity INFO or higher should either (A) be intelligible
444 to end-users who don't know the Tor source; or (B) somehow inform the
445 end-users that they aren't expected to understand the message (perhaps
446 with a string like "internal error"). Option (A) is to be preferred to
447 option (B).
449 Doxygen
450 ~~~~~~~~
452 We use the 'doxygen' utility to generate documentation from our
453 source code. Here's how to use it:
455   1. Begin every file that should be documented with
456          /**
457           * \file filename.c
458           * \brief Short description of the file.
459           **/
461      (Doxygen will recognize any comment beginning with /** as special.)
463   2. Before any function, structure, #define, or variable you want to
464      document, add a comment of the form:
466         /** Describe the function's actions in imperative sentences.
467          *
468          * Use blank lines for paragraph breaks
469          *   - and
470          *   - hyphens
471          *   - for
472          *   - lists.
473          *
474          * Write <b>argument_names</b> in boldface.
475          *
476          * \code
477          *     place_example_code();
478          *     between_code_and_endcode_commands();
479          * \endcode
480          */
482   3. Make sure to escape the characters "<", ">", "\", "%" and "#" as "\<",
483      "\>", "\\", "\%", and "\#".
485   4. To document structure members, you can use two forms:
487        struct foo {
488          /** You can put the comment before an element; */
489          int a;
490          int b; /**< Or use the less-than symbol to put the comment
491                  * after the element. */
492        };
494   5. To generate documentation from the Tor source code, type:
496      $ doxygen -g
498      To generate a file called 'Doxyfile'.  Edit that file and run
499      'doxygen' to generate the API documentation.
501   6. See the Doxygen manual for more information; this summary just
502      scratches the surface.
504 Doxygen comment conventions
505 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
507 Say what functions do as a series of one or more imperative sentences, as
508 though you were telling somebody how to be the function.  In other words, DO
509 NOT say:
511      /** The strtol function parses a number.
512       *
513       * nptr -- the string to parse.  It can include whitespace.
514       * endptr -- a string pointer to hold the first thing that is not part
515       *    of the number, if present.
516       * base -- the numeric base.
517       * returns: the resulting number.
518       */
519      long strtol(const char *nptr, char **nptr, int base);
521 Instead, please DO say:
523      /** Parse a number in radix <b>base</b> from the string <b>nptr</b>,
524       * and return the result.  Skip all leading whitespace.  If
525       * <b>endptr</b> is not NULL, set *<b>endptr</b> to the first character
526       * after the number parsed.
527       **/
528      long strtol(const char *nptr, char **nptr, int base);
530 Doxygen comments are the contract in our abstraction-by-contract world: if
531 the functions that call your function rely on it doing something, then your
532 function should mention that it does that something in the documentation.  If
533 you rely on a function doing something beyond what is in its documentation,
534 then you should watch out, or it might do something else later.
536 Putting out a new release
537 -------------------------
539 Here are the steps Roger takes when putting out a new Tor release:
541 1) Use it for a while, as a client, as a relay, as a hidden service,
542 and as a directory authority. See if it has any obvious bugs, and
543 resolve those.
545 1.5) As applicable, merge the maint-X branch into the release-X branch.
547 2) Gather the changes/* files into a changelog entry, rewriting many
548 of them and reordering to focus on what users and funders would find
549 interesting and understandable.
551    2.1) Make sure that everything that wants a bug number has one.
552         Make sure that everything which is a bugfix says what version
553         it was a bugfix on.
554    2.2) Concatenate them.
555    2.3) Sort them by section. Within each section, sort by "version it's
556         a bugfix on", else by numerical ticket order.
558    2.4) Clean them up:
560    Standard idioms:
561      "Fixes bug 9999; bugfix on 0.3.3.3-alpha."
563    One space after a period.
565    Make stuff very terse
567    Make sure each section name ends with a colon
569    Describe the user-visible problem right away
571    Mention relevant config options by name.  If they're rare or unusual,
572    remind people what they're for
574    Avoid starting lines with open-paren
576    Present and imperative tense: not past.
578    'Relays', not 'servers' or 'nodes' or 'Tor relays'.
580    "Stop FOOing", not "Fix a bug where we would FOO".
582    Try not to let any given section be longer than about a page. Break up
583    long sections into subsections by some sort of common subtopic. This
584    guideline is especially important when organizing Release Notes for
585    new stable releases.
587    If a given changes stanza showed up in a different release (e.g.
588    maint-0.2.1), be sure to make the stanzas identical (so people can
589    distinguish if these are the same change).
591    2.5) Merge them in.
593    2.6) Clean everything one last time.
595    2.7) Run ./scripts/maint/format_changelog.py to make it prettier.
597 3) Compose a short release blurb to highlight the user-facing
598 changes. Insert said release blurb into the ChangeLog stanza. If it's
599 a stable release, add it to the ReleaseNotes file too. If we're adding
600 to a release-0.2.x branch, manually commit the changelogs to the later
601 git branches too.
603 4) In maint-0.2.x, bump the version number in configure.ac and run
604    scripts/maint/updateVersions.pl to update version numbers in other
605    places, and commit.  Then merge maint-0.2.x into release-0.2.x.
607    (NOTE: TO bump the version number, edit configure.ac, and then run
608    either make, or 'perl scripts/maint/updateVersions.pl', depending on
609    your version.)
611 5) Make dist, put the tarball up somewhere, and tell #tor about it. Wait
612 a while to see if anybody has problems building it. Try to get Sebastian
613 or somebody to try building it on Windows.
615 6) Get at least two of weasel/arma/sebastian to put the new version number
616 in their approved versions list.
618 7) Sign the tarball, then sign and push the git tag:
619   gpg -ba <the_tarball>
620   git tag -u <keyid> tor-0.2.x.y-status
621   git push origin tag tor-0.2.x.y-status
623 8a) scp the tarball and its sig to the dist website, i.e.
624 /srv/dist-master.torproject.org/htdocs/ on dist-master. When you want
625 it to go live, you run "static-update-component dist.torproject.org"
626 on dist-master.
628 8b) Edit "include/versions.wmi" and "Makefile" to note the new version.
630 9) Email the packagers (cc'ing tor-assistants) that a new tarball is up.
631    The current list of packagers is:
632        {weasel,gk,mikeperry} at torproject dot org
633        {blueness} at gentoo dot org
634        {paul} at invizbox dot io
635        {ondrej.mikle} at gmail dot com
636        {lfleischer} at archlinux dot org
638 10) Add the version number to Trac.  To do this, go to Trac, log in,
639 select "Admin" near the top of the screen, then select "Versions" from
640 the menu on the left.  At the right, there will be an "Add version"
641 box.  By convention, we enter the version in the form "Tor:
642 0.2.2.23-alpha" (or whatever the version is), and we select the date as
643 the date in the ChangeLog.
645 11) Forward-port the ChangeLog.
647 12) Wait up to a day or two (for a development release), or until most
648 packages are up (for a stable release), and mail the release blurb and
649 changelog to tor-talk or tor-announce.
651   (We might be moving to faster announcements, but don't announce until
652   the website is at least updated.)
654 13) If it's a stable release, bump the version number in the maint-x.y.z
655     branch to "newversion-dev", and do a "merge -s ours" merge to avoid
656     taking that change into master.  Do a similar 'merge -s theirs'
657     merge to get the change (and only that change) into release.  (Some
658     of the build scripts require that maint merge cleanly into release.)