xref: /aosp_15_r20/external/coreboot/Documentation/contributing/coding_style.md (revision b9411a12aaaa7e1e6a6fb7c5e057f44ee179a49c)
1# Coding Style
2
3This document describes the preferred C coding style for the
4coreboot project. It is in many ways exactly the same as the Linux
5kernel coding style. In fact, most of this document has been copied from
6the [Linux kernel coding style](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/plain/Documentation/process/4.Coding.rst)
7
8The guidelines in this file should be seen as a strong suggestion, and
9should overrule personal preference. They may be ignored in individual
10instances when there are good practical reasons to do so, and reviewers
11are in agreement.
12
13Any style questions that are not mentioned in here should be decided
14between the author and reviewers on a case-by-case basis. When modifying
15existing files, authors should try to match the prevalent style in that
16file -- otherwise, they should generally match similar existing files in
17coreboot.
18
19Bulk style changes to existing code ("cleanup patches") should avoid
20changing existing style choices unless they actually violate this style
21guide, or there is broad consensus that the new version is an
22improvement. By default the style choices of the original author should
23be honored. (Note that `checkpatch.pl` is not part of this style guide,
24and neither is `clang-format`. These tools can be useful to find
25potential issues or simplify formatting in new submissions, but they
26were not designed to directly match this guide and may have false
27positives. They should not be bulk-applied to change existing code
28except in cases where they directly match the style guide.)
29
30## Indentation
31
32Tabs are 8 characters, and thus indentations are also 8 characters.
33There are heretic movements that try to make indentations 4 (or even 2!)
34characters deep, and that is akin to trying to define the value of PI to
35be 3.
36
37Rationale: The whole idea behind indentation is to clearly define where
38a block of control starts and ends. Especially when you've been looking
39at your screen for 20 straight hours, you'll find it a lot easier to
40see how the indentation works if you have large indentations.
41
42Now, some people will claim that having 8-character indentations makes
43the code move too far to the right, and makes it hard to read on a
4480-character terminal screen. The answer to that is that if you need
45more than 3 levels of indentation, you're screwed anyway, and should
46fix your program.  Note that coreboot has expanded the 80 character
47limit to 96 characters to allow for modern wider screens.
48
49In short, 8-char indents make things easier to read, and have the added
50benefit of warning you when you're nesting your functions too deep.
51Heed that warning.
52
53The preferred way to ease multiple indentation levels in a switch
54statement is to align the "switch" and its subordinate "case" labels
55in the same column instead of "double-indenting" the "case" labels.
56E.g.:
57
58```c
59switch (suffix) {
60case 'G':
61case 'g':
62	mem <<= 30;
63	break;
64case 'M':
65case 'm':
66	mem <<= 20;
67	break;
68case 'K':
69case 'k':
70	mem <<= 10;
71	__fallthrough;
72default:
73	break;
74}
75```
76
77Don't put multiple statements on a single line unless you have
78something to hide:
79
80```c
81if (condition) do_this;
82  do_something_everytime;
83```
84
85Don't put multiple assignments on a single line either. Kernel coding
86style is super simple. Avoid tricky expressions.
87
88Outside of comments, documentation and except in Kconfig, spaces are
89never used for indentation, and the above example is deliberately
90broken.
91
92Get a decent editor and don't leave whitespace at the end of lines. This
93will actually keep the patch from being tested in the CI, so patches
94with ending whitespace cannot be merged.
95
96## Breaking long lines and strings
97
98Coding style is all about readability and maintainability using commonly
99available tools.
100
101The limit on the length of lines is 96 columns and this is a strongly
102preferred limit.
103
104Statements longer than 96 columns will be broken into sensible chunks,
105unless exceeding 96 columns significantly increases readability and does
106not hide information. Descendants are always substantially shorter than
107the parent and are placed substantially to the right. The same applies
108to function headers with a long argument list. However, never break
109user-visible strings such as printk messages, because that breaks the
110ability to grep for them.
111
112## Placing Braces and Spaces
113
114The other issue that always comes up in C styling is the placement of
115braces. Unlike the indent size, there are few technical reasons to
116choose one placement strategy over the other, but the preferred way, as
117shown to us by the prophets Kernighan and Ritchie, is to put the opening
118brace last on the line, and put the closing brace first, thusly:
119
120```c
121if (x is true) {
122	we do y
123}
124```
125
126This applies to all non-function statement blocks (if, switch, for,
127while, do). E.g.:
128
129```c
130switch (action) {
131case KOBJ_ADD:
132	return "add";
133case KOBJ_REMOVE:
134	return "remove";
135case KOBJ_CHANGE:
136	return "change";
137default:
138	return NULL;
139}
140```
141
142However, there is one special case, namely functions: they have the
143opening brace at the beginning of the next line, thus:
144
145```c
146int function(int x)
147{
148	body of function
149}
150```
151
152Heretic people all over the world have claimed that this inconsistency
153is ... well ... inconsistent, but all right-thinking people know that
154(a) K&R are _right_ and (b) K&R are right. Besides, functions are
155special anyway (you can't nest them in C).
156
157Note that the closing brace is empty on a line of its own, _except_ in
158the cases where it is followed by a continuation of the same statement,
159ie a "while" in a do-statement or an "else" in an if-statement, like
160this:
161
162```c
163do {
164	body of do-loop
165} while (condition);
166```
167
168and
169
170```c
171if (x == y) {
172	..
173} else if (x > y) {
174	...
175} else {
176	....
177}
178```
179
180Rationale: K&R.
181
182Also, note that this brace-placement also minimizes the number of empty
183(or almost empty) lines, without any loss of readability. Thus, as the
184supply of new-lines on your screen is not a renewable resource (think
18525-line terminal screens here), you have more empty lines to put
186comments on.
187
188Do not unnecessarily use braces where a single statement will do.
189
190```c
191if (condition)
192	action();
193```
194
195and
196
197```c
198if (condition)
199	do_this();
200else
201	do_that();
202```
203
204This does not apply if only one branch of a conditional statement is a
205single statement; in the latter case use braces in both branches:
206
207```c
208if (condition) {
209	do_this();
210	do_that();
211} else {
212	otherwise();
213}
214```
215
216### Spaces
217
218Linux kernel style for use of spaces depends (mostly) on
219function-versus-keyword usage. Use a space after (most) keywords. The
220notable exceptions are sizeof, typeof, alignof, and __attribute__,
221which look somewhat like functions (and are usually used with
222parentheses in Linux, although they are not required in the language, as
223in: "sizeof info" after "struct fileinfo info;" is declared).
224
225So use a space after these keywords:
226
227```
228if, switch, case, for, do, while
229```
230
231but not with sizeof, typeof, alignof, or __attribute__. E.g.,
232
233```c
234s = sizeof(struct file);
235```
236
237Do not add spaces around (inside) parenthesized expressions. This
238example is
239
240-   bad*:
241
242```c
243s = sizeof( struct file );
244```
245
246When declaring pointer data or a function that returns a pointer type,
247the preferred use of '*' is adjacent to the data name or function
248name and not adjacent to the type name. Examples:
249
250```c
251char *linux_banner;
252unsigned long long memparse(char *ptr, char **retptr);
253char *match_strdup(substring_t *s);
254```
255
256Use one space around (on each side of) most binary and ternary
257operators, such as any of these:
258
259```
260=  +  -  <  >  *  /  %  |  &  ^  <=  >=  ==  !=  ?  :
261```
262
263but no space after unary operators:
264
265```
266&  *  +  -  ~  !  sizeof  typeof  alignof  __attribute__  defined
267```
268
269no space before the postfix increment & decrement unary operators:
270
271```
272++  --
273```
274
275no space after the prefix increment & decrement unary operators:
276
277```
278++  --
279```
280
281and no space around the '.' and "->" structure member operators.
282
283Do not leave trailing whitespace at the ends of lines. Some editors with
284"smart" indentation will insert whitespace at the beginning of new
285lines as appropriate, so you can start typing the next line of code
286right away. However, some such editors do not remove the whitespace if
287you end up not putting a line of code there, such as if you leave a
288blank line. As a result, you end up with lines containing trailing
289whitespace.
290
291Git will warn you about patches that introduce trailing whitespace, and
292can optionally strip the trailing whitespace for you; however, if
293applying a series of patches, this may make later patches in the series
294fail by changing their context lines.
295
296### Naming
297
298C is a Spartan language, and so should your naming be. Unlike Modula-2
299and Pascal programmers, C programmers do not use cute names like
300ThisVariableIsATemporaryCounter. A C programmer would call that variable
301"tmp", which is much easier to write, and not the least more difficult
302to understand.
303
304HOWEVER, while mixed-case names are frowned upon, descriptive names for
305global variables are a must. To call a global function "foo" is a
306shooting offense.
307
308GLOBAL variables (to be used only if you _really_ need them) need to
309have descriptive names, as do global functions. If you have a function
310that counts the number of active users, you should call that
311"count_active_users()" or similar, you should _not_ call it
312"cntusr()".
313
314Encoding the type of a function into the name (so-called Hungarian
315notation) is brain damaged - the compiler knows the types anyway and can
316check those, and it only confuses the programmer. No wonder MicroSoft
317makes buggy programs.
318
319LOCAL variable names should be short, and to the point. If you have some
320random integer loop counter, it should probably be called "i". Calling
321it "loop_counter" is non-productive, if there is no chance of it
322being mis-understood. Similarly, "tmp" can be just about any type of
323variable that is used to hold a temporary value.
324
325If you are afraid to mix up your local variable names, you have another
326problem, which is called the function-growth-hormone-imbalance syndrome.
327See chapter 6 (Functions).
328
329## Typedefs
330
331Please don't use things like "vps_t".
332
333It's a _mistake_ to use typedef for structures and pointers. When you
334see a
335
336```c
337vps_t a;
338```
339
340in the source, what does it mean?
341
342In contrast, if it says
343
344```c
345struct virtual_container *a;
346```
347
348you can actually tell what "a" is.
349
350Lots of people think that typedefs "help readability". Not so. They
351are useful only for:
352
353(a) totally opaque objects (where the typedef is actively used to
354_hide_ what the object is).
355
356Example: "pte_t" etc. opaque objects that you can only access using
357the proper accessor functions.
358
359NOTE! Opaqueness and "accessor functions" are not good in themselves.
360The reason we have them for things like pte_t etc. is that there really
361is absolutely _zero_ portably accessible information there.
362
363(b) Clear integer types, where the abstraction _helps_ avoid confusion
364whether it is "int" or "long".
365
366u8/u16/u32 are perfectly fine typedefs, although they fit into category
367(d) better than here.
368
369NOTE! Again - there needs to be a _reason_ for this. If something is
370"unsigned long", then there's no reason to do
371
372```c
373typedef unsigned long myflags_t;
374```
375
376but if there is a clear reason for why it under certain circumstances
377might be an "unsigned int" and under other configurations might be
378"unsigned long", then by all means go ahead and use a typedef.
379
380(c) when you use sparse to literally create a _new_ type for
381type-checking.
382
383(d) New types which are identical to standard C99 types, in certain
384exceptional circumstances.
385
386Although it would only take a short amount of time for the eyes and
387brain to become accustomed to the standard types like 'uint32_t',
388some people object to their use anyway.
389
390Therefore, the Linux-specific 'u8/u16/u32/u64' types and their signed
391equivalents which are identical to standard types are permitted --
392although they are not mandatory in new code of your own.
393
394When editing existing code which already uses one or the other set of
395types, you should conform to the existing choices in that code.
396
397(e) Types safe for use in userspace.
398
399In certain structures which are visible to userspace, we cannot require
400C99 types and cannot use the 'u32' form above. Thus, we use __u32
401and similar types in all structures which are shared with userspace.
402
403Maybe there are other cases too, but the rule should basically be to
404NEVER EVER use a typedef unless you can clearly match one of those
405rules.
406
407In general, a pointer, or a struct that has elements that can reasonably
408be directly accessed should _never_ be a typedef.
409
410## Functions
411
412Functions should be short and sweet, and do just one thing. They should
413fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,
414as we all know), and do one thing and do that well.
415
416The maximum length of a function is inversely proportional to the
417complexity and indentation level of that function. So, if you have a
418conceptually simple function that is just one long (but simple)
419case-statement, where you have to do lots of small things for a lot of
420different cases, it's OK to have a longer function.
421
422However, if you have a complex function, and you suspect that a
423less-than-gifted first-year high-school student might not even
424understand what the function is all about, you should adhere to the
425maximum limits all the more closely. Use helper functions with
426descriptive names (you can ask the compiler to in-line them if you think
427it's performance-critical, and it will probably do a better job of it
428than you would have done).
429
430Another measure of the function is the number of local variables. They
431shouldn't exceed 5-10, or you're doing something wrong. Re-think the
432function, and split it into smaller pieces. A human brain can generally
433easily keep track of about 7 different things, anything more and it gets
434confused. You know you're brilliant, but maybe you'd like to
435understand what you did 2 weeks from now.
436
437In source files, separate functions with one blank line. If the function
438is exported, the EXPORT* macro for it should follow immediately after
439the closing function brace line. E.g.:
440
441```c
442int system_is_up(void)
443{
444	return system_state == SYSTEM_RUNNING;
445}
446EXPORT_SYMBOL(system_is_up);
447```
448
449In function prototypes, include parameter names with their data types.
450Although this is not required by the C language, it is preferred in
451Linux because it is a simple way to add valuable information for the
452reader.
453
454## Centralized exiting of functions
455
456Albeit deprecated by some people, the equivalent of the goto statement
457is used frequently by compilers in form of the unconditional jump
458instruction.
459
460The goto statement comes in handy when a function exits from multiple
461locations and some common work such as cleanup has to be done. If there
462is no cleanup needed then just return directly.
463
464The rationale is:
465
466-   unconditional statements are easier to understand and follow
467-   nesting is reduced
468-   errors by not updating individual exit points when making
469    modifications are prevented
470-   saves the compiler work to optimize redundant code away ;)
471
472```c
473int fun(int a)
474{
475	int result = 0;
476	char *buffer = kmalloc(SIZE);
477
478	if (buffer == NULL)
479		return -ENOMEM;
480
481	if (condition1) {
482		while (loop1) {
483			...
484		}
485		result = 1;
486		goto out;
487	}
488	...
489	out:
490	kfree(buffer);
491	return result;
492}
493```
494
495## Commenting
496
497Comments are good, but there is also a danger of over-commenting. NEVER
498try to explain HOW your code works in a comment: it's much better to
499write the code so that the _working_ is obvious, and it's a waste of
500time to explain badly written code.
501
502Generally, you want your comments to tell WHAT your code does, not HOW.
503Also, try to avoid putting comments inside a function body: if the
504function is so complex that you need to separately comment parts of it,
505you should probably go back to chapter 6 for a while. You can make small
506comments to note or warn about something particularly clever (or ugly),
507but try to avoid excess. Instead, put the comments at the head of the
508function, telling people what it does, and possibly WHY it does it.
509
510coreboot style for comments is the C89 "/* ... */" style. You may also
511use C99-style "// ..." comments for single-line comments.
512
513The preferred style for *short* (multi-line) comments is:
514
515```c
516/* This is the preferred style for short multi-line
517   comments in the coreboot source code.
518   Please use it consistently. */
519```
520
521The preferred style for *long* (multi-line) comments is:
522
523```c
524/*
525 * This is the preferred style for multi-line
526 * comments in the coreboot source code.
527 * Please use it consistently.
528 *
529 * Description:  A column of asterisks on the left side,
530 * with beginning and ending almost-blank lines.
531 */
532```
533
534It's also important to comment data, whether they are basic types or
535derived types. To this end, use just one data declaration per line (no
536commas for multiple data declarations). This leaves you room for a small
537comment on each item, explaining its use.
538
539## You've made a mess of it
540That's OK, we all do. You've probably been told by your long-time Unix user
541helper that "GNU emacs" automatically formats the C sources for you, and
542you've noticed that yes, it does do that, but the defaults it uses are less
543than desirable (in fact, they are worse than random typing - an infinite
544number of monkeys typing into GNU emacs would never make a good program).
545
546So, you can either get rid of GNU emacs, or change it to use saner values.
547To do the latter, you can stick the following in your .emacs file:
548
549```lisp
550(defun c-lineup-arglist-tabs-only (ignored)
551  "Line up argument lists by tabs, not spaces"
552  (let* ((anchor (c-langelem-pos c-syntactic-element))
553	 (column (c-langelem-2nd-pos c-syntactic-element))
554	 (offset (- (1+ column) anchor))
555	 (steps (floor offset c-basic-offset)))
556    (* (max steps 1)
557       c-basic-offset)))
558
559(add-hook 'c-mode-common-hook
560          (lambda ()
561            ;; Add kernel style
562            (c-add-style
563             "linux-tabs-only"
564             '("linux" (c-offsets-alist
565                        (arglist-cont-nonempty
566                         c-lineup-gcc-asm-reg
567                         c-lineup-arglist-tabs-only))))))
568
569(add-hook 'c-mode-hook
570          (lambda ()
571            (let ((filename (buffer-file-name)))
572              ;; Enable kernel mode for the appropriate files
573              (when (and filename
574                         (string-match (expand-file-name "~/src/linux-trees")
575                                        filename))
576                (setq indent-tabs-mode t)
577                (c-set-style "linux-tabs-only")))))
578```
579
580This will make emacs go better with the kernel coding style for C files
581below ~/src/linux-trees.  Obviously, this should be updated to match
582your own paths for coreboot.
583
584But even if you fail in getting emacs to do sane formatting, not
585everything is lost: use "indent".
586
587Now, again, GNU indent has the same brain-dead settings that GNU emacs
588has, which is why you need to give it a few command line options.
589However, that's not too bad, because even the makers of GNU indent
590recognize the authority of K&R (the GNU people aren't evil, they are
591just severely misguided in this matter), so you just give indent the
592options "-kr -i8" (stands for "K&R, 8 character indents"), or use
593"scripts/Lindent", which indents in the latest style.
594
595"indent" has a lot of options, and especially when it comes to comment
596re-formatting you may want to take a look at the man page. But remember:
597"indent" is not a fix for bad programming.
598
599## Kconfig configuration files
600
601For all of the Kconfig* configuration files throughout the source tree,
602the indentation is somewhat different. Lines under a "config"
603definition are indented with one tab, while help text is indented an
604additional two spaces. Example:
605
606```kconfig
607config AUDIT
608	bool "Auditing support"
609	depends on NET
610	help
611	  Enable auditing infrastructure that can be used with another
612	  kernel subsystem, such as SELinux (which requires this for
613	  logging of avc messages output).  Does not do system-call
614	  auditing without CONFIG_AUDITSYSCALL.
615```
616
617Seriously dangerous features (such as write support for certain
618filesystems) should advertise this prominently in their prompt string:
619
620```kconfig
621config ADFS_FS_RW
622	bool "ADFS write support (DANGEROUS)"
623	depends on ADFS_FS
624	...
625```
626
627For full documentation on the configuration files, see the file
628Documentation/kbuild/kconfig-language.txt.
629
630Macros, Enums and RTL
631---------------------
632
633Names of macros defining constants and labels in enums are capitalized.
634
635```c
636#define CONSTANT 0x12345
637```
638
639Enums are preferred when defining several related constants.
640
641CAPITALIZED macro names are appreciated but macros resembling functions
642may be named in lower case.
643
644Generally, inline functions are preferable to macros resembling
645functions.
646
647Macros with multiple statements should be enclosed in a do - while
648block:
649
650```c
651#define macrofun(a, b, c)   \
652    do {                    \
653        if (a == 5)         \
654            do_this(b, c);  \
655    } while (0)
656```
657
658Things to avoid when using macros:
659
6601) macros that affect control flow:
661
662```c
663#define FOO(x)              \
664    do {                        \
665	    if (blah(x) < 0)        \
666		    return -EBUGGERED;  \
667    } while(0)
668```
669
670is a *very* bad idea. It looks like a function call but exits the
671"calling" function; don't break the internal parsers of those who
672will read the code.
673
6742) macros that depend on having a local variable with a magic name:
675
676```c
677#define FOO(val) bar(index, val)
678```
679
680might look like a good thing, but it's confusing as hell when one reads
681the code and it's prone to breakage from seemingly innocent changes.
682
6833) macros with arguments that are used as l-values: FOO(x) = y; will
684bite you if somebody e.g. turns FOO into an inline function.
685
6864) forgetting about precedence: macros defining constants using
687expressions must enclose the expression in parentheses. Beware of
688similar issues with macros using parameters.
689
690```c
691#define CONSTANT 0x4000
692#define CONSTEXP (CONSTANT | 3)
693```
694
695The cpp manual deals with macros exhaustively. The gcc internals manual
696also covers RTL which is used frequently with assembly language in the
697kernel.
698
699Printing coreboot messages
700------------------------
701
702coreboot developers like to be seen as literate. Do mind the spelling of
703coreboot messages to make a good impression. Do not use crippled words
704like "dont"; use "do not" or "don't" instead. Make the messages
705concise, clear, and unambiguous.
706
707coreboot messages do not have to be terminated with a period.
708
709Printing numbers in parentheses (%d) adds no value and should be
710avoided.
711
712Allocating memory
713-----------------
714
715coreboot provides a single general purpose memory allocator: malloc()
716
717The preferred form for passing a size of a struct is the following:
718
719```c
720p = malloc(sizeof(*p));
721```
722
723The alternative form where struct name is spelled out hurts readability
724and introduces an opportunity for a bug when the pointer variable type
725is changed but the corresponding sizeof that is passed to a memory
726allocator is not.
727
728Casting the return value which is a void pointer is redundant. The
729conversion from void pointer to any other pointer type is guaranteed by
730the C programming language.
731
732You should contain your memory usage to stack variables whenever
733possible. Only use malloc() as a last resort. In ramstage, you may also
734be able to get away with using static variables. Never use malloc()
735outside of ramstage.
736
737Since coreboot only runs for a very short time, there is no memory
738deallocator, although a corresponding free() is offered. It is a no-op.
739Use of free() is not required though it is accepted. It is useful when
740sharing code with other codebases that make use of free().
741
742The inline disease
743------------------
744
745There appears to be a common misperception that gcc has a magic "make
746me faster" speedup option called "inline". While the use of inlines
747can be appropriate (for example as a means of replacing macros, see
748Chapter 12), it very often is not.
749
750A reasonable rule of thumb is to not put inline at functions that have
751more than 3 lines of code in them. An exception to this rule are the
752cases where a parameter is known to be a compile time constant, and as a
753result of this constantness you *know* the compiler will be able to
754optimize most of your function away at compile time. For a good example
755of this later case, see the kmalloc() inline function.
756
757Often people argue that adding inline to functions that are static and
758used only once is always a win since there is no space tradeoff. While
759this is technically correct, gcc is capable of inlining these
760automatically without help, and the maintenance issue of removing the
761inline when a second user appears outweighs the potential value of the
762hint that tells gcc to do something it would have done anyway.
763
764Function return values and names
765--------------------------------
766
767Functions can return values of many different kinds, and one of the most
768common is a value indicating whether the function succeeded or failed.
769Such a value can be represented as an error-code integer (`CB_ERR_xxx`
770(negative number) = failure, `CB_SUCCESS` (0) = success) or a "succeeded"
771boolean (0 = failure, non-zero = success).
772
773Mixing up these two sorts of representations is a fertile source of
774difficult-to-find bugs. If the C language included a strong distinction
775between integers and booleans then the compiler would find these
776mistakes for us... but it doesn't. To help prevent such bugs, always
777follow this convention:
778
779If the name of a function is an action or an imperative command,
780the function should return an error-code integer.  If the name
781is a predicate, the function should return a "succeeded" boolean.
782
783For example, "add work" is a command, and the `add_work()` function
784returns 0 for success or `CB_ERR` for failure. In the same way, "PCI
785device present" is a predicate, and the `pci_dev_present()` function
786returns 1 if it succeeds in finding a matching device or 0 if it
787doesn't.
788
789Functions whose return value is the actual result of a computation,
790rather than an indication of whether the computation succeeded, are not
791subject to this rule. Generally they indicate failure by returning some
792out-of-range result. Typical examples would be functions that return
793pointers; they use NULL to report failure.
794
795Error handling, assertions and die()
796-----------------------------
797
798As firmware, coreboot has no means to let the user interactively fix things when
799something goes wrong. We either succeed to boot or the device becomes a brick
800that must be recovered through complicated external means (e.g. a flash
801programmer). Therefore, coreboot code should strive to continue booting
802wherever possible.
803
804In most cases, errors should be handled by logging a message of at least
805`BIOS_ERR` level, returning out of the function stack for the failed feature,
806and then continuing execution. For example, if a function reading the EDID of an
807eDP display panel encounters an I2C error, it should print a "cannot read EDID"
808message and return an error code. The calling display initialization function
809knows that without the EDID there is no way to initialize the display correctly,
810so it will also immediately return with an error code without running its
811remaining code that would initialize the SoC's display controller. Execution
812returns further up the function stack to the mainboard initialization code
813which continues booting despite the failed display initialization, since
814display functionality is non-essential to the system. (Code is encouraged but
815not required to use `enum cb_err` error codes to return these errors.)
816
817coreboot also has the `die()` function that completely halts execution. `die()`
818should only be used as a last resort, since it results in the worst user
819experience (bricked system). It is generally preferrable to continue executing
820even after a problem was encountered that might be fatal (e.g. SPI clock
821couldn't be configured correctly), because a slight chance of successfully
822booting is still better than not booting at all. The only cases where `die()`
823should be used are:
824
8251. There is no (simple) way to continue executing. For example, when loading the
826   next stage from SPI flash fails, we don't have any more code to execute. When
827   memory initialization fails, we have no space to load the ramstage into.
828
8292. Continuing execution would pose a security risk. All security features in
830   coreboot are optional, but when they are configured in the user must be able
831   to rely on them. For example, if CBFS verification is enabled and the file
832   hash when loading the romstage doesn't match what it should be, it is better
833   to stop execution than to jump to potentially malicious code.
834
835In addition to normal error logging with `printk()`, coreboot also offers the
836`assert()` macro. `assert()` should be used judiciously to confirm that
837conditions are true which the programmer _knows_ to be true, in order to catch
838programming errors and incorrect assumptions. It is therefore different from a
839normal `if ()`-check that is used to actually test for things which may turn
840out to be true or false based on external conditions. For example, anything
841that involves communicating with hardware, such as whether an attempt to read
842from SPI flash succeeded, should _not_ use `assert()` and should instead just
843be checked with a normal `if ()` and subsequent manual error handling. Hardware
844can always fail for various reasons and the programmer can never 100% assume in
845advance that it will work as expected. On the other hand, if a function takes a
846pointer parameter `ctx` and the contract for that function (as documented in a
847comment above its declaration) specifies that this parameter should point to a
848valid context structure, then adding an `assert(ctx)` line to that function may
849be a good idea. The programmer knows that this function should never be called
850with a NULL pointer (because that's how it is specified), and if it was actually
851called with a NULL pointer that would indicate a programming error on account of
852the caller.
853
854`assert()` can be configured to either just print an error message and continue
855execution (default), or call `die()` (when `CONFIG_FATAL_ASSERTS` is set).
856Developers are encouraged to always test their code with this option enabled to
857make assertion errors (and therefore bugs) more easy to notice. Since assertions
858thus do not always stop execution, they should never be relied upon to be the
859sole guard against conditions that really _need_ to stop execution (e.g.
860security guarantees should never be enforced only by `assert()`).
861
862Headers and includes
863---------------
864
865Headers should always be included at the top of the file. Includes should
866always use the `#include <file.h>` notation, except for rare cases where a file
867in the same directory that is not part of a normal include path gets included
868(e.g. local headers in mainboard directories), which should use `#include
869"file.h"`. Local "file.h" includes should always come separately after all
870<file.h> includes.  Headers that can be included from both assembly files and
871.c files should keep all C code wrapped in `#ifndef __ASSEMBLER__` blocks,
872including includes to other headers that don't follow that provision. Where a
873specific include order is required for technical reasons, it should be clearly
874documented with comments. This should not be the norm.
875
876Files should generally include every header they need a definition from
877directly (and not include any unnecessary extra headers). Excepted from
878this are certain headers that intentionally chain-include other headers
879which logically belong to them and are just factored out into a separate
880location for implementation or organizatory reasons. This could be
881because part of the definitions is generic and part SoC-specific (e.g.
882`<gpio.h>` chain-including `<soc/gpio.h>`), architecture-specific (e.g.
883`<device/mmio.h>` chain-including `<arch/mmio.h>`), separated out into
884commonlib[/bsd] for sharing/license reasons (e.g. `<cbfs.h>`
885chain-including `<commonlib/bsd/cbfs_serialized.h>`) or just split out
886to make organizing subunits of a larger header easier. This can also
887happen when certain definitions need to be in a specific header for
888legacy POSIX reasons but we would like to logically group them together
889(e.g. `uintptr_t` is in `<stdint.h>` and `size_t` in `<stddef.h>`, but
890it's nicer to be able to just include `<types.h>` and get all the common
891type and helper function stuff we need everywhere).
892
893The headers `<kconfig.h>`, `<rules.h>` and `<commonlib/bsd/compiler.h>`
894are always automatically included in all compilation units by the build
895system and should not be included manually.
896
897Don't re-invent common macros
898-----------------------------
899
900The header file `src/commonlib/bsd/include/commonlib/bsd/helpers.h`
901contains a number of macros that you should use, rather than explicitly
902coding some variant of them yourself. For example, if you need to
903calculate the length of an array, take advantage of the macro
904
905```c
906#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
907```
908
909Editor modelines and other cruft
910--------------------------------
911
912Some editors can interpret configuration information embedded in source
913files, indicated with special markers. For example, emacs interprets
914lines marked like this:
915
916```
917-*- mode: c -*-
918```
919
920Or like this:
921
922```
923/*
924Local Variables:
925compile-command: "gcc -DMAGIC_DEBUG_FLAG foo.c"
926End:
927*/
928```
929
930Vim interprets markers that look like this:
931
932```
933/* vim:set sw=8 noet */
934```
935
936Do not include any of these in source files. People have their own
937personal editor configurations, and your source files should not
938override them. This includes markers for indentation and mode
939configuration. People may use their own custom mode, or may have some
940other magic method for making indentation work correctly.
941
942Inline assembly
943---------------
944
945In architecture-specific code, you may need to use inline assembly to
946interface with CPU or platform functionality. Don't hesitate to do so
947when necessary. However, don't use inline assembly gratuitously when C
948can do the job. You can and should poke hardware from C when possible.
949
950Consider writing simple helper functions that wrap common bits of inline
951assembly, rather than repeatedly writing them with slight variations.
952Remember that inline assembly can use C parameters.
953
954Large, non-trivial assembly functions should go in .S files, with
955corresponding C prototypes defined in C header files. The C prototypes
956for assembly functions should use "asmlinkage".
957
958You may need to mark your asm statement as volatile, to prevent GCC from
959removing it if GCC doesn't notice any side effects. You don't always
960need to do so, though, and doing so unnecessarily can limit
961optimization.
962
963When writing a single inline assembly statement containing multiple
964instructions, put each instruction on a separate line in a separate
965quoted string, and end each string except the last with nt to
966properly indent the next instruction in the assembly output:
967
968```c
969asm ("magic %reg1, #42nt"
970	"more_magic %reg2, %reg3"
971	: /* outputs */ : /* inputs */ : /* clobbers */);
972```
973
974GCC extensions
975--------------
976
977GCC is the only officially-supported compiler for coreboot, and a
978variety of its C language extensions are heavily used throughout the
979code base. There have been occasional attempts to add clang as a second
980compiler option, which is generally compatible to the same language
981extensions that have been long-established by GCC.
982
983Some GCC extensions (e.g. inline assembly) are basically required for
984proper firmware development. Others enable more safe or flexible
985coding patterns than can be expressed with standard C (e.g. statement
986expressions and `typeof()` to avoid double evaluation in macros like
987`MAX()`). Yet others just add some simple convenience and reduce
988boilerplate (e.g. `void *` arithmetic).
989
990Since some GCC extensions are necessary either way, there is no gain
991from avoiding other GCC extensions elsewhere. The use of all official
992GCC extensions is expressly allowed within coreboot. In cases where an
993extension can be replaced by a 100% equivalent C standard feature with
994no extra boilerplate or loss of readability, the C standard feature
995should be preferred (this usually only happens when GCC retains an
996older pre-standardization extension for backwards compatibility, e.g.
997the old pre-C99 syntax for designated initializers). But if there is
998any advantage offered by the GCC extension (e.g. using GCC zero-length
999arrays instead of C99 variable-length arrays because they don't inhibit
1000`sizeof()`), there is no reason to deprive ourselves of that, and "this
1001is not C standard compliant" should not be a reason to argue against
1002its use in reviews.
1003
1004This rule only applies to explicit GCC extensions listed in the
1005"Extensions to the C Language Family" section of the GCC manual. Code
1006should never rely on incidental GCC translation behavior that is not
1007explicitly documented as a feature and could change at any moment.
1008
1009Refactoring
1010-----------
1011Because refactoring existing code can add bugs to tested code, any
1012refactors should be done only with serious consideration. Refactoring
1013for style differences should only be done if the existing style
1014conflicts with a documented coreboot guideline. If you believe that the
1015style should be modified, the pros and cons can be discussed on the
1016mailing list and in the coreboot leadership meeting.
1017
1018Similarly, the original author should be respected. Changing working
1019code simply because of a stylistic disagreement is *prohibited*. This is
1020not saying that refactors that are objectively better (simpler, faster,
1021easier to understand) are not allowed, but there has to be a definite
1022improvement, not simply stylistic changes.
1023
1024Basically, when refactoring code, there should be a clear benefit to
1025the project and codebase. The reviewers and submitters get to make the
1026call on how to interpret this.
1027
1028When refactoring, adding unit tests to verify that the post-change
1029functionality matches or improves upon pre-change functionality is
1030encouraged.
1031
1032References
1033----------
1034
1035The C Programming Language, Second Edition by Brian W. Kernighan and
1036Dennis M. Ritchie. Prentice Hall, Inc., 1988. ISBN 0-13-110362-8
1037(paperback), 0-13-110370-9 (hardback). URL:
1038<https://duckduckgo.com/?q=isbn+0-13-110362-8> or
1039<https://www.google.com/search?q=isbn+0-13-110362-8>
1040
1041
1042The Practice of Programming by Brian W. Kernighan and Rob Pike.
1043Addison-Wesley, Inc., 1999. ISBN 0-201-61586-X. URL:
1044<https://duckduckgo.com/?q=ISBN+0-201-61586-X> or
1045<https://www.google.com/search?q=ISBN+0-201-61586-X>
1046
1047GNU manuals - where in compliance with K&R and this text - for cpp, gcc,
1048gcc internals and indent, all available from
1049<http://www.gnu.org/manual/>
1050
1051WG14 is the international standardization working group for the
1052programming language C, URL: <http://www.open-std.org/JTC1/SC22/WG14/>
1053
1054Kernel CodingStyle, by [email protected] at OLS 2002:
1055<http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/>
1056