1LIBXENLIGHT CODING STYLE 2======================== 3 4 5AN APOLOGY AND WARNING 6---------------------- 7 8Much of the code in libxl does not yet follow this coding style 9document in every respect. However, new code is expected to conform. 10 11Patches to improve the style of existing code are welcome. Please 12separate these out from functional changes. 13 14If it is not feasible to conform fully to the style while patching old 15code, without doing substantial style reengineering first, we may 16accept patches which contain nonconformant elements, provided that 17they don't make the coding style problem worse overall. 18 19In this case, the new code should conform to the prevailing style in 20the area being touched. 21 22 23MEMORY ALLOCATION 24----------------- 25 26Memory allocation for libxl-internal purposes should normally be done 27with the provided gc mechanisms; there is then no need to free. See 28"libxl memory management" in libxl.h. 29 30 31CONVENTIONAL VARIABLE NAMES 32--------------------------- 33 34The following local variable names should be used where applicable: 35 36 int rc; /* a libxl error code - and not anything else */ 37 int r; /* the return value from a system call (or libxc call) */ 38 bool ok; /* the success return value from a boolean function */ 39 40 uint32_t domid; 41 libxl__gc *gc; 42 libxl__egc *egc; 43 libxl__ao *ao; 44 45 libxl_foo_bar_state *fbs; /* local variable */ 46 libxl_foo_bar_state foo_bar; /* inside another state struct */ 47 48 49CONVENIENCE MACROS 50------------------ 51 52There are a number of convenience macros which shorten the program and 53avoid opportunity for mistakes. In some cases non-use of the macros 54produces functional bugs or incorrect error handling. Use the macros 55whenever they are applicable. For example: 56 57 Usually, don't use: Instead, use (see libxl_internal.h): 58 libxl__log[v] LOG, LOGE, LOGEV 59 libxl__sprintf GCSPRINTF 60 libxl__*alloc et al. GCNEW, GCNEW_ARRAY, GCREALLOC_ARRAY 61 isalnum etc. directly CTYPE 62 libxl__ctx_[un]lock CTX_LOCK, CTX_UNLOCK 63 gc=...; ao=...; EGC_GC, AO_GC, STATE_AO_GC 64 explicit gc creation GC_INIT, GC_FREE 65 memset(..,0,sizeof..) FILLZERO 66 67Instead of malloc et al one should (as an exception to the above) use 68libxl__{zalloc,calloc,realloc} etc but passing NOGC. 69 70ERROR HANDLING 71-------------- 72 73Unless, there are good reasons to do otherwise, the following error 74handling and cleanup paradigm should be used: 75 76 * All local variables referring to resources which might need 77 cleaning up are declared at the top of the function, and 78 initialised to a sentinel value indicating "nothing allocated". 79 For example, 80 libxl_evgen_disk_eject *evg = NULL; 81 int nullfd = -1; 82 83 * If the function is to return a libxl error value, `rc' is 84 used to contain the error code, but it is NOT initialised: 85 int rc; 86 87 * There is only one error cleanup path out of the function. It 88 starts with a label `out:'. That error cleanup path checks for 89 each allocated resource and frees it iff necessary. It then 90 returns rc. For example, 91 out: 92 if (evg) libxl__evdisable_disk_eject(gc, evg); 93 if (nullfd >= 0) close(nullfd); 94 return rc; 95 96 * Function calls which might fail (ie most function calls) are 97 handled by putting the return/status value into a variable, and 98 then checking it in a separate statement: 99 char *dompath = libxl__xs_get_dompath(gc, bl->domid); 100 if (!dompath) { rc = ERROR_FAIL; goto out; } 101 102 * If a resource is freed in the main body of the function (for 103 example, in a loop), the corresponding variable has to be reset to 104 the sentinel at the point where it's freed. 105 106Whether to use the `out' path for successful returns as well as error 107returns is a matter of taste and convenience for the specific 108function. Not reusing the out path is fine if the duplicated function 109exit code is only `CTX_UNLOCK; GC_FREE;' (or similar). 110 111If you reuse the `out' path for successful returns, there may be 112resources which are to be returned to the caller rather than freed. 113In that case you have to reset the local variable to `nothing here', 114to avoid the resource being freed on the out path. That resetting 115should be done immediately after the resource value is stored at the 116applicable _r function parameter (or equivalent). Do not test `rc' in 117the out section, to discover whether to free things. 118 119The uses of the single-line formatting in the examples above are 120permitted exceptions to the usual libxl code formatting rules. 121 122 123 124ARCHITECTURE-SPECIFIC CODE, CONDITIONAL COMPILATION 125--------------------------------------------------- 126 127Architecture-specific code should be isolated in libxl_<arch>.c, 128with a function call interface, wherever possible. 129 130#ifdefs should be avoided, and in any case not interspersed through 131the primary functional code. 132 133 134IDEMPOTENT DATA STRUCTURE CONSTRUCTION/DESTRUCTION 135-------------------------------------------------- 136 137Nontrivial data structures (in structs) should come with an idempotent 138_dispose function, which must free all resources associated with the 139data structure (but not free the struct itself). 140 141Such a struct should also come with an _init function which 142initialises the struct so that _dispose is a no-op. 143 144 145ASYNCHRONOUS/LONG-RUNNING OPERATIONS 146------------------------------------ 147 148All long-running operations in libxl need to use the asynchronous 149operation machinery. Consult the programmer documentation in 150libxl_internal.h for details - search for "Machinery for asynchronous 151operations". 152 153The code for asynchronous operations should be laid out in 154chronological order. That is, where there is a chain of callback 155functions, each subsequent function should be, textually, the next 156function in the file. This will normally involve predeclaring the 157callback functions. Synchronous helper functions should be separated 158out into a section preceding the main callback chain. 159 160Control flow arrangements in asynchronous operations should be made as 161simple as possible, because it can otherwise be very hard to see 162through the tangle. 163 164 165When inventing a new sub-operation in asynchronous code, consider 166whether to structure it formally as a sub-operation with its own state 167structure. (See, for example, libxl__datacopier_*.) 168 169An ao-suboperation state structure should contain, in this order: 170 * fields that the caller must fill in, and which are, 171 effectively, the parameters to the operation, including: 172 - libxl__ao *ao 173 - the callback function pointer(s), which 174 should be named callback or callback_*. 175 * shared information fields or ones used for returning information 176 to the calling operation 177 * private fields 178These sections should be clearly demarcated by comments. 179 180An asynchronous operation should normally have an idempotent stop or 181cancel function. It should normally also have an _init function for 182its state struct, which arranges that the stop is a no-op. 183 184The permitted order of calls into your ao operation's methods must be 185documented in comments, if it is nontrivial. 186 187 188When using an ao sub-operation, you should normally: 189 * Physically include the sub-operation state struct in your 190 own state struct; 191 * Use CONTAINER_OF to find your own state struct at the start of 192 your implementations of the sub-operation callback functions; 193 * Unconditionally initialise the sub-operation's struct (with its 194 _init method) in your own _init method. 195 * Unconditionally cancel or destroy the sub-operation in your own 196 cancel or destroy method. 197 198 199FORMATTING AND NAMING 200--------------------- 201 202Blatantly copied from qemu and linux with few modifications. 203 204 2051. Whitespace 206 207Of course, the most important aspect in any coding style is whitespace. 208Crusty old coders who have trouble spotting the glasses on their noses 209can tell the difference between a tab and eight spaces from a distance 210of approximately fifteen parsecs. Many a flamewar have been fought and 211lost on this issue. 212 213Libxenlight indents are four spaces. Tabs are never used, except in 214Makefiles where they have been irreversibly coded into the syntax. 215Spaces of course are superior to tabs because: 216 217 - You have just one way to specify whitespace, not two. Ambiguity breeds 218 mistakes. 219 - The confusion surrounding 'use tabs to indent, spaces to justify' is gone. 220 - Tab indents push your code to the right, making your screen seriously 221 unbalanced. 222 - Tabs will be rendered incorrectly on editors who are misconfigured not 223 to use tab stops of eight positions. 224 - Tabs are rendered badly in patches, causing off-by-one errors in almost 225 every line. 226 - It is the libxenlight coding style. 227 228Do not leave whitespace dangling off the ends of lines. 229 230 2312. Line width 232 233Lines are limited to 75 characters. 234 235Rationale: 236 - Some people like to tile their 24" screens with a 6x4 matrix of 80x24 237 xterms and use vi in all of them. The best way to punish them is to 238 let them keep doing it. 239 - In an 80 column terminal, some room needs to be left for > quoting 240 characters, +/- diff characters, and so on, in emails. 241 - Code and especially patches is much more readable if limited to a sane 242 line length. Eighty is traditional. 243 - It is the libxenlight coding style. 244 245 2463. Naming 247 248C is a Spartan language, and so should your naming be. Unlike Modula-2 249and Pascal programmers, C programmers do not use cute names like 250ThisVariableIsATemporaryCounter. A C programmer would call that 251variable "tmp", which is much easier to write, and not the least more 252difficult to understand. 253 254HOWEVER, while mixed-case names are frowned upon, descriptive names for 255global variables are a must. To call a global function "foo" is a 256shooting offense. 257 258GLOBAL variables (to be used only if you _really_ need them) need to 259have descriptive names, as do global functions. If you have a function 260that counts the number of active users, you should call that 261"count_active_users()" or similar, you should _not_ call it "cntusr()". 262 263Encoding the type of a function into the name (so-called Hungarian 264notation) is brain damaged - the compiler knows the types anyway and can 265check those, and it only confuses the programmer. 266 267LOCAL variable names should be short, and to the point. If you have 268some random integer loop counter, it should probably be called "i". 269Calling it "loop_counter" is non-productive, if there is no chance of it 270being mis-understood. Similarly, "tmp" can be just about any type of 271variable that is used to hold a temporary value. 272 273Local variables used to store return values should have descriptive name 274like "rc" or "ret". Following the same reasoning the label used as exit 275path should be called "out". 276 277Function arguments which are used to return values to the caller 278should be suffixed `_r' or `_out'. 279 280Variables, type names and function names are 281lower_case_with_underscores. 282Type names and function names use the prefix libxl__ when internal to 283libxenlight and libxl_ when exported in libxl.h. 284Xl should avoid using libxl_ and libxl__ as prefix for its own function 285names. 286 287When wrapping standard library functions, use the prefix libxl_ to alert 288readers that they are seeing a wrapped version; otherwise avoid this prefix. 289 290Typedefs are used to eliminate the redundant 'struct' keyword. 291It is the libxenlight coding style. 292 293 2944. Statements 295 296Don't put multiple statements on a single line. 297Don't put multiple assignments on a single line either. 298Error code paths with an if statement and a goto or a return on the same 299line are allowed. Examples: 300 301 if (rc) goto out; 302 if (rc < 0) return; 303 304Libxenlight coding style is super simple. Avoid tricky expressions. 305 306 3075. Block structure 308 309Every indented statement is braced, but blocks that contain just one 310statement may have the braces omitted. To avoid confusion, either all 311the blocks in an if...else chain have braces, or none of them do. 312 313The opening brace is on the line that contains the control flow 314statement that introduces the new block; the closing brace is on the 315same line as the else keyword, or on a line by itself if there is no 316else keyword. Examples: 317 318 if (a == 5) { 319 printf("a was 5.\n"); 320 } else if (a == 6) { 321 printf("a was 6.\n"); 322 } else { 323 printf("a was something else entirely.\n"); 324 } 325 326 if (a == 5) 327 printf("a was 5.\n"); 328 329An exception is the opening brace for a function; for reasons of tradition 330and clarity it comes on a line by itself: 331 332 void a_function(void) 333 { 334 do_something(); 335 } 336 337Rationale: a consistent (except for functions...) bracing style reduces 338ambiguity and avoids needless churn when lines are added or removed. 339Furthermore, it is the libxenlight coding style. 340 341