The SILC Project

source navigation ]
identifier search ]
freetext search ]
file search ]

silc/doc/CodingStyle

  1 Coding Style in SILC source tree
  2 ================================
  3 
  4 This document describes the coding style and coding conventions used
  5 in the SILC source tree.  The purpose of the document is to describe the
  6 common way to program for SILC and thus should be learned when programming
  7 new code.  The document describes various conventions regarding variable
  8 naming, function naming, indentation, overall appearance of a piece of
  9 code and how some of the technical issues has been done in the SILC and
 10 should be done in the future.
 11 
 12 
 13 Naming
 14 ======
 15 
 16 Generic naming
 17 
 18 All identifiers, whether they are defines, functions or something else, with
 19 exception of variables, has a common naming convention.  Usually all
 20 identifiers use `silc' prefix to indicate that the identifier is part of
 21 SILC distribution.  For example, silc_server_init(), SILC_PACKET_TYPE_ERROR,
 22 etc.  As mentioned however, variables, local or global, does not use this
 23 naming convention.
 24 
 25 Lower level routines, usually some library routines, may use their
 26 own naming convention if generic API is defined over them.  The API uses
 27 the common naming convention while the lower level routines uses what
 28 ever they want.  For example, ciphers are implemented currently in this
 29 way.  They define common SILC Cipher API but the actual implementation
 30 of algorithms uses their own naming convention.  Another example is
 31 the MPI math library that uses its own function naming but we have our
 32 own SILC MP API over it that has been defined using common SILC naming
 33 convention.
 34 
 35 
 36 Variables
 37 
 38 Variable names are always in lowercase and any mixed-case or totally
 39 uppercase variable names should be avoided.  Variable names may include
 40 underscore if it is necessary.  For example, `unsigned char *id_string;'.
 41 
 42 The same name convention is used in structure field names.  All fields
 43 in structures should be in lowercase.  Global variables should have some
 44 sort of prefix to indicate that the variable is global.  Although, global
 45 variables should be avoided if possible.
 46 
 47 Local variable names should be as short as possible without losing
 48 meaning of the name.  For example there is no reason to call loop
 49 counter as `loop_counter' when `i' is commonly used instead.  Using
 50 variable name `tmp' is also ok and should be used when some temporary
 51 value is used.
 52 
 53 
 54 #define's and Macros
 55 
 56 All #define's should always be in uppercase to indicate that it is
 57 a define, for example, `#define SILC_PACKET_TYPE_NONE 0'.  As mentioned
 58 previously #define's and macros always use the `SILC' prefix.  The
 59 names also uses always underscores.
 60 
 61 Names of #define's and macros should be self explanatory.  This may
 62 lead to long names but it is better than having some `#define SILC_KE1_SX'
 63 which does not tell you anything.
 64 
 65 
 66 Type definitions
 67 
 68 Type definitions (typedefs) uses some what different naming convention
 69 from variables and macros.  Typedefs has mixed-case names and they
 70 never use underscores.  For example, `SilcSomeStruct', `SilcServerObject'.
 71 Like in any other case the names should be self explanatory which may
 72 lead to long names but that is not a problem.
 73 
 74 The names should tell what the typedef is about.  If it is a typedef
 75 of a structure it should tell what the structure is for in the first
 76 place.  For example `SilcClientStruct', `SilcCipherObject', 
 77 `SilcConfigSection´, etc.
 78 
 79 
 80 Structures
 81 
 82 Same naming convention used in typedefs applies to names of structures as
 83 well.  Same as with typedef, structure names should be self explanatory
 84 and should tell what the structure is made for.
 85 
 86 Structures are used a lot in SILC.  They are used as simple structures
 87 and as objects as well.  When normal structures are needed they are
 88 defined as follows,
 89 
 90         struct SilcDummyStruct {
 91           unsigned char *dummy;
 92         };
 93 
 94 And used as `struct SilcDummyStruct *dummy'.  However, this is quite
 95 rarely used in the SILC, instead structures are typedef'd as following
 96 later.  When structure is used as object they are defined as follows,
 97 
 98         typedef struct SilcDummyObject {
 99           unsigned char *dummy;
100           unsigned int flags;
101           void (*callback)(void *, unsigned int);
102         } SilcDummyStruct;
103 
104 If the SilcDummyObject is not needed it may be omitted (which is very
105 common in SILC code), leaving,
106 
107         typedef struct {
108           unsigned char *dummy;
109           unsigned int flags;
110           void (*callback)(void *, unsigned int);
111         } SilcDummyStruct;
112 
113 Finally, it is common that structures are typedef'd pointers as they
114 are very flexible to use,
115 
116         typedef SilcDummyStruct *SilcDummy;
117 
118 or,
119 
120         typedef struct {
121           unsigned char *dummy;
122           unsigned int flags;
123           void (*callback)(void *, unsigned int);
124         } SilcDummyStruct, *SilcDummy;
125 
126 It is common in SILC to typedef structures instead of defining name
127 for the structure.  In this case the structure may be used without
128 defining `struct' to the code, For example,
129 
130         SilcDummyStruct dummy_obj;
131         SilcDummyStruct *dummy;
132 
133 If the structure has a pointer typedef then they are defined as normal
134 variables but for real they are pointers, For example,
135 
136         SilcDummy dummy;
137         dummy = silc_calloc(1, sizeof(*dummy));
138         dummy->flags = SILC_DUMMY_EMPTY;
139 
140 This convention is very common in SILC code and has been used consistently
141 throughout the code.  The pattern here is that all structures are named
142 as `SilcXxxStruct', all objects are named as `SilcXxxObject' and when
143 they are typedef'd pointers they are named as `SilcXxx'.
144 
145 
146 Functions
147 
148 Function naming uses the common naming convention used in the SILC.  All
149 functions are always lowercase and they use underscores.  The name of
150 the function always starts with prefix `silc_'.  The name of the function
151 should be self explanatory which may lead to long names.  The name of
152 a function is constructed from following parts,
153 
154         silc_<application>_<module>_<function>
155 
156 The <application> is for example <client> or <server>, however, it is
157 always omitted (and must be omitted) when programming library code.
158 
159 The <module> is the module you are programming currently.  You should
160 have a pretty good idea what you are programming and what the module
161 does.  For example, <cipher>, <config>, <command>, <packet>, etc.
162 
163 The <function> is the description of the functionality of the function
164 you are writing.  Naturally it should be self explanatory and weird
165 short names should be avoided.  It is better to have long function
166 names than some odd name that does not tell what it is about.  Function
167 naming could be for example, <read>, <new_id>, <register>, <find_by_name>,
168 etc.
169 
170 So, it is common in SILC to have function names, such as,
171 
172         silc_server_packet_send
173         silc_server_packet_send_to_channel
174         silc_client_packet_process
175         silc_idcache_del_by_id
176         silc_task_unregister_by_fd
177         silc_protocol_excute_final
178         silc_buffer_alloc
179 
180 When function registers something the name of the function should
181 generally be `silc_function_register' and unregistering should happen
182 with `silc_function_unregister'.  When function allocates something it
183 should be called `silc_function_alloc' and when freeing it should be
184 called `silc_function_free'.  Respectively, with init/uninit functions.
185 
186 When this naming convention is used consistently it is easy to remember
187 what the name of the function is.  For example, if you need buffer it
188 is easy to figure out that the routines are most likely called
189 `silc_buffer_*',  and if you need to allocate buffer it is most likely
190 called `silc_buffer_alloc'.  This sort of naming makes the programming,
191 in the long run, much cleaner, simpler and faster.
192 
193 
194 Inline functions
195 
196 SILC uses quite a bit inline functions to optimize the code.  The
197 naming of inline functions must follow same convention as any normal
198 function.  All inline functions in SILC are defined and written into
199 header files.  Inline functions must be defined in following manner
200 in the header file,
201 
202 static inline void silc_dummy_inline(unsigned int flags)
203 {
204   doing_little_dummy_things;
205 }
206 
207 
208 Indentation
209 ===========
210 
211 SILC has been coded with Emacs so standard indentation of Emacs is used
212 in the SILC code.  The indentation is always 2 characters, not a
213 tabulator.  If you use Emacs then this should not be a problem.  So,
214 if you code for SILC be sure to format the code to the standard way
215 used in the SILC before submitting the code.
216 
217 A tip for those who think that these long function names etc are just
218 too long to type, consider using dynamic abbreviation found in Emacs.
219 With this cool feature you only have type some part of the string and
220 then use the dabbrev to find the rest of the string.  I guess, by
221 default it is M-/ in Emacs but I have bound it into Shift-TAB so it
222 is fast to use when typing.
223 
224 
225 Placing Braces
226 ==============
227 
228 The common fight about how the braces should be placed in the C code
229 is probably going on in the SILC code as well.  However, SILC code
230 is consistent about this.  The placing uses K&R style thus the opening
231 of the brace is put to the last on the line and the closing brace is
232 on first on its own line,
233 
234         if (condition) {
235           silc_something();
236           silc_something_more();
237         }
238 
239 The function's braces are as follows,
240 
241         int silc_client_function()
242         {
243           return 0;
244         }
245 
246 More examples,
247 
248         if (condition) {
249           something;
250           silc_something_more();
251         } else {
252           something_else;
253         }
254 
255         if (condition) {
256           something;
257           silc_something_more();
258         } else if (other_condition) {
259           something;
260           silc_something_more();
261         } else {
262           something_else;
263         }
264 
265         if (condition)
266           oneline_no_braces;
267 
268 
269 Commenting
270 ==========
271 
272 SILC code is usually pretty well commented and this should be the way
273 in the future as well.  However, the comments should not tell how the
274 code works, it should be apparent by looking at the code.  Instead the
275 commenting should tell what the function does.  All functions should
276 be commented.  If nothing more a line of comment telling what the function
277 is about helps a lot when you go back to it after six months.  Static
278 functions should be commented as well.
279 
280 When writing a new header it is preferred that the header file is
281 immediately written in the ROBOdoc documentation format.  This is
282 important when you are doing library code under lib/.  There are plenty
283 of examples of this format.  The ROBOdoc is used automatically generate
284 the Toolkit documentation.
285 
286 Comments should use normal C-language comments /* */ and not C++ comments.
287 
288 
289 General Appearance
290 ==================
291 
292 The code should be clean and good to eye, although the function of it
293 must always supersede the appearance.  However, it is nice to read code
294 that looks good.  Here are some issues on general appearance.
295 
296         o Use empty lines when appropriate but not too much.  There
297           should not be excess empty lines at the end of file.  However,
298           using some empty lines in the code makes the code better
299           looking.
300 
301         o The line is 79 characters long and not one character longer.
302           Longer lines must be cut in two, or three, or ...
303 
304         o Use spaces very much.  Do not write things like `if(!k)',
305           instead write `if (!k)'.  Same with `for', `while', etc.
306           Spaces should be put around all binary operators like `*',
307           `==', `+', etc.  Also, when setting a value to variable be
308           sure to set spaces around `='.  When writing argument list
309           to a function, space should follow each of the comma in the
310           list.  However, do not use spaces within parenthesis, for
311           example, `if ( !k )' is not accepted.
312 
313         o If you are not sure about how something should be done or
314           the code you've done is not finished, it should be commented
315           with XXX plus explanation what is going on.  For example,
316           /* XXX hmm... how is this flushed? */
317 
318 
319 Source Files
320 
321 All source files starts with header that includes the name of the author,
322 copyright notice and the copyright policy, usually part of GNU GPL licence.
323 Now, this really isn't that important but some sort of header should be in
324 all source files.
325 
326 In the start of the source files should include the #include's that are
327 needed.  All library source files must include `silc.h', this is
328 a must.  Client source file must include at least `silcclient.h' and
329 server source file must include `silcserver.h'.  Additional include's
330 may be added as well, however, system specific includes should not be
331 added directly (unless it is really a special case).  Go see any source
332 file as an example.
333 
334 
335 Header Files
336 
337 As with source files, header files should include same file header at
338 the start of the file.
339 
340 Header files are usually divided in three parts in SILC.  At the start
341 of header files should include all definitions, typedefs, structure
342 definitions etc.  After definitions should include macros and inline
343 functions if any of those exist.  After macros should include the
344 public prototypes of the functions.  Go see any header file as an example.
345 
346 
347 Using gotos
348 ===========
349 
350 Gotos are used in the SILC code quite often.  If you know how to use
351 goto's properly then it is ok to use them for example to optimize the
352 code.  If you use goto's then use them only to make forward jumps, try
353 to avoid backward jumps at all cost.  If you don't know how to use goto's
354 do not use them.
355 
356 
357 Debug Messages
358 ==============
359 
360 When writing new code it is recommended that the code produces some sort
361 of debug messages.  SILC has own debug logging system that must be used
362 in the generic SILC code.  Few macros exist,
363 
364         SILC_LOG_DEBUG
365         SILC_LOG_HEXDUMP
366         SILC_LOG_INFO
367         SILC_LOG_WARNING
368         SILC_LOG_ERROR
369         SILC_LOG_FATAL
370 
371 When doing debugging the most used macros are SILC_LOG_DEBUG and
372 SILC_LOG_HEXDUMP.  With first macro you can print out any sort of debug
373 messages with variable argument list, for example,
374 
375         SILC_LOG_DEBUG(("Start"));
376         SILC_LOG_DEBUG(("Packet length %d", packet_len));
377 
378 Note the extra parenthesis that are required for the macro so that the
379 variable argument list formatting would work correctly.
380 
381 When you need to dump some data into screen you should use SILC_LOG_HEXDUMP
382 macro.  For example,
383 
384         SILC_LOG_HEXDUMP(("Packet"), packet->data, packet->len);
385         SILC_LOG_HEXDUMP(("Packet, size %d", size), packet->data, packet->len);
386 
387 In SILC_LOG_HEXDUMP the data to be dumped are set between the second last
388 and last parenthesis in order that the data is first and the length of the
389 data is next.  If arguments are used they are used the same way as in
390 SILC_LOG_DEBUG and the data to be dumped are set after the argument list
391 is closed with the parenthesis.
392 
393 
394 Memory Allocation
395 =================
396 
397 Naturally, memory allocation is a big part of SILC.  However, there are
398 few things that must be noted on the issue.  SILC has defined its own
399 memory allocation functions that must be used.  System specific functions
400 must not be used directly.  There are functions like,
401 
402         silc_malloc
403         silc_calloc
404         silc_realloc
405         silc_free
406 
407 You should always use silc_calloc instead of silc_malloc because
408 silc_calloc automatically zeroes the allocated memory area.  This is
409 important especially with structures because generally we want that all
410 fields, by default, are zero.
411 
412 So, instead of doing
413 
414         SilcStruct *ptr;
415 
416         ptr = silc_malloc(sizeof(*ptr));
417 
418 You should do
419 
420         SilcStruct *ptr
421 
422         ptr = silc_calloc(1, sizeof(*ptr));
423 
424 
425 When freeing memory it should be zero'ed when appropriate.  All memory
426 allocations that handle sensitive data such as keys should be zero'ed
427 by memset() before freeing the memory.  Common way to do is,
428 
429         memset(ptr, 'F', sizeof(*ptr));
430         silc_free(ptr);
431 
432 Where 'F' indicates free'd memory if you'd ever check it with debugger.
433 Other choice is to use 0 instead of 'F'.  The pointer after freeing
434 should be set to NULL if appropriate, ptr = NULL.
435 
436 Note that some functions in the SILC library handles the zeroing of
437 the memory area automatically, like for example, silc_buffer_free.
438 
439 Also note that all allocation routines assert()'s if the memory allocation
440 fails, ie. system does not have free memory.
441 
442 
443 Callback Programming
444 ====================
445 
446 SILC uses pretty much programming convention called callback programming.
447 This is a programming style that extensively uses function pointers
448 which are usually called inside some other function.
449 
450 Typical scenario is this;  You are performing some task that most likely
451 is asynchronous.  You need to be able get some structure context when
452 the operation finishes.  Most common way in this case is to pass the
453 structure context to the operation function with a callback function
454 that is called when the operation has finished.  Following code explains
455 probaly better.
456 
457 
458 /* Prototypes */
459 static silc_callback(void *context);
460 void silc_start();
461 void silc_async_operation_register(int fd, SilcAsyncCb callback, 
462                                    void *context);
463 void silc_async_operation(int fd, SilcAsyncCb callback, void *context);
464 
465 /* Type definition of the callback function */
466 typedef (*SilcAsyncCb)(void *context);
467 
468 /* Registers async operation and passes callback function and context
469    to it as arguments. */
470 
471 void silc_start()
472 {
473   SilcDummyStruct *ctx;
474 
475   ctx = silc_calloc(1, sizeof(*ctx));
476   ctx->fd = 30;
477 
478   silc_async_operation_register(30, silc_callback, (void *)ctx);
479 }
480 
481 /* The callblack function that is called from the operation function */
482 
483 static void silc_callback(void *context)
484 {
485   SilcDummyStruct *ctx = (SilcDummyStruct *)context;
486 
487   ctx->fd = 10;
488 }
489 
490 /* Register async operation */
491 
492 void silc_async_operation_register(int fd, SilcAsyncCb callback,
493                                    void *context)
494 {
495   /* Register and return immediately */
496   silc_register_async_operation_internal(fd, callback, context);
497 }
498 
499 /* Operation function that will call the callback function after it
500    has finished. */
501 
502 void silc_async_operation(int fd, SilcAsyncCb callback, void *context)
503 {
504   here_this_function_does_what_ever_it_wants;
505 
506   here_something_more;
507 
508   /* We are finished, call the callback */
509   if (callback)
510     (*callback)(context);
511 }
512 
513 
514 Now, after the registeration of the async operation in this dumb example
515 the silc_start returns immediately.  Lets say, 10 seconds later the
516 async operation is executed (it would have been better to call it just
517 timeout) by calling silc_async_operation which on the other hand will
518 call the callback function after it has finished.  The context that
519 was passed to the registeration function is now passed back to the
520 callback function.  Thus, you will get the context you wanted.  This is
521 the typical scenario where callback functions come in very handy.  This
522 is also the best way to pass context's that are needed later without
523 making them global context's.  And as long as the context's are defined
524 as void * they can be what ever contexts making the functions, that
525 takes in the context, generic.  Like in above example, you could pass
526 what ever context to the registeration function if you'd want to.
527 
528 Callback programming is also used when making generic API's of some
529 operation.  For example, if you want generic hooks to the API so that
530 something could be done while doing the operation (maybe to collect
531 statistics or something else) just get the functions accept a callback
532 function and context and call them when appropriate, then continue
533 as normally.
534 
535 Callback functions has been used a lot in SILC code.  The scheduler
536 and task system implemented in core library uses extensively callback
537 functions.  Timeout's uses callbacks as well.  SILC Key Exchange protocol
538 uses callback functions too.  The callback function in SKE provides
539 packet sending without defining into the SKE code how the packets
540 should be sent thus making it generic for both client and server
541 (and actually to any application for that matter).
542 
543 There are some technical issues on callback programming that are
544 common in SILC code.
545 
546         o Callback functions are usually defined as void functions
547           as the routine that calls them usually don't care about
548           what the callback function does.  Many times it doesn't
549           actually know what it does nor would it be interested to
550           know that.  It doesn't care about return values.
551 
552         o Many times the callback functions are static functions
553           because they are not wanted to be called in anyway else
554           than as callback functions.
555 
556         o Callback function names usually have the `_cb' or `_callback'
557           at the end of function name, eg. silc_client_cb.
558 
559         o Type of callback functions should be typedef'd instead of
560           defining them directly to the function.  See above example.
561           This makes the code much cleaner.
562 
563         o Callback function types has usually the suffix `Cb' or
564           ´Callback' in the type name, eg. SilcAsyncCallback.
565 
566         o You must explicitly cast the void * context's to correct
567           type in the callback function.  Of course you must be careful
568           to cast them to the correct type as they are void * they
569           could be anything.  Many times this causes problems when you
570           forget what was the type you passed to it.  Callback
571           programming may get very complex.
572 
573         o You cannot use inline functions as callback functions,
574           naturally.
575 
576 Callback programming may be hard to understand from first standing if
577 you haven't done these before, and debugging them may be pain in the
578 ass sometimes.  But after the grand idea behind callback functions
579 becomes clear they are a wonderful tool.
580 
581 
582 Lists
583 =====
584 
585 SILC has two different list API's.  The List API and the Dynamic List API.
586 For definitions of List API see lib/silcutil/silclist.h and for Dynamic
587 List API see lib/silcutil/silcdlist.h.  Following short example of the
588 List API.
589 
590 List API
591 
592 typedef struct SilcDummyStruct {
593   int dummy;
594   void *context;
595   struct SilcDummyStruct *next;
596 } SilcDummy;
597 
598 int main()
599 {
600   SilcList list;
601   SilcDummy *dummy;
602   SilcDummy *entry;
603 
604   /* Initialize the list */
605   silc_list_init(list, struct SilcDummyStruct, next);
606 
607   /* Allocate one list entry */
608   dummy = silc_calloc(1, sizeof(*dummy));
609   dummy->dummy = 100;
610   dummy->context = NULL;
611 
612   /* Add the entry to the list */
613   silc_list_add(list, dummy);
614 
615   /* Allocate second list entry */
616   dummy = silc_calloc(1, sizeof(*dummy));
617   dummy->dummy = 3000;
618   dummy->context = NULL;
619 
620   /* Add the entry to the list */
621   silc_list_add(list, dummy);
622 
623   /* Then traverse the list, print the values, remove from list and free
624      memory */
625   silc_list_start(list);
626   while ((entry = silc_list_get(list)) != SILC_LIST_END) {
627     fprintf(stderr, "%d\n", entry->dummy);
628 
629     /* Remove from list and free memory */
630     silc_list_del(list, entry);
631     silc_free(entry);
632   }
633 
634   return 0;
635 }
636 
637 
638 Copyrights of the Code
639 ======================
640 
641 The original code in SILC is GPL licensed.  New code will be accepted to
642 the official SILC source tree if it is coded in GPL or similiar free
643 license as GPL is, and of course if it is public domain.  Code with
644 restricting licenses will not be accepted to the SILC source tree.
645 SILC is free software, open source, what ever, project and will remain
646 as such.
647 
648 Also, about authoring; If you write code to SILC don't forget to add
649 yourself as author at the start of the file.  The reason for this is
650 of course that everybody should get the credits they deserve but also
651 if problems occur we know who to blame. :)

This page was automatically generated by the LXR engine.
Free-text search provided by Glimpse