tap-follow: fix memory leak
[metze/wireshark/wip.git] / doc / README.developer
1 This file is a HOWTO for Wireshark developers. It describes general development
2 and coding practices for contributing to Wireshark no matter which part of
3 Wireshark you want to work on.
4
5 To learn how to write a dissector, read this first, then read the file
6 README.dissector.
7
8 This file is compiled to give in depth information on Wireshark.
9 It is by no means all inclusive and complete. Please feel free to send
10 remarks and patches to the developer mailing list.
11
12 0. Prerequisites.
13
14 Before starting to develop a new dissector, a "running" Wireshark build
15 environment is required - there's no such thing as a standalone "dissector
16 build toolkit".
17
18 How to setup such an environment is platform dependent; detailed
19 information about these steps can be found in the "Developer's Guide"
20 (available from: https://www.wireshark.org) and in the INSTALL and
21 README.md files of the sources root dir.
22
23 0.1. General README files.
24
25 You'll find additional information in the following README files:
26
27 - README.capture        - the capture engine internals
28 - README.design         - Wireshark software design - incomplete
29 - README.developer      - this file
30 - README.dissector      - How to dissect a packet
31 - README.display_filter - Display Filter Engine
32 - README.idl2wrs        - CORBA IDL converter
33 - README.packaging      - how to distribute a software package containing WS
34 - README.regression     - regression testing of WS and TS
35 - README.stats_tree     - a tree statistics counting specific packets
36 - README.tapping        - "tap" a dissector to get protocol specific events
37 - README.xml-output     - how to work with the PDML exported output
38 - wiretap/README.developer - how to add additional capture file types to
39   Wiretap
40
41 0.2. Dissector related README files.
42
43 You'll find additional dissector related information in the file
44 README.dissector as well as the following README files:
45
46 - README.heuristic      - what are heuristic dissectors and how to write them
47 - README.plugins        - how to "pluginize" a dissector
48 - README.request_response_tracking - how to track req./resp. times and such
49 - README.wmem           - how to obtain "memory leak free" memory
50
51 0.3 Contributors
52
53 James Coe <jammer[AT]cin.net>
54 Gilbert Ramirez <gram[AT]alumni.rice.edu>
55 Jeff Foster <jfoste[AT]woodward.com>
56 Olivier Abad <oabad[AT]cybercable.fr>
57 Laurent Deniel <laurent.deniel[AT]free.fr>
58 Gerald Combs <gerald[AT]wireshark.org>
59 Guy Harris <guy[AT]alum.mit.edu>
60 Ulf Lamping <ulf.lamping[AT]web.de>
61
62 1. Portability.
63
64 Wireshark runs on many platforms, and can be compiled with a number of
65 different compilers; here are some rules for writing code that will work
66 on multiple platforms.
67
68 In general, not all C99 features can be used since some C compilers used to
69 compile Wireshark, such as Microsoft's C compiler, don't support all C99
70 features.  The C99 features that can be used are:
71
72  - flexible array members
73  - compound literals
74  - designated initializers
75  - "//" comments
76  - mixed declarations and code
77  - new block scopes for selection and iteration statements (that is, declaring
78    the type in a for-loop like: for (int i = 0; i < n; i++) ;)
79  - macros with a variable number of arguments (variadic macros)
80  - trailing comma in enum declarations
81  - inline functions (guaranteed only by use of glib.h)
82
83 Don't initialize global or static variables (variables with static
84 storage duration) in their declaration with non-constant values.  Not
85 all compilers support this.  E.g., if "i" is a static or global
86 variable, don't declare "i" as
87
88     guint32 i = somearray[2];
89
90 outside a function, or as
91
92     static guint32 i = somearray[2];
93
94 inside or outside a function, declare it as just
95
96     guint32 i;
97
98 or
99
100     static guint32 i;
101
102 and later, in code, initialize it with
103
104     i = somearray[2];
105
106 instead.  Initializations of variables with automatic storage duration -
107 i.e., local variables - with non-constant values is permitted, so,
108 within a function
109
110     guint32 i = somearray[2];
111
112 is allowed.
113
114 Don't use zero-length arrays as structure members, use flexible array members
115 instead.
116
117 Don't use anonymous unions; not all compilers support them.
118 Example:
119
120     typedef struct foo {
121       guint32 foo;
122       union {
123         guint32 foo_l;
124         guint16 foo_s;
125       } u;  /* have a name here */
126     } foo_t;
127
128 Don't use "uchar", "u_char", "ushort", "u_short", "uint", "u_int",
129 "ulong", "u_long" or "boolean"; they aren't defined on all platforms.
130 If you want an 8-bit unsigned quantity, use "guint8"; if you want an
131 8-bit character value with the 8th bit not interpreted as a sign bit,
132 use "guchar"; if you want a 16-bit unsigned quantity, use "guint16";
133 if you want a 32-bit unsigned quantity, use "guint32"; and if you want
134 an "int-sized" unsigned quantity, use "guint"; if you want a boolean,
135 use "gboolean".  Use "%d", "%u", "%x", and "%o" to print those types;
136 don't use "%ld", "%lu", "%lx", or "%lo", as longs are 64 bits long on
137 many platforms, but "guint32" is 32 bits long.
138
139 Don't use "long" to mean "signed 32-bit integer", and don't use
140 "unsigned long" to mean "unsigned 32-bit integer"; "long"s are 64 bits
141 long on many platforms.  Use "gint32" for signed 32-bit integers and use
142 "guint32" for unsigned 32-bit integers.
143
144 Don't use "long" to mean "signed 64-bit integer" and don't use "unsigned
145 long" to mean "unsigned 64-bit integer"; "long"s are 32 bits long on
146 many other platforms.  Don't use "long long" or "unsigned long long",
147 either, as not all platforms support them; use "gint64" or "guint64",
148 which will be defined as the appropriate types for 64-bit signed and
149 unsigned integers.
150
151 On LLP64 data model systems (notably 64-bit Windows), "int" and "long"
152 are 32 bits while "size_t" and "ptrdiff_t" are 64 bits. This means that
153 the following will generate a compiler warning:
154
155     int i;
156     i = strlen("hello, sailor");  /* Compiler warning */
157
158 Normally, you'd just make "i" a size_t. However, many GLib and Wireshark
159 functions won't accept a size_t on LLP64:
160
161     size_t i;
162     char greeting[] = "hello, sailor";
163     guint byte_after_greet;
164
165     i = strlen(greeting);
166     byte_after_greet = tvb_get_guint8(tvb, i); /* Compiler warning */
167
168 Try to use the appropriate data type when you can. When you can't, you
169 will have to cast to a compatible data type, e.g.
170
171     size_t i;
172     char greeting[] = "hello, sailor";
173     guint byte_after_greet;
174
175     i = strlen(greeting);
176     byte_after_greet = tvb_get_guint8(tvb, (gint) i); /* OK */
177
178 or
179
180     gint i;
181     char greeting[] = "hello, sailor";
182     guint byte_after_greet;
183
184     i = (gint) strlen(greeting);
185     byte_after_greet = tvb_get_guint8(tvb, i); /* OK */
186
187 See http://www.unix.org/version2/whatsnew/lp64_wp.html for more
188 information on the sizes of common types in different data models.
189
190 When printing or displaying the values of 64-bit integral data types,
191 don't use "%lld", "%llu", "%llx", or "%llo" - not all platforms
192 support "%ll" for printing 64-bit integral data types.  Instead, for
193 GLib routines, and routines that use them, such as all the routines in
194 Wireshark that take format arguments, use G_GINT64_MODIFIER, for example:
195
196     proto_tree_add_uint64_format_value(tree, hf_uint64, tvb, offset, len,
197                                        val, "%" G_GINT64_MODIFIER "u", val);
198
199 When specifying an integral constant that doesn't fit in 32 bits, don't
200 use "LL" at the end of the constant - not all compilers use "LL" for
201 that.  Instead, put the constant in a call to the "G_GINT64_CONSTANT()"
202 macro, e.g.
203
204     G_GINT64_CONSTANT(-11644473600), G_GUINT64_CONSTANT(11644473600)
205
206 rather than
207
208     -11644473600LL, 11644473600ULL
209
210 Don't assume that you can scan through a va_list initialized by va_start
211 more than once without closing it with va_end and re-initializing it with
212 va_start.  This applies even if you're not scanning through it yourself,
213 but are calling a routine that scans through it, such as vfprintf() or
214 one of the routines in Wireshark that takes a format and a va_list as an
215 argument.  You must do
216
217     va_start(ap, format);
218     call_routine1(xxx, format, ap);
219     va_end(ap);
220     va_start(ap, format);
221     call_routine2(xxx, format, ap);
222     va_end(ap);
223
224 rather
225     va_start(ap, format);
226     call_routine1(xxx, format, ap);
227     call_routine2(xxx, format, ap);
228     va_end(ap);
229
230 Don't use a label without a statement following it.  For example,
231 something such as
232
233     if (...) {
234
235         ...
236
237     done:
238     }
239
240 will not work with all compilers - you have to do
241
242     if (...) {
243
244         ...
245
246     done:
247         ;
248     }
249
250 with some statement, even if it's a null statement, after the label.
251
252 Don't use "bzero()", "bcopy()", or "bcmp()"; instead, use the ANSI C
253 routines
254
255     "memset()" (with zero as the second argument, so that it sets
256     all the bytes to zero);
257
258     "memcpy()" or "memmove()" (note that the first and second
259     arguments to "memcpy()" are in the reverse order to the
260     arguments to "bcopy()"; note also that "bcopy()" is typically
261     guaranteed to work on overlapping memory regions, while
262     "memcpy()" isn't, so if you may be copying from one region to a
263     region that overlaps it, use "memmove()", not "memcpy()" - but
264     "memcpy()" might be faster as a result of not guaranteeing
265     correct operation on overlapping memory regions);
266
267     and "memcmp()" (note that "memcmp()" returns 0, 1, or -1, doing
268     an ordered comparison, rather than just returning 0 for "equal"
269     and 1 for "not equal", as "bcmp()" does).
270
271 Not all platforms necessarily have "bzero()"/"bcopy()"/"bcmp()", and
272 those that do might not declare them in the header file on which they're
273 declared on your platform.
274
275 Don't use "index()" or "rindex()"; instead, use the ANSI C equivalents,
276 "strchr()" and "strrchr()".  Not all platforms necessarily have
277 "index()" or "rindex()", and those that do might not declare them in the
278 header file on which they're declared on your platform.
279
280 Don't use "tvb_get_ptr().  If you must use it, keep in mind that the pointer
281 returned by a call to "tvb_get_ptr()" is not guaranteed to be aligned on any
282 particular byte boundary; this means that you cannot safely cast it to any
283 data type other than a pointer to "char", unsigned char", "guint8", or other
284 one-byte data types.  Casting a pointer returned by tvb_get_ptr() into any
285 multi-byte data type or structure may cause crashes on some platforms (even
286 if it does not crash on x86-based PCs).  Even if such mis-aligned accesses
287 don't crash on your platform they will be slower than properly aligned
288 accesses would be.  Furthermore, the data in a packet is not necessarily in
289 the byte order of the machine on which Wireshark is running.  Use the tvbuff
290 routines to extract individual items from the packet, or, better yet, use
291 "proto_tree_add_item()" and let it extract the items for you.
292
293 Don't use structures that overlay packet data, or into which you copy
294 packet data; the C programming language does not guarantee any
295 particular alignment of fields within a structure, and even the
296 extensions that try to guarantee that are compiler-specific and not
297 necessarily supported by all compilers used to build Wireshark.  Using
298 bitfields in those structures is even worse; the order of bitfields
299 is not guaranteed.
300
301 Don't use "ntohs()", "ntohl()", "htons()", or "htonl()"; the header
302 files required to define or declare them differ between platforms, and
303 you might be able to get away with not including the appropriate header
304 file on your platform but that might not work on other platforms.
305 Instead, use "g_ntohs()", "g_ntohl()", "g_htons()", and "g_htonl()";
306 those are declared by <glib.h>, and you'll need to include that anyway,
307 as Wireshark header files that all dissectors must include use stuff from
308 <glib.h>.
309
310 Don't fetch a little-endian value using "tvb_get_ntohs() or
311 "tvb_get_ntohl()" and then using "g_ntohs()", "g_htons()", "g_ntohl()",
312 or "g_htonl()" on the resulting value - the g_ routines in question
313 convert between network byte order (big-endian) and *host* byte order,
314 not *little-endian* byte order; not all machines on which Wireshark runs
315 are little-endian, even though PCs are.  Fetch those values using
316 "tvb_get_letohs()" and "tvb_get_letohl()".
317
318 Do not use "open()", "rename()", "mkdir()", "stat()", "unlink()", "remove()",
319 "fopen()", "freopen()" directly.  Instead use "ws_open()", "ws_rename()",
320 "ws_mkdir()", "ws_stat()", "ws_unlink()", "ws_remove()", "ws_fopen()",
321 "ws_freopen()": these wrapper functions change the path and file name from
322 UTF8 to UTF16 on Windows allowing the functions to work correctly when the
323 path or file name contain non-ASCII characters.
324
325 Also, use ws_read(), ws_write(), ws_lseek(), ws_dup(), ws_fstat(), and
326 ws_fdopen(), rather than read(), write(), lseek(), dup(), fstat(), and
327 fdopen() on descriptors returned by ws_open().
328
329 Those functions are declared in <wsutil/file_util.h>; include that
330 header in any code that uses any of those routines.
331
332 When opening a file with "ws_fopen()", "ws_freopen()", or "ws_fdopen()", if
333 the file contains ASCII text, use "r", "w", "a", and so on as the open mode
334 - but if it contains binary data, use "rb", "wb", and so on.  On
335 Windows, if a file is opened in a text mode, writing a byte with the
336 value of octal 12 (newline) to the file causes two bytes, one with the
337 value octal 15 (carriage return) and one with the value octal 12, to be
338 written to the file, and causes bytes with the value octal 15 to be
339 discarded when reading the file (to translate between C's UNIX-style
340 lines that end with newline and Windows' DEC-style lines that end with
341 carriage return/line feed).
342
343 In addition, that also means that when opening or creating a binary
344 file, you must use "ws_open()" (with O_CREAT and possibly O_TRUNC if the
345 file is to be created if it doesn't exist), and OR in the O_BINARY flag,
346 even on UN*X - O_BINARY is defined by <wsutil/file_util.h> as 0 on UN*X.
347
348 Do not include <unistd.h>, <fcntl.h>, or <io.h> to declare any of the
349 routines listed as replaced by routines in <wsutil/file_util.h>;
350 instead, just include <wsutil/file_util.h>.
351
352 If you need the declarations of other functions defined by <unistd.h>,
353 don't include it without protecting it with
354
355     #ifdef HAVE_UNISTD_H
356
357         ...
358
359     #endif
360
361 Don't use forward declarations of static arrays without a specified size
362 in a fashion such as this:
363
364     static const value_string foo_vals[];
365
366         ...
367
368     static const value_string foo_vals[] = {
369         { 0,        "Red" },
370         { 1,        "Green" },
371         { 2,        "Blue" },
372         { 0,        NULL }
373     };
374
375 as some compilers will reject the first of those statements.  Instead,
376 initialize the array at the point at which it's first declared, so that
377 the size is known.
378
379 For #define names and enum member names, prefix the names with a tag so
380 as to avoid collisions with other names - this might be more of an issue
381 on Windows, as it appears to #define names such as DELETE and
382 OPTIONAL.
383
384 Don't use the "numbered argument" feature that many UNIX printf's
385 implement, e.g.:
386
387     g_snprintf(add_string, 30, " - (%1$d) (0x%1$04x)", value);
388
389 as not all UNIX printf's implement it, and Windows printf doesn't appear
390 to implement it.  Use something like
391
392     g_snprintf(add_string, 30, " - (%d) (0x%04x)", value, value);
393
394 instead.
395
396 Don't use
397
398     case N ... M:
399
400 as that's not supported by all compilers.
401
402 snprintf() -> g_snprintf()
403 snprintf() is not available on all platforms, so it's a good idea to use the
404 g_snprintf() function declared by <glib.h> instead.
405
406 tmpnam() -> mkstemp()
407 tmpnam is insecure and should not be used any more. Wireshark brings its
408 own mkstemp implementation for use on platforms that lack mkstemp.
409 Note: mkstemp does not accept NULL as a parameter.
410
411 Wireshark requires mininum versions of each of the libraries it uses, in
412 particular GLib 2.32.0 and Qt 5.2.0 or newer. If you require a mechanism
413 that is available only in a newer version of a library then use its
414 version detection macros, e.g. "#if GLIB_CHECK_VERSION(...)" and "#if
415 QT_VERSION_CHECK(...)" to conditionally compile code using that
416 mechanism.
417
418 When different code must be used on UN*X and Win32, use a #if or #ifdef
419 that tests _WIN32, not WIN32.  Try to write code portably whenever
420 possible, however; note that there are some routines in Wireshark with
421 platform-dependent implementations and platform-independent APIs, such
422 as the routines in epan/filesystem.c, allowing the code that calls it to
423 be written portably without #ifdefs.
424
425 Wireshark uses Libgcrypt as general-purpose crypto library. To use it from
426 your dissector, do not include gcrypt.h directly, but use the wrapper file
427 wsutil/wsgcrypt.h instead.
428
429 2. String handling
430
431 Do not use functions such as strcat() or strcpy().
432 A lot of work has been done to remove the existing calls to these functions and
433 we do not want any new callers of these functions.
434
435 Instead use g_snprintf() since that function will if used correctly prevent
436 buffer overflows for large strings.
437
438 Be sure that all pointers passed to %s specifiers in format strings are non-
439 NULL. Some implementations will automatically replace NULL pointers with the
440 string "(NULL)", but most will not.
441
442 When using a buffer to create a string, do not use a buffer stored on the stack.
443 I.e. do not use a buffer declared as
444
445    char buffer[1024];
446
447 instead allocate a buffer dynamically using the string-specific or plain wmem
448 routines (see README.wmem) such as
449
450    wmem_strbuf_t *strbuf;
451    strbuf = wmem_strbuf_new(wmem_packet_scope(), "");
452    wmem_strbuf_append_printf(strbuf, ...
453
454 or
455
456    char *buffer=NULL;
457    ...
458    #define MAX_BUFFER 1024
459    buffer=wmem_alloc(wmem_packet_scope(), MAX_BUFFER);
460    buffer[0]='\0';
461    ...
462    g_snprintf(buffer, MAX_BUFFER, ...
463
464 This avoids the stack from being corrupted in case there is a bug in your code
465 that accidentally writes beyond the end of the buffer.
466
467
468 If you write a routine that will create and return a pointer to a filled in
469 string and if that buffer will not be further processed or appended to after
470 the routine returns (except being added to the proto tree),
471 do not preallocate the buffer to fill in and pass as a parameter instead
472 pass a pointer to a pointer to the function and return a pointer to a
473 wmem-allocated buffer that will be automatically freed. (see README.wmem)
474
475 I.e. do not write code such as
476   static void
477   foo_to_str(char *string, ... ){
478      <fill in string>
479   }
480   ...
481      char buffer[1024];
482      ...
483      foo_to_str(buffer, ...
484      proto_tree_add_string(... buffer ...
485
486 instead write the code as
487   static void
488   foo_to_str(char **buffer, ...
489     #define MAX_BUFFER x
490     *buffer=wmem_alloc(wmem_packet_scope(), MAX_BUFFER);
491     <fill in *buffer>
492   }
493   ...
494     char *buffer;
495     ...
496     foo_to_str(&buffer, ...
497     proto_tree_add_string(... *buffer ...
498
499 Use wmem_ allocated buffers. They are very fast and nice. These buffers are all
500 automatically free()d when the dissection of the current packet ends so you
501 don't have to worry about free()ing them explicitly in order to not leak memory.
502 Please read README.wmem.
503
504 Don't use non-ASCII characters in source files; not all compiler
505 environments will be using the same encoding for non-ASCII characters,
506 and at least one compiler (Microsoft's Visual C) will, in environments
507 with double-byte character encodings, such as many Asian environments,
508 fail if it sees a byte sequence in a source file that doesn't correspond
509 to a valid character.  This causes source files using either an ISO
510 8859/n single-byte character encoding or UTF-8 to fail to compile.  Even
511 if the compiler doesn't fail, there is no guarantee that the compiler,
512 or a developer's text editor, will interpret the characters the way you
513 intend them to be interpreted.
514
515 3. Robustness.
516
517 Wireshark is not guaranteed to read only network traces that contain correctly-
518 formed packets. Wireshark is commonly used to track down networking
519 problems, and the problems might be due to a buggy protocol implementation
520 sending out bad packets.
521
522 Therefore, code does not only have to be able to handle
523 correctly-formed packets without, for example, crashing or looping
524 infinitely, they also have to be able to handle *incorrectly*-formed
525 packets without crashing or looping infinitely.
526
527 Here are some suggestions for making code more robust in the face
528 of incorrectly-formed packets:
529
530 Do *NOT* use "g_assert()" or "g_assert_not_reached()" in dissectors.
531 *NO* value in a packet's data should be considered "wrong" in the sense
532 that it's a problem with the dissector if found; if it cannot do
533 anything else with a particular value from a packet's data, the
534 dissector should put into the protocol tree an indication that the
535 value is invalid, and should return.  The "expert" mechanism should be
536 used for that purpose.
537
538 If there is a case where you are checking not for an invalid data item
539 in the packet, but for a bug in the dissector (for example, an
540 assumption being made at a particular point in the code about the
541 internal state of the dissector), use the DISSECTOR_ASSERT macro for
542 that purpose; this will put into the protocol tree an indication that
543 the dissector has a bug in it, and will not crash the application.
544
545 If you are allocating a chunk of memory to contain data from a packet,
546 or to contain information derived from data in a packet, and the size of
547 the chunk of memory is derived from a size field in the packet, make
548 sure all the data is present in the packet before allocating the buffer.
549 Doing so means that:
550
551     1) Wireshark won't leak that chunk of memory if an attempt to
552        fetch data not present in the packet throws an exception.
553
554 and
555
556     2) it won't crash trying to allocate an absurdly-large chunk of
557        memory if the size field has a bogus large value.
558
559 If you're fetching into such a chunk of memory a string from the buffer,
560 and the string has a specified size, you can use "tvb_get_*_string()",
561 which will check whether the entire string is present before allocating
562 a buffer for the string, and will also put a trailing '\0' at the end of
563 the buffer.
564
565 If you're fetching into such a chunk of memory a 2-byte Unicode string
566 from the buffer, and the string has a specified size, you can use
567 "tvb_get_faked_unicode()", which will check whether the entire string
568 is present before allocating a buffer for the string, and will also
569 put a trailing '\0' at the end of the buffer.  The resulting string will be
570 a sequence of single-byte characters; the only Unicode characters that
571 will be handled correctly are those in the ASCII range.  (Wireshark's
572 ability to handle non-ASCII strings is limited; it needs to be
573 improved.)
574
575 If you're fetching into such a chunk of memory a sequence of bytes from
576 the buffer, and the sequence has a specified size, you can use
577 "tvb_memdup()", which will check whether the entire sequence is present
578 before allocating a buffer for it.
579
580 Otherwise, you can check whether the data is present by using
581 "tvb_ensure_bytes_exist()" although this frequently is not needed: the
582 TVB-accessor routines can handle requests to read data beyond the end of
583 the TVB (by throwing an exception which will either mark the frame as
584 truncated--not all the data was captured--or as malformed).
585
586 Note also that you should only fetch string data into a fixed-length
587 buffer if the code ensures that no more bytes than will fit into the
588 buffer are fetched ("the protocol ensures" isn't good enough, as
589 protocol specifications can't ensure only packets that conform to the
590 specification will be transmitted or that only packets for the protocol
591 in question will be interpreted as packets for that protocol by
592 Wireshark).  If there's no maximum length of string data to be fetched,
593 routines such as "tvb_get_*_string()" are safer, as they allocate a buffer
594 large enough to hold the string.  (Note that some variants of this call
595 require you to free the string once you're finished with it.)
596
597 If you have gotten a pointer using "tvb_get_ptr()" (which you should not
598 have: you should seriously consider a better alternative to this function),
599 you must make sure that you do not refer to any data past the length passed
600 as the last argument to "tvb_get_ptr()"; while the various "tvb_get"
601 routines perform bounds checking and throw an exception if you refer to data
602 not available in the tvbuff, direct references through a pointer gotten from
603 "tvb_get_ptr()" do not do any bounds checking.
604
605 If you have a loop that dissects a sequence of items, each of which has
606 a length field, with the offset in the tvbuff advanced by the length of
607 the item, then, if the length field is the total length of the item, and
608 thus can be zero, you *MUST* check for a zero-length item and abort the
609 loop if you see one.  Otherwise, a zero-length item could cause the
610 dissector to loop infinitely.  You should also check that the offset,
611 after having the length added to it, is greater than the offset before
612 the length was added to it, if the length field is greater than 24 bits
613 long, so that, if the length value is *very* large and adding it to the
614 offset causes an overflow, that overflow is detected.
615
616 If you have a
617
618     for (i = {start}; i < {end}; i++)
619
620 loop, make sure that the type of the loop index variable is large enough
621 to hold the maximum {end} value plus 1; otherwise, the loop index
622 variable can overflow before it ever reaches its maximum value.  In
623 particular, be very careful when using gint8, guint8, gint16, or guint16
624 variables as loop indices; you almost always want to use an "int"/"gint"
625 or "unsigned int"/"guint" as the loop index rather than a shorter type.
626
627 If you are fetching a length field from the buffer, corresponding to the
628 length of a portion of the packet, and subtracting from that length a
629 value corresponding to the length of, for example, a header in the
630 packet portion in question, *ALWAYS* check that the value of the length
631 field is greater than or equal to the length you're subtracting from it,
632 and report an error in the packet and stop dissecting the packet if it's
633 less than the length you're subtracting from it.  Otherwise, the
634 resulting length value will be negative, which will either cause errors
635 in the dissector or routines called by the dissector, or, if the value
636 is interpreted as an unsigned integer, will cause the value to be
637 interpreted as a very large positive value.
638
639 Any tvbuff offset that is added to as processing is done on a packet
640 should be stored in a 32-bit variable, such as an "int"; if you store it
641 in an 8-bit or 16-bit variable, you run the risk of the variable
642 overflowing.
643
644 sprintf() -> g_snprintf()
645 Prevent yourself from using the sprintf() function, as it does not test the
646 length of the given output buffer and might be writing into unintended memory
647 areas. This function is one of the main causes of security problems like buffer
648 exploits and many other bugs that are very hard to find. It's much better to
649 use the g_snprintf() function declared by <glib.h> instead.
650
651 You should test your dissector against incorrectly-formed packets.  This
652 can be done using the randpkt and editcap utilities that come with the
653 Wireshark distribution.  Testing using randpkt can be done by generating
654 output at the same layer as your protocol, and forcing Wireshark/TShark
655 to decode it as your protocol, e.g. if your protocol sits on top of UDP:
656
657     randpkt -c 50000 -t dns randpkt.pcap
658     tshark -nVr randpkt.pcap -d udp.port==53,<myproto>
659
660 Testing using editcap can be done using preexisting capture files and the
661 "-E" flag, which introduces errors in a capture file.  E.g.:
662
663     editcap -E 0.03 infile.pcap outfile.pcap
664     tshark -nVr outfile.pcap
665
666 The script fuzz-test.sh is available to help automate these tests.
667
668 4. Name convention.
669
670 Wireshark uses the underscore_convention rather than the InterCapConvention for
671 function names, so new code should probably use underscores rather than
672 intercaps for functions and variable names. This is especially important if you
673 are writing code that will be called from outside your code.  We are just
674 trying to keep things consistent for other developers.
675
676 C symbols exported from libraries shipped with Wireshark should start with a
677 prefix that helps avoiding name collision with public symbols from other shared
678 libraries. The current suggested prefixes for newly added symbols are
679 ws_, wslua_, wmem_ and wtap_.
680
681 5. White space convention.
682
683 Please avoid using tab expansions different from 8 column widths, as not all
684 text editors in use by the developers support this. For a detailed
685 discussion of tabs, spaces, and indentation, see
686
687     http://www.jwz.org/doc/tabs-vs-spaces.html
688
689 Most of the files in Wireshark tend to use 2-space or 4-space indentation. When
690 creating a new file you are free to choose an indentation logic but you are
691 encouraged to use 4-space indentation for C/C++ source to keep inconsistency
692 between files to a minimum.
693
694 Each file should have a short comment (modelines) on the indentation logic at
695 the end of the file. See
696
697     https://www.wireshark.org/tools/modelines.html
698
699 for guidance.
700
701 A complementary and arguably better alternative to modelines is
702 EditorConfig (http://editorconfig.org). The default EditorConfig indentation
703 style is defined in the .editorconfig file placed on the root of the project
704 source code tree (4-space indentation for C). One advantage of following the
705 default style is that no additional EditorConfig settings are required for new
706 files. If your file does not follow this style please add a file-specific
707 setting overriding the default style to a separate .editorconfig configuration
708 file placed in the source file directory.
709
710 Some IDEs and text editors have built-in EditorConfig support and many more
711 have plugins available (links at http://editorconfig.org).
712
713 Please do not leave trailing whitespace (spaces/tabs) on lines.
714
715 When editing an existing file, try following the existing indentation
716 logic and even if it very tempting, never ever use a restyler/reindenter
717 utility on an existing file.  If you run across wildly varying
718 indentation styles within the same file, it might be helpful to send a
719 note to wireshark-dev for guidance.
720
721 6. Compiler warnings
722
723 You should write code that is free of compiler warnings. Such warnings will
724 often indicate questionable code and sometimes even real bugs, so it's best
725 to avoid warnings at all.
726
727 The compiler flags in the Makefiles are set to "treat warnings as errors",
728 so your code won't even compile when warnings occur.
729
730 7. Miscellaneous notes
731
732 Each commit in your branch corresponds to a different VCSVERSION string
733 automatically defined in the header 'version.h' during the build. If you happen
734 to find it convenient to disable this feature it can be done using:
735
736     touch .git/wireshark-disable-versioning
737
738 i.e., the file 'wireshark-disable-versioning' must exist in the git repo dir.
739
740 /*
741  * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
742  *
743  * Local variables:
744  * c-basic-offset: 4
745  * tab-width: 8
746  * indent-tabs-mode: nil
747  * End:
748  *
749  * vi: set shiftwidth=4 tabstop=8 expandtab:
750  * :indentSize=4:tabSize=8:noTabs=true:
751  */