<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Barr Code</title>
	<atom:link href="http://embeddedgurus.com/barr-code/feed/" rel="self" type="application/rss+xml" />
	<link>http://embeddedgurus.com/barr-code</link>
	<description>A Blog by Michael Barr</description>
	<lastBuildDate>Wed, 25 Jan 2012 09:45:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Combining C&#8217;s volatile and const Keywords</title>
		<link>http://embeddedgurus.com/barr-code/2012/01/combining-cs-volatile-and-const-keywords/</link>
		<comments>http://embeddedgurus.com/barr-code/2012/01/combining-cs-volatile-and-const-keywords/#comments</comments>
		<pubDate>Tue, 24 Jan 2012 11:29:17 +0000</pubDate>
		<dc:creator>Michael Barr</dc:creator>
				<category><![CDATA[Coding Standards]]></category>
		<category><![CDATA[Efficient C/C++]]></category>
		<category><![CDATA[Firmware Bugs]]></category>
		<category><![CDATA[bugs]]></category>
		<category><![CDATA[embedded]]></category>
		<category><![CDATA[firmware]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[safety]]></category>
		<category><![CDATA[standards]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/barr-code/?p=695</guid>
		<description><![CDATA[Does it ever make sense to declare a variable in C or C++ as both volatile (i.e., &#8220;ever-changing&#8221;) and const (&#8220;read-only&#8221;)? If so, why? And how should you combine volatile and const properly? One of the most consistently popular articles on the Netrino website is about C&#8217;s volatile keyword. The volatile keyword, like const, is [...]]]></description>
			<content:encoded><![CDATA[<p><em>Does it ever make sense to declare a variable in C or C++ as both volatile (i.e., &#8220;ever-changing&#8221;) and const (&#8220;read-only&#8221;)?  If so, why?  And how should you combine volatile and const properly?</em></p>
<p>One of the most consistently popular articles on the <a href="http://www.netrino.com" title="Netrino" target="_blank">Netrino</a> website is about C&#8217;s volatile keyword. The volatile keyword, like const, is a type qualifier.  These keywords can be used by themselves or together in variable declarations.</p>
<p>I&#8217;ve written about volatile and const individually before.  If you haven&#8217;t previously used the volatile keyword, I recommend you read <a href="http://www.netrino.com/Embedded-Systems/How-To/C-Volatile-Keyword" title="How to Use C's volatile Keyword" target="_blank">How to Use C&#8217;s volatile Keyword</a> before going on.  As that article makes plain:</p>
<blockquote><p>C&#8217;s volatile keyword is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time&#8211;without any action being taken by the code the compiler finds nearby.</p></blockquote>
<p><b>How to Use C&#8217;s volatile Keyword</b></p>
<p>By declaring a variable volatile you are effectively asking the compiler to be as inefficient as possible when it comes to reading or writing that variable.  Specifically, the compiler should generate object code to perform each and every read from a volatile variable and each and every write to a volatile variable&#8211;even if you write it twice in a row or read it and ignore the result.  No read or write can be skipped.  Effectively no optimizations are allowed with respect to volatile variables.  </p>
<p>The use of volatile variables also creates additional sequence points in C and C++ programs.  The order of accesses of volatile variables A and B in the object code must be the same as the order of those accesses in the source code.  The compiler is not allowed to reorder volatile variable accesses for any reason.</p>
<p>Here are a couple of examples of declarations of volatile variables:</p>
<p><code>int volatile g_flag_shared_with_isr;</code><br />
<br />
<code>uint8_t volatile * p_led_reg = (uint8_t *) 0x00080000;</code></p>
<p>The first example declares a global flag that can be shared between an ISR and some other part of the code (e.g., a background processing loop in main() or an RTOS task) without fear that the compiler will optimize (i.e., &#8220;delete&#8221;) the code you write to check for asynchronous changes to the flag&#8217;s value.  It is important to use volatile to declare all variables that are shared by asynchronous software entities, which is important in any kind of multithreaded programming.  (Remember, though, that access to global variables shared by tasks or with an ISR must always also be controlled via a <a href="http://www.netrino.com/Embedded-Systems/How-To/RTOS-Mutex-Semaphore" title="Mutexes and Semaphores Demystified" target="_blank">mutex</a> or interrupt disable, respectively.)</p>
<p>The second example declares a pointer to a hardware register at a known physical memory address (80000h)&#8211;in this case to manipulate the state of one or more LEDs.  Because the pointer to the hardware register is declared volatile, the compiler must always perform each individual write.  Even if you write C code to turn an LED on followed immediately by code to turn the same LED off, you can trust that the hardware really will receive both instructions.  Because of the sequence point restrictions, you are also guaranteed that the LED will be off after both lines of the C code have been executed.  The volatile keyword should always be used with creating pointers to memory-mapped I/O such as this.</p>
<p>[See <a href="http://embeddedgurus.com/barr-code/2009/03/coding-standard-rule-4-use-volatile-whenever-possible/" title="Coding Standard Rule #4: Use volatile Whenever Possible" target="_blank">Coding Standard Rule #4: Use volatile Whenever Possible</a> for more on the use of volatile by itself.]</p>
<p><strong>How to Use C&#8217;s const Keyword</strong></p>
<p>The const keyword is can be used to modify parameters as well as in variable declarations.  Here we are only interested in the use of const as a type qualifier, as in:</p>
<p><code>uint16_t const max_temp_in_c = 1000;</code></p>
<p>This declaration creates a 16-bit unsigned integer value of 1,000 with a scoped name of <code>max_temp_in_c</code>.  In C, this variable will exist in memory at run-time, but will typically be located, by the linker, in a non-volatile memory area such as ROM or flash.  Any reference to the const variable will read from that location.  (In C++, a const integer may no longer exist as an addressable location in run-time memory.)</p>
<p>Any attempt the code makes to write to a const variable directly (i.e., by its name) will result in a compile-time error.  To the extent that the const variable is located in ROM or flash, an indirect write (i.e., via a pointer to its address) will also be thwarted&#8211;though at run-time, obviously.</p>
<p>Another use of const is to mark a hardware register as read-only.  For example:</p>
<p><code>uint8_t const * p_latch_reg = 0x10000000;</code></p>
<p>Declaring the pointer this way, any attempt to write to that physical memory address via the pointer (e.g., <code>*p_latch_reg = 0xFF;</code>) should result in a compile-time error.</p>
<p>[See <a href="http://embeddedgurus.com/barr-code/2009/03/coding-standard-rule-2-use-const-wherever-possible/" title="Coding Standard Rule #2: Use const Whenever Possible" target="_blank">Coding Standard Rule #2: Use const Whenever Possible</a> for more on the use of const by itself.]</p>
<p><strong>How to Use const and volatile Together</strong></p>
<p>Though the essence of the volatile (&#8220;ever-changing&#8221;) and const (&#8220;read-only&#8221;) decorators may seem at first glance opposed, there are some times when it makes sense to use them both to declare one variable.  The scenarios I&#8217;ve run across have involved pointers to memory-mapped hardware registers and shared memory areas.</p>
<p><em>(#1) Constant Addresses of Hardware Registers</em></p>
<p>The following declaration uses both const and volatile in the frequently useful scenario of declaring a constant pointer to a volatile hardware register.</p>
<p><code>uint8_t volatile * const p_led_reg = (uint8_t *) 0x00080000;</code></p>
<p>The proper way to read a complex declaration like this is from the name of the variable back to the left, as in:</p>
<blockquote><p>p_led_reg IS A constant pointer TO A volatile 8-bit unsigned integer.</p></blockquote>
<p>Reading it that way, we can see that the keyword const modifies only the pointer (i.e., the fixed address 80000h), which does not change at run-time.  Whereas the keyword volatile modifies only the type of integer.  This is actually quite useful and is a much safer version of the declaration of a p_led_reg that appears at the top of this article.  In particular, adding const means that the simple typo of a missed pointer dereference (&#8216;*&#8217;) will be caught at compile time.  That is, the mistaken code <code>p_led_reg = LED1_ON;</code> won&#8217;t overwrite the address with the non-80000h value of LED1_ON.  The compiler error leads us to correct this to <code>*p_led_reg = LED1_ON;</code>, which is almost certainly what we meant to write in the first place.</p>
<p><em>(#2) Read-Only Shared-Memory Buffer</em></p>
<p>Another use for a combination of const and volatile is where you have two processors communicating via a shared memory area and you are coding the side of this communications that will only be reading from a shared memory buffer.  In this case you could declare variables such as:</p>
<p><code>int const volatile comm_flag;</code><br />
<br />
<code>uint8_t const volatile comm_buffer[BUFFER_SIZE];</code></p>
<p>Of course, you&#8217;d usually want to instruct the linker to place these global variables at the correct addresses in the shared memory area or to declare the above as pointers to specific physical memory addresses.  In the case of pointers, the use of const and volatile may become even more complex, as in the next category.</p>
<p><em>(#3) Read-Only Hardware Register</em></p>
<p>Sometimes you will run across a read-only hardware register.  In addition to enforcing compile-time checking so that the software doesn&#8217;t try to overwrite the memory location, you also need to be sure that each and every requested read actually occurs.  By declaring your variable IS A (constant) pointer TO A constant and volatile memory location you request all of the appropriate protections, as in:</p>
<p><code>uint8_t const volatile * const p_latch_reg = (uint8_t *) 0x10000000;</code></p>
<p>As you can see, the declarations of variables that involve both the volatile and const decorators can quickly become complicated to read.  But the technique of combining C&#8217;s volatile and const keywords can be useful and even important.  This is definitely something you should learn to master to be a master embedded software engineer.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/barr-code/2012/01/combining-cs-volatile-and-const-keywords/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Firmware Forensics: Best Practices in Embedded Software Source Code Discovery</title>
		<link>http://embeddedgurus.com/barr-code/2011/09/firmware-forensics-best-practices-in-embedded-software-source-code-discovery/</link>
		<comments>http://embeddedgurus.com/barr-code/2011/09/firmware-forensics-best-practices-in-embedded-software-source-code-discovery/#comments</comments>
		<pubDate>Tue, 27 Sep 2011 15:32:25 +0000</pubDate>
		<dc:creator>Michael Barr</dc:creator>
				<category><![CDATA[Firmware Bugs]]></category>
		<category><![CDATA[copyright]]></category>
		<category><![CDATA[embedded]]></category>
		<category><![CDATA[firmware]]></category>
		<category><![CDATA[patents]]></category>
		<category><![CDATA[safety]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/barr-code/?p=692</guid>
		<description><![CDATA[Software has become ubiquitous, embedded as it is into the fabric of our lives in literally billions of new (non-computer) products per year, from microwave ovens to electronic throttle controls. When products controlled by software are the subject of litigation, whether for infringement of intellectual property rights or product liability, it is imperative to analyze [...]]]></description>
			<content:encoded><![CDATA[<p>Software has become ubiquitous, embedded as it is into the fabric of our lives in literally billions of new (non-computer) products per year, from microwave ovens to electronic throttle controls.  When products controlled by software are the subject of litigation, whether for infringement of intellectual property rights or product liability, it is imperative to analyze the embedded software (a.k.a., firmware) properly and thoroughly.  This article enumerates five best practices for embedded software source code discovery and the rationale for each.</p>
<p>In February 2011, the U.S. government’s <a href="http://www.nhtsa.gov">National Highway Traffic Safety Administration</a> and a team from <a href="http://www.nasa.gov/offices/nesc/">NASA’s Engineering and Safety Center</a> published reports of their joint investigation into the causes of unintended acceleration in Toyota vehicles. While NHTSA led the overall effort and examined recall records, accident reports, and complaint statistics, the more technically focused team from NASA performed reviews of the electronics and embedded software at the heart of Toyota’s “electronic throttle control subsystem” (ETCS). Redacted public versions of the official reports from each agency, together with a number of related documents, can be found at http://www.nhtsa.gov/UA.</p>
<p>These reports are very interesting in what they have to say about the quality of Toyota’s firmware and NASA’s review of the same.  However, of greater significance is what they are not able to say about unintended acceleration.  It appears that NASA did not follow a number of best practices for reviewing embedded software source code that might have identified useful evidence.  In brief, NASA failed to find a firmware cause of unintended acceleration—but their review also fails to rule out firmware causes entirely.  </p>
<p>This article describes a set of five recommended practices for firmware source code review that are based on my experiences as both an embedded software developer and as an expert witness.  Each of the recommendations will consider what more could have been done to determine whether Toyota’s ETCS firmware played a role in any of the unintended acceleration.  The five recommended practices are: (1) ask for the bug list; (2) insist on an executable; (3) reproduce the development environment; (4) try for the version control repository; and (5) remember the hardware.  The relative value and importance of the individual practices will vary by type of litigation, so the recommendations are presented in the order that is most readable.</p>
<p><strong>Ask for the Bug List</strong></p>
<p>Any serious litigation involving embedded software will require an expert review of the source code.  The source code should be requested early in the process of discovery.  Owners of source code tend to strenuously resist such requests but procedures limiting access to the source code to only certain named and pre-approved experts and only under physical security (often a non-networked computer with no removable storage in a locked room) tend to be agreed upon or ordered by a judge.</p>
<p>Software development organizations commonly keep additional records that may prove more important or useful than a mere copy of the source code.  Any reasonably thorough software team will maintain a bug list (a.k.a., defect database) describing most or all of the problems observed in the software along with the current status of each (e.g., “fixed in v2.2” or “still under investigation”).  The list of bugs fixed and known—or the company’s lack of such a list—is germane to issues of software quality.  Thus the bug list should be routinely requested and supplied in discovery.  (It is also recommended that a request be made for copies of software design documents, coding standards, build logs and associated tool outputs, testing logs, and other artifacts of the embedded software design and development process.)</p>
<p>Very nearly every piece of software ever written has defects, both known and unknown.  Thus the bug list provides helpful guidance to a reviewer of the source code.  Often, for example, bugs cluster in specific source files in need of major rework.  To ignore the company’s own records of known bugs, as the NASA reviewers apparently did, is to examine a constitution without considering the historical reasons for the adoption of each section and amendment.  Indeed, a simple search of the text in Toyota’s bug list for the terms “stuck” and “fuel valve” might yet provide some useful information about unintended acceleration.</p>
<p><strong>Insist on an Executable</strong></p>
<p>In software parlance, the “executable” program is the binary version of the program that’s actually executed in the product.  The machine-readable executable is constructed from a set of human-readable source code files using software build tools such as compilers and linkers.  It is important to recognize that one set of source code files may be capable of producing multiple executables, based on tool configuration and options.</p>
<p>Though not human-readable, an executable program may provide valuable information to an expert reviewer.  For example, one common technique is to extract the human-readable “strings” within the executable.  The strings in an executable program include information such as on-screen messages to the user (e.g., “Press the ‘?’ button for help.”).  In a copyright infringement case in which I once consulted several strings in the defendant’s executable helpfully contained a phrase similar to “Copyright Plaintiff”!  You may not be so lucky, but isn’t it worth a try?</p>
<p>It may also be possible to reverse engineer or disassemble an executable file into a more human-readable form.  Disassembly could be important in cases of alleged patent infringement, for example, where what looks like an infringement of a method claim in the source code might be unused code or not actually part of the executable in the product as used by customers.</p>
<p>Sometimes it is easy to extract the executable directly from the product for expert examination—in which case the expert should engage in this step.  For instance, software running on Microsoft Windows consists of an executable file with the extension .EXE, which is easily extracted.  However, the executable programs in most embedded systems are difficult, at best, to extract.   (Note that if it is possible for the expert to extract an executable from one or more exemplars of the product, an automated comparison should always be made between the installed and produced binary files.  You never know what you may find and any difference could have important implications for the facts underlying the case.)  Extraction of Toyota’s ETCS firmware might not be physically possible.  Thus the legal team should insist on production of the executable(s) actually used by the relevant customers.</p>
<p><strong>Reproduce the Development Environment</strong></p>
<p>The dichotomy between source code and executable code and the inability of even most software experts to make much sense of binary code can create problems in the factual landscape of litigation.  For example, suppose that the source code produced by Toyota was inadvertently incomplete in that it was missing two or three source code files.  Even an expert reviewer looking at the source code might not know about the absent files.  For example, if the bug the expert is looking for is related to fuel valve control and the code related to that subject doesn’t reference the missing files, the reviewer may not notice their absence.  No expert can spot a bug in a missing file.</p>
<p>Fortunately, there is a reliable way for an expert to confirm that she has been provided with all of the source code.  The objective is simply stated: reproduce the software build tools setup and compile the produced source code. To do this it is necessary to have a copy of the development team’s detailed build settings, such as make files, preprocessor defines, and linker control files.  If the build process completes and produces an executable, it is certain the other party has provided a complete copy of the source code.  (Further additional technical details include the need to start with a “clean” set of files that contains no object files or libraries.  It may also be necessary to obtain third-party header files or libraries.)  </p>
<p>Furthermore, if the executable as built matches the executable as produced (actually, ideally, the executable as extracted from the product) bit by binary bit, it is certain that the other party has provided a true and correct version of the source code.  Unfortunately, trying to prove this part may take longer than just completing a build; the build could fail to produce the desired proof for a variety of reasons.  The details here get complicated: to get exactly the same output executable, it is necessary to use all of the following: precisely the same version of the compiler, linker, and each other build tool as the original developers; precisely the same configuration of each of those tools; and precisely the same set of build instructions.  Even a slight variation in just one of these details will generally produce an executable that doesn’t match the other binary image at all—just as the wrong version of the source code would.</p>
<p><strong>Try for the Version Control Repository</strong></p>
<p>Embedded software source code is never created in an instant.  All software is developed one layer at a time over a period of months or years in the same way that a bridge and the attached roadways exist in numerous interim configurations during their construction.  The version control repository for a software program is like a series of time-lapse photos tracking the day-by-day changes in the construction of the bridge.  But there is one considerable difference: it is possible to go back to one of those source code snapshots and rebuild the executable of that particular version.  This becomes critically important when multiple software versions will be deployed over a number of years.  In the automotive industry, for example, it must be possible to give one customer a bug fix for his v2.1 firmware while also working on the new v3.0 firmware to be released the following model year.</p>
<p>Consider, for the sake of discussion, that the executable version of Toyota’s ETCS v2.1 firmware that was installed in the factory in one million cars around the world had an undiscovered bug that could result in unintended acceleration under certain rare operating conditions.  Now further suppose that this bug was (perhaps unintentionally) eliminated in the v2.2 source code, from which a subsequent executable was created and installed at the factory into millions more cars with the same model names—and also as an upgrade into some of the original one million cars as they visited dealers for scheduled maintenance.  In this scenario, an examination of the v2.2 source code proves nothing about the safety of the hundreds of thousands of cars still with v2.1 under the hood.</p>
<p>Gaining access to the entire version control repository containing all of the past versions of a company’s firmware source code through discovery may be out of the question.  For example, a judge in a source code copyright and trade secrets case I consulted in would only allow the plaintiff to choose one calendar date and to then receive a snapshot of the defendant’s source code from that specific date.  If the plaintiff was lucky it would find evidence of their proprietary code in that specific snapshot.  But the observed absence of their proprietary code from that one specific snapshot doesn’t prove the alleged theft didn’t happen earlier or later in time.</p>
<p>There are some problems with examination of an entire version control repository.  It may be difficult to make sense of the repository’s structure.  Or, if the structure can be understood, it might take many times as long to perform a thorough review of the major and minor versions of the various source code files as it would to just review one snapshot in time.  At first glance, many of those files would appear the same or similar in every version—but subtle differences could be important to making a case.  To really be productive with that volume of code, it may be necessary to obtain a chronological schedule provided by a bug list and/or other production documents describing the source code at various points in time.</p>
<p><strong>Remember the Hardware</strong></p>
<p>Embedded software is always written with the hardware platform in mind and should be reviewed in the same manner.  For example, it is only possible to properly reverse engineer or disassemble an executable program once the specific microprocessor (e.g., Pentium, PowerPC, or ARM) is known.  But knowing the processor is just the beginning, because the hardware and software are intertwined in complex ways in such embedded systems.</p>
<p>Only one or more features of the hardware are enabled or active when the hardware is in a particular configuration.  For instance, consider an embedded system with a network interface, such as an Ethernet jack that is only powered when a cable is mechanically inserted.  Some or all of the software required to send and receive messages over this network may be not be executed until a cable is inserted.  A proper analysis of the software needs to keep hardware-software interactions like this in perspective.  Ideally, testing of the firmware should be done on the hardware as configured in exemplars of the units at issue—so it is useful to ask for hardware during discovery, if you are not able to acquire exemplars in other ways.  It is not clear from the redacted reports if NHTSA’s testing of certain Toyota Camrys was done using the same firmware version on exactly the same hardware as the owners who experienced unintended acceleration.  Hardware interactions can be one of the most important considerations of all when analyzing embedded software.</p>
<p>Sometimes a bug is not visible in the software itself.  Such a bug may result from a combination of hardware and software behaviors or multi-processor interactions.  For example, one motor control system I’m familiar with had a dangerous <a href="/barr-code/2010/02/firmware-specific-bug-1-race-condition/">race condition</a>.   The bug, though, was the result of an unforeseen mismatch between the hardware reaction time and the software reaction time around a sequence of commands to the motor.</p>
<p><strong>Additional Analysis Required</strong></p>
<p>As you can see, the review of embedded software can be complicated.  This is partly because the hardware of each embedded system is unique.  In addition, the system as a whole generally involves complex interactions between hardware, software, and user.  An expert in embedded software should typically have a degree in electrical engineering, computer engineering, or computer science plus years of relevant experience designing embedded systems and programming in the relevant language(s).</p>
<p>The five best practices presented here are meant to establish the critical importance of making certain specific requests early in the legal discovery process.  They are by no means the only types of analysis that should be performed on the source code.  For example, in any case involving the quality or reliability of embedded software, the source code should be tested via static analysis tools.  This and other types of technical analysis should be well understood by any expert witness or litigation consultant with the proper background.</p>
<p>In the case of Toyota’s unintended acceleration issues, I hope that expert review in the class action litigation against Toyota will include these and other additional types of analysis to identify all of the potential causes and determine if embedded software played any role. Though government funds for analysis by NASA are understandably limited, it is suggested that transportation safety organizations, such as NHTSA, should establish rules that ensure that future investigations are more thorough and that safety-related technical findings in litigation cannot be hidden behind the veil of secrecy of a settlement agreement.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/barr-code/2011/09/firmware-forensics-best-practices-in-embedded-software-source-code-discovery/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t Follow These 5 Dangerous Coding Standard Rules</title>
		<link>http://embeddedgurus.com/barr-code/2011/08/dont-follow-these-5-dangerous-coding-standard-rules/</link>
		<comments>http://embeddedgurus.com/barr-code/2011/08/dont-follow-these-5-dangerous-coding-standard-rules/#comments</comments>
		<pubDate>Tue, 30 Aug 2011 19:13:57 +0000</pubDate>
		<dc:creator>Michael Barr</dc:creator>
				<category><![CDATA[Coding Standards]]></category>
		<category><![CDATA[Efficient C/C++]]></category>
		<category><![CDATA[Firmware Bugs]]></category>
		<category><![CDATA[bugs]]></category>
		<category><![CDATA[embedded]]></category>
		<category><![CDATA[firmware]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[safety]]></category>
		<category><![CDATA[standards]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/barr-code/?p=670</guid>
		<description><![CDATA[Over the summer I happened across a brief blog post by another firmware developer in which he presented ten C coding rules for better embedded C code. I had an immediate strong negative reaction to half of his rules and later came to dislike a few more, so I&#8217;m going to describe what I don&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>Over the summer I happened across a brief blog post by another firmware developer in which he presented ten C coding rules for better embedded C code.  I had an immediate strong negative reaction to half of his rules and later came to dislike a few more, so I&#8217;m going to describe what I don&#8217;t like about each.  I&#8217;ll refer to this author as <em>BadAdvice</em>.  I hope that if you have followed rules like the five below my comments will persuade you to move away from those toward <a href="http://netrino.com/coding-standard">a set of embedded C coding rules that keep bugs out</a>.  If you disagree, please start a constructive discussion in the comments.</p>
<p><strong>Bad Rule #1: Do not divide; use right shift.</strong></p>
<p>As worded, the above rule is way too broad.  It&#8217;s not possible to always avoid C&#8217;s division operator.  First of all, right shifting only works as a substitute for division when it is integer division and the denominator is a power of two (e.g., right shift by one bit to divide by 2, two bits to divide by 4, etc.).  But I&#8217;ll give BadAdvice the benefit of the doubt and assume that he meant to say you should &#8220;use right shift as a substitute for division whenever possible&#8221;.</p>
<p>For his example, BadAdvice shows code to compute an average over 16 integer data samples, which are accumulated into a variable <code>sum</code>, during the first 16 iterations of a loop.  On the 17th iteration, the average is computed by right shifting sum by 4 bits (i.e., dividing by 16).  Perhaps the worst thing about this example code is how much it is tied a pair of <code>#define</code>s for the magic numbers 16 and 4.  A simple but likely refactoring to average over 15 instead of 16 samples would break the entire example&#8211;you&#8217;d have to change from the right shift to a divide proper.  It&#8217;s also easy to imagine someone changing <code>AVG_COUNT</code> from 16 to 15 without realizing about the shift; and if you didn&#8217;t change this, you&#8217;d get a bug in that the sum of 15 samples would still be right shifted by 4 bits.</p>
<p><em>Better Rule: Shift bits when you mean to shift bits and divide when you mean to divide.</em></p>
<p>There are many sources of bugs in software programs.  The original programmer creates some bugs.  Other bugs result from misunderstandings by those who later maintain, extend, port, and/or reuse the code.  Thus coding rules should emphasize readability and portability most highly.  The choice to deviate from a good coding rule in favor of efficiency should be taken only within a subset of the code.  Unless there is a very specific function or construct that needs to be hand optimized, efficiency concerns should be left to the compiler.</p>
<p><strong>Bad Rule #2: Use variable types in relation to the maximum value that variable may take.</strong></p>
<p>BadAdvice gives the example of a variable named <code>seconds</code>, which holds integer values from 0 to 59.  And he shows choosing <code>char</code> for the type over <code>int</code>.  His stated goal is to reduce memory use.</p>
<p>In principle, I agree with the underlying practices of not always declaring variables <code>int</code> and choosing the type (and signedness) based on the maximum range of values.  However, I think it essential that any practice like this be matched with a corresponding practice of always declaring specifically sized variables using <a href="http://www.netrino.com/Embedded-Systems/How-To/C-Fixed-Width-Integers-C99">C99&#8242;s portable fixed-width integer types</a>.</p>
<p>It is impossible to understand the reasoning of the original programmer from <code>unsigned char seconds;</code>.  Did he choose <code>char</code> because it is big enough or for some other reason?  (Remember too that a plain <code>char</code> may be naturally signed or unsigned, depending on the compiler.  Perhaps the original programmer even knows his compiler&#8217;s <code>char</code>s are default <code>unsigned</code> and omits that keyword.)  The intent behind variables declared <code>short</code> and <code>long</code> is at least as difficult to decipher.  A <code>short</code> integer may be 16-bits or 32-bits (or something else), depending on the compiler; a width the original programmer may have (or may not have) relied upon.</p>
<p><em>Better Rule: Whenever the width of an integer matters, use C99&#8242;s portable fixed-width integer types.</em></p>
<p>A variable declared <code>uint16_t</code> leaves no doubt about the original intent as it is very clearly meant to be a container for an unsigned integer value no wider than 16-bits.  This type selection adds new and useful information to the source code and makes programs both more readable and more portable.  Now that C99 has standardized the names of fixed-width integer types, declarations involving <code>short</code> and <code>long</code> should no longer be used.  Even <code>char</code> should only be used for actual character (i.e., ASCII) data.  (Of course, there may still be <code>int</code> variables around, where size does not matter, such as in loop counters.)</p>
<p><strong>Bad Rule #3: Avoid &gt;= and use &lt;.</strong></p>
<p>As worded above, I can&#8217;t say I understand this rule or its goal sufficiently, but to illustrate it BadAdvice gives the specific example of an if-else if wherein he recommends <code>if (speed &lt; 100) ... else if (speed &gt; 99)</code> instead of <code>if (speed &lt; 100) ... else if (speed &gt;= 100)</code>.  Say what?  First of all, why not just use else for that specific scenario, as <code>speed</code> must be either below 100 or 100 or above.  </p>
<p>Even if we assume we need to test for less than 100 first and then for greater than or equal to 100 second, why would anyone in their right mind prefer to use greater than 99?  That would be confusing to any reader of the code.  To me it reads like a bug and I need to keep going back over it to find the logical problem with the apparently mismatched range checks.  Additionally, I believe that BadAdvice&#8217;s terse rationale that &#8220;Benefits: Lesser Code&#8221; is simply untrue. Any half decent compiler should be able to optimize either comparison as needed for the underlying processor.</p>
<p><em>Better Rule: Use whatever comparison operator is easiest to read in a given situation.</em></p>
<p>One of the very best things any embedded programmer can do is to make their code as readable as possible to as broad an audience as possible.  That way another programmer who needs to modify your code, a peer doing code review to help you find bugs, or even you years later, will find the code hard to misinterpret.</p>
<p><strong>Bad Rule #4: Avoid variable initialization while defining.</strong></p>
<p>BadAdvice says that following the above rule will make initialization faster.  He gives the example of <code>unsigned char MyVariable = 100;</code> (not preferred) vs:</p>
<p><code><br />
#define INITIAL_VALUE 100<br />
unsigned char MyVariable;<br />
// Before entering forever loop in main<br />
MyVariable = INITIAL_VALUE<br />
</code></p>
<p>Though it&#8217;s unclear from the above, let&#8217;s assume that <code>MyVariable</code> is a local stack variable.  (It could also be global, the way his pseudo code is written.)  I don&#8217;t think there should be a (portably) noticeable efficiency gain from switching to the latter.  And I do think that following this rule creates an opening to forget to do the initialization or to unintentionally place the initialization code within a conditional clause.</p>
<p><em>Better Rule: Initialize every variable as soon as you know the initial value.</em></p>
<p>I&#8217;d much rather see every variable initialized on creation with perhaps the creation of the variable postponed as long as possible.  If you&#8217;re using a C99 or C++ compiler, you can declare a variable anywhere within the body of a function.</p>
<p><strong>Bad Rule #5: Use #defines for constant numbers.</strong></p>
<p>The example given for this rule is of defining three constant values, including <code>#define ON 1</code> and <code>#define OFF 0</code>.  The rationale is &#8220;Increased convenience of changing values in a single place for the whole file. Provides structure to the code.&#8221;  And I agree that using named constants instead of magic numbers elsewhere in the code is a valuable practice.  However, I think there is an even better way to go about this.</p>
<p><em>Better Rule: Declare constants using <code>const</code> or <code>enum</code>.</em></p>
<p>C&#8217;s <code>const</code> keyword can be used to declare a variable of any type as unable to be changed at run-time.  This is a preferable way of declaring constants, as they are in this way given a type that can be used to make comparisons properly and enabling them to be type-checked by the compiler if they are passed as parameters to function calls.  Enumeration sets may be used instead for integer constants that come in groups, such as <code>enum { OFF = 0, ON };</code>.</p>
<p><strong>Final Thoughts</strong></p>
<p>There are two scary things about these and a few of the other rules on BadAdvice&#8217;s blog.  First, is that they are out there on the Internet to be found with a search for embedded C coding rules.  Second, is that BadAdvice&#8217;s bio says he works on medical device design.  I&#8217;m not sure which is worse.  But I do hope the above reasoning and proposed better rules gets you thinking about how to develop more reliable embedded software with fewer bugs. </p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/barr-code/2011/08/dont-follow-these-5-dangerous-coding-standard-rules/feed/</wfw:commentRss>
		<slash:comments>57</slash:comments>
		</item>
		<item>
		<title>How to Enforce Coding Standards Using PC-Lint</title>
		<link>http://embeddedgurus.com/barr-code/2011/06/how-to-enforce-coding-standards-using-pc-lint/</link>
		<comments>http://embeddedgurus.com/barr-code/2011/06/how-to-enforce-coding-standards-using-pc-lint/#comments</comments>
		<pubDate>Fri, 17 Jun 2011 01:39:53 +0000</pubDate>
		<dc:creator>Michael Barr</dc:creator>
				<category><![CDATA[Coding Standards]]></category>
		<category><![CDATA[embedded]]></category>
		<category><![CDATA[firmware]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[standards]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/barr-code/?p=652</guid>
		<description><![CDATA[In an earlier blog post, I introduced the concept of automatic enforcement of coding standards by stating that: Enforcement of coding standards too often depends on programmers already under deadline pressure to be disciplined while they code and/or to make time to perform peer code reviews. &#8230; To ensure your selected coding standard is followed, [...]]]></description>
			<content:encoded><![CDATA[<p>In an <a href="/barr-code/2011/05/how-to-enforce-coding-standards-automatically/">earlier blog post</a>, I introduced the concept of automatic enforcement of coding standards by stating that:</p>
<blockquote><p>Enforcement of coding standards too often depends on programmers already under deadline pressure to be disciplined while they code and/or to make time to perform peer code reviews. &#8230; To ensure your selected coding standard is followed, and thus effective, your team should find as many automated ways to enforce as many of its rules as possible. And you should make such automated rule checking part of the everyday software build process.</p></blockquote>
<p>One of the tools we have found to be indispensible for this purpose is <a href="http://www.gimpel.com">Gimpel Software</a>&#8216;s <a href="http://www.gimpel.com/html/pcl.htm">PC-Lint</a> (and the multi-platform <a href="http://www.gimpel.com/html/flex.htm">FlexeLint</a>). At just a few hundred dollars per seat, PC-Lint happens to also be one of the least expensive tools we own and thus a source of tremendous value to our team.</p>
<p>The following options can be set (in version 9.00) to assist in the automated enforcement of the identified rules from the <a href="http://netrino.com/Coding-Standard">Embedded C Coding Standard</a>.</p>
<p>&nbsp;</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="257" valign="top"><strong>Rule(s)</strong></td>
<td width="457" valign="top"><strong>Tool Configuration Notes</strong></td>
</tr>
<tr>
<td width="257" valign="top">Which C (1.1)</td>
<td width="457" valign="top">975 (unrecognized pragma)</p>
<p>+pragma(name, action)</p>
<p>-pragma(name)</td>
</tr>
<tr>
<td width="257" valign="top">Braces (1.3)</td>
<td width="457" valign="top">PC-Lint can help identify missing braces   through indentation checking:</p>
<p>525 (negative indentation)</p>
<p>539 (did not expect positive indentation)</p>
<p>725 (expected positive indentation)</td>
</tr>
<tr>
<td width="257" valign="top">Parentheses (1.4)</td>
<td width="457" valign="top">665 (Unparenthesized parameter in macro is   passed an expression)</p>
<p>773 (Expression-like macro not parenthesized)</p>
<p>821 (Right hand side of assignment not parenthesized)</p>
<p>834 (Operator ‘<em>Name</em>’ followed by operator ‘<em>Name</em>’ is   confusing. Use parentheses)</p>
<p>973 (Unary operator in macro &#8216;<em>Symbol</em>&#8216; not parenthesized)</td>
</tr>
<tr>
<td width="257" valign="top">Casts (1.6)</td>
<td width="457" valign="top">507, 511, 519 (Size incompatibility in   cast)</p>
<p>549, 571, 611 (suspicious cast)</p>
<p>643 (loss of precision in pointer cast)</p>
<p>680 (suspicious truncation in arithmetic expression converted to   pointer)</p>
<p>688 (cast used within preprocessor conditional statement)</p>
<p>740, 741 (unusual pointer cast)</p>
<p>920 (cast from &#8216;type&#8217; to &#8216;void&#8217;)</p>
<p>921-930 (cast from &#8216;type&#8217; to &#8216;type&#8217;)</p>
<p>1773 (attempt to cast away const or volatile)</td>
</tr>
<tr>
<td width="257" valign="top">Keywords to avoid (1.7)</td>
<td width="457" valign="top">-deprecate( keyword, auto, violates coding   standard )</p>
<p>-deprecate( keyword, register, violates coding standard )</p>
<p>-deprecate( keyword, goto, violates coding standard )</p>
<p>-deprecate( keyword, continue, violates coding standard )</td>
</tr>
<tr>
<td width="257" valign="top">Keywords to Frequent (1.8)</td>
<td width="457" valign="top">818 (Pointer parameter could be declared   ptr to const)</p>
<p>843 (Variable could be declared as const)</p>
<p>844 (Pointer variable could be declared as const)</p>
<p>952 (parameter could be declared as const)</p>
<p>953 (variable could be declared as const)</p>
<p>954 (pointer variable could be declared as pointing to a const)</p>
<p>765 (external symbol could be made static)</td>
</tr>
<tr>
<td width="257" valign="top">Comments, Acceptable Formats (2.1)</td>
<td width="457" valign="top">602 (comment within comment)</td>
</tr>
<tr>
<td width="257" valign="top">Alignment (3.2)</p>
<p>Indentation (3.4)</td>
<td width="457" valign="top">525 (negative indentation)</p>
<p>539 (did not expect positive indentation)</p>
<p>725 (expected positive indentation)</td>
</tr>
<tr>
<td width="257" valign="top">Header Files (4.2)</p>
<p>Source Files (4.3)</td>
<td width="457" valign="top">451 (header file repeatedly included but   does not have a standard include guard)</p>
<p>766 (Include of header file not used in module)</p>
<p>966 (indirectly included header file not used in module)</p>
<p>967 (Header file does not have a standard include guard)</td>
</tr>
<tr>
<td width="257" valign="top">Fixed Width Integers (5.2)</p>
<p>Signed Integers (5.3)</td>
<td width="457" valign="top">569 (Loss of information &#8212; <em>Integer </em>bits to <em>Integer </em>bits)</p>
<p>570 (loss of sign,   assignment being made from a negative constant to an unsigned quantity)</p>
<p>573 (signed-unsigned mix   with divide)</p>
<p>574 (signed-unsigned mix   with relational)</p>
<p>701, 703 (shift left of   signed quantity)</p>
<p>702, 704 (shift right of   signed quantity)</p>
<p>712 (loss of precision,   one type is larger than another type)</p>
<p>713 (loss of precision,   signed to unsigned)</p>
<p>734 (loss of precision,   to a quantity smaller than an int)</td>
</tr>
<tr>
<td width="257" valign="top">Structure and Unions (5.5)</td>
<td width="457" valign="top">38 (Offset of symbol   inconsistent<strong> </strong>&#8211; A member of a class or struct appears in a   different position (offset from the start of the structure) than an earlier   declaration)</p>
<p>39 (Redefinition of symbol conflicts with &#8216;location&#8217; &#8212; a struct or a   union is being redefined)</td>
</tr>
<tr>
<td width="257" valign="top">Function-Like Macros (6.3)</td>
<td width="457" valign="top">665 (Unparenthesized parameter in macro is   passed an expression)</p>
<p>773 (Expression-like macro not parenthesized)</td>
</tr>
<tr>
<td width="257" valign="top">Initialization (7.2)</td>
<td width="457" valign="top">35 (initializer has side-effects)</p>
<p>133 (too many   initializers for aggregate)</p>
<p>134 (missing   initializer)</p>
<p>530, 603 (symbol not   initialized)</p>
<p>540 (excessive size &#8212; a   string initializer required more space than what was allocated)</p>
<p>644 (variable may not   have been initialized)</p>
<p>651 (potentially   confusing initializer)</p>
<p>708 (union   initialization)</p>
<p>727, 728, 729, 738   (symbol not explicitly initialized)</p>
<p>771, 772 (symbol   conceivably not initialized)</p>
<p>784 (nul character   truncated from string &#8212; During initialization of an array with a string   constant there was not enough room to hold the trailing NUL character)</p>
<p>785, 943 (too few   initializers for aggregate)</p>
<p>940 (omitted braces within an initializer)</td>
</tr>
<tr>
<td width="257" valign="top">Switch Statements (8.3)</td>
<td width="457" valign="top">44 (A case<strong> </strong>or default<strong> </strong>statement occurred   outside a switch)</p>
<p>108 (Invalid context<strong> </strong>&#8211; A continue<strong> </strong>or break<strong> </strong>statement was   encountered without an appropriate surrounding context)</p>
<p>137 (constant used twice within switch)</p>
<p>408 (type mismatch with switch expression)</p>
<p>744 (switch statement has no default)</p>
<p>764 (switch statement does not have a case)</p>
<p>825 (control flows into case/default)</td>
</tr>
<tr>
<td width="257" valign="top">Equivalence Tests (8.6)</td>
<td width="457" valign="top">720 (Boolean test of   assignment)</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<p>As a convenience to readers who follow the Netrino <a href="http://netrino.com/Coding-Standard">Embedded C Coding Standard</a> and may like to use RSM and/or PC-Lint to inexpensively and automatically enforce as many of the rules as possible, here are starter configuration files:</p>
<ul>
<li>RSM 7.75 Configuration File: <a href="http://netrino.com/files/rsm_netrino.cfg">rsm_netrino.cfg</a></li>
<li>PC-Lint 9.00 Configuration File: <a href="http://netrino.com/files/pclint_netrino.lnt">pclint_netrino.lnt</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/barr-code/2011/06/how-to-enforce-coding-standards-using-pc-lint/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Is &#8220;(uint16_t) -1&#8243; Portable C Code?</title>
		<link>http://embeddedgurus.com/barr-code/2011/06/is-uint16_t-1-portable-c-code/</link>
		<comments>http://embeddedgurus.com/barr-code/2011/06/is-uint16_t-1-portable-c-code/#comments</comments>
		<pubDate>Thu, 02 Jun 2011 14:59:46 +0000</pubDate>
		<dc:creator>Michael Barr</dc:creator>
				<category><![CDATA[Coding Standards]]></category>
		<category><![CDATA[bugs]]></category>
		<category><![CDATA[embedded]]></category>
		<category><![CDATA[firmware]]></category>
		<category><![CDATA[safety]]></category>
		<category><![CDATA[standards]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/barr-code/?p=641</guid>
		<description><![CDATA[Twice in the last month, Netrino&#8217;s engineers have run across third-party middleware that included a statement of the form: uint16_t variable = (uint16_t) -1; which we take as the author&#8217;s clever way of coding: 0xFFFF We aren&#8217;t naturally inclined to like the obfuscation anyway, but also wondered if &#8220;(uint16_t) -1&#8243; is even portable C code? [...]]]></description>
			<content:encoded><![CDATA[<p>Twice in the last month, Netrino&#8217;s engineers have run across third-party middleware that included a statement of the form:</p>
<p><code>uint16_t variable = (uint16_t) -1;</code></p>
<p>which we take as the author&#8217;s clever way of coding:</p>
<p><code>0xFFFF</code></p>
<p>We aren&#8217;t naturally inclined to like the obfuscation anyway, but also wondered if &#8220;(uint16_t) -1&#8243; is even portable C code? And, supposing it is portable, is there some advantage we don&#8217;t know about that suggests using that form over the hex literal? In the process of researching these issues, I learned a helpful fact or two worth sharing.</p>
<p><strong>Q: Is the result of &#8220;(uint16_t) -1&#8243; guaranteed (by the ISO C standard) to be 0xFFFF?</strong></p>
<p>A: No. But it&#8217;s likely the result will be 0xFFFF on most compilers/processors, since there is really just the one common internal CPU representation of unsigned integers. (For signed integers, most/all processors will use the common 2&#8242;s complement representation underneath&#8211;even though that&#8217;s not required in any way by the language standard.)</p>
<p><strong>Q: Is there any advantage to writing 0xFFFF that way?</strong></p>
<p>A: According to the C99 Standard, all conforming implementations support uint_least16_t, but some may not support <a href="http://www.netrino.com/Embedded-Systems/How-To/C-Fixed-Width-Integers-C99">uint16_t</a>.  If the platform doesn&#8217;t support uint16_t, then &#8220;(uint16_t) -1&#8243; won&#8217;t compile, but 0xFFFF will compile as a value of some larger unsigned integer type (i.e., a bug waiting to happen). </p>
<p>Of course, platforms that don&#8217;t have a fixed-width 16-bit unsigned capability are rare, though it may be that some DSPs fall into that category. The same issue applies to <a href="http://www.netrino.com/Embedded-Systems/How-To/C-Fixed-Width-Integers-C99">uint32_t</a> and 0xFFFFFFFF, of course.  However, I suspect platforms that don&#8217;t have a fixed-width 32-bit unsigned capability are even rarer.</p>
<p><strong>Q: What is the best way to represent the maximum unsigned integer value of a given size?</strong></p>
<p>A: The very best way to represent the maximum values for unsigned (and signed) fixed-width types is to use the constants named in C99&#8242;s stdint.h header file. These are of the form UINTn_MAX (and INTn_MAX) where n is the number of bits (e.g., UINT16_MAX). That is guaranteed to either work or not compile, with no middle ground for bugs.</p>
<p><em>Hat Tip</em>: Many thanks to C and C++ standards guru <a href="http://www.dansaks.com">Dan Saks</a> for help with these answers.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/barr-code/2011/06/is-uint16_t-1-portable-c-code/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>How to Enforce Coding Standards (Automatically)</title>
		<link>http://embeddedgurus.com/barr-code/2011/05/how-to-enforce-coding-standards-automatically/</link>
		<comments>http://embeddedgurus.com/barr-code/2011/05/how-to-enforce-coding-standards-automatically/#comments</comments>
		<pubDate>Wed, 25 May 2011 15:01:34 +0000</pubDate>
		<dc:creator>Michael Barr</dc:creator>
				<category><![CDATA[Coding Standards]]></category>
		<category><![CDATA[Firmware Bugs]]></category>
		<category><![CDATA[embedded]]></category>
		<category><![CDATA[ethics]]></category>
		<category><![CDATA[firmware]]></category>
		<category><![CDATA[safety]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[standards]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/barr-code/?p=623</guid>
		<description><![CDATA[Coding standards can be an important tool in the fight to keep bugs out of embedded software. Unfortunately, too many well-intentioned (especially, corporate) coding standards are ineffective and gather more dust than followers. The hard truth is that enforcement of coding standards too often depends on programmers already under deadline pressure to be disciplined while [...]]]></description>
			<content:encoded><![CDATA[<p>Coding standards can be an important tool in the fight to <a href="http://www.eetimes.com/discussion/other/4008255/Bug-killing-standards-for-firmware-coding">keep bugs out of embedded software</a>. Unfortunately, too many well-intentioned (especially, corporate) coding standards are ineffective and gather more dust than followers. The hard truth is that enforcement of coding standards too often depends on programmers already under deadline pressure to be disciplined while they code and/or to make time to perform peer code reviews. And when peer reviews are done in this scenario, they too easily devolve into compliance discussions that miss the forest for the trees.</p>
<p>To ensure your selected coding standard is followed and thus effective, your team should find as many automated ways to enforce as many of its rules as possible. And you should make such automated rule checking part of the everyday software build process. Ideally, you would also restrict version control check-ins to just code that has passed all the automated checks. No code that breaks any of these automatable rules should be allowed in peer code reviews. That way, code reviewers can focus their limited hours on (1) what the code is supposed to do, (2) whether it does so correctly, and (3) whether the code and comments together are easily understood by all involved.</p>
<p>One of the ways <a href="http://netrino.com">Netrino</a> has found to increase compliance with its <a href="http://netrino.com/Coding-Standard">Embedded C Coding Standard</a> is by configuring static analysis tools we already use to automatically enforce individual rules.</p>
<p>Perhaps the best option is to use a static analysis tool that includes built-in support for your chosen coding standard and/or the ability to be customized to proprietary rules. <a href="http://ldra.com">LDRA</a>&#8216;s static analysis engine, a screenshot from which is shown in the image below, comes preconfigured to check about 80% of the &#8220;<a href="http://www.ldra.com/netrino.asp">NETRINO</a>&#8221; coding standard rules, as well as a number of other widely used coding standards.</p>
<p align="center"><a href="http://www.ldra.com/images/integrations/Figure1_Netrino_300.JPG"><img width="700" src="http://www.ldra.com/images/integrations/Figure1_Netrino_300.JPG" alt="The LDRA Tool Suite Enforces Netrino's Embedded C Coding Standard" /></a></p>
<p>But there are other, less expensive, options available as well. Two tools that we have used are <a href="http://msquaredtechnologies.com/m2rsm/index.htm">RSM</a> and <a href="http://gimpel.com/">PC-Lint</a> from M Squared Technologies and Gimpel Software, respectively. Neither can easily and independently enforce all of our <a href="http://netrino.com/Coding-Standard">Embedded C Coding Standard</a> rules. But used together and properly configured, these two tools offer a low-cost automated coding standards enforcement mechanism that covers a large percentage of the rules.</p>
<p><strong>Configuring RSM</strong></p>
<p>The following <a href="http://msquaredtechnologies.com/m2rsm/index.htm">RSM</a> outputs can be examined and configuration options set (in version 7.75) to assist in the automated enforcement of the identified rules from the <a href="http://netrino.com/Coding-Standard">Embedded C Coding Standard</a>. Pricing for the RSM tool, which runs on Windows, Linux, and other versions of Unix (including Mac OS X), is online at <a href="http://msquaredtechnologies.com/m2rsm/order/">http://msquaredtechnologies.com/m2rsm/order/</a>.</p>
<table>
<tr>
<td><strong>Rule #</strong></td>
<td><strong>Brief Description</strong></td>
<td><strong>Tool Configuration Notes</strong></td>
</tr>
<tr>
<td>1.2.a</td>
<td>Line length limited to 80 characters.</td>
<td>Quality Notice 1</td>
</tr>
<tr>
<td>1.3.a</td>
<td>Braces surround all blocks of code.</td>
<td>Quality Notice 22</td>
</tr>
<tr>
<td>1.7.c</td>
<td>Keyword goto not used.</td>
<td>Quality Notice 9</td>
</tr>
<tr>
<td>1.7.d</td>
<td>Keyword continue not used.</td>
<td>Quality Notice 43</td>
</tr>
<tr>
<td>1.7.e</td>
<td>Keyword break not used outside switch.</td>
<td>Quality Notice 44</td>
</tr>
<tr>
<td>2.2</td>
<td>Location and content of comments.</td>
<td>Quality Notices 17, 20, 51; Options -Es -Ec -EC</td>
</tr>
<tr>
<td>3.1</td>
<td>Use of white space.</td>
<td>Quality Notices 16, 19</td>
</tr>
<tr>
<td>3.5.a</td>
<td>No tab characters.</td>
<td>Quality Notice 30; Option -Dt</td>
</tr>
<tr>
<td>3.6.a</td>
<td>UNIX-style (single-character) linefeeds.</td>
<td>Option -Du</td>
</tr>
<tr>
<td>4.1.a-d</td>
<td>Module naming conventions.</td>
<td>Option -Rn</td>
</tr>
<tr>
<td>4.2.a</td>
<td>Precisely one header file per source file.</td>
<td>Option -Rn</td>
</tr>
<tr>
<td>6.1.a-e</td>
<td>Precisely one header file per source file.</td>
<td>Quality Notice 2; Option -l</td>
</tr>
<tr>
<td>6.2</td>
<td>Cyclomatic complexity of functions.</td>
<td>Quality Notices 10, 18, 27; Option -c</td>
</tr>
<tr>
<td>6.3.b.i-iii</td>
<td>Preprocessor macro safety mechanisms.</td>
<td>Option -m</td>
</tr>
<tr>
<td>8.2.d</td>
<td>If-else if statements always have else.</td>
<td>Quality Notice 22</td>
</tr>
<tr>
<td>8.3.b</td>
<td>Switch statements always have default.</td>
<td>Quality Notices 13, 14, 56</td>
</tr>
<tr>
<td>8.5.a</td>
<td>No unconditional jumps.</td>
<td>Quality Notices 9, 43, 444</td>
</tr>
</table>
<p></p>
<p><strong>Configuring PC-Lint</strong></p>
<p>In a <a href="/barr-code/2011/06/how-to-enforce-coding-standards-using-pc-lint/">future blog post</a>, I will similarly identify <a href="http://gimpel.com">PC-Lint</a> configurations that can be used (in version 9.0) to assist in the automated enforcement of specific rules from the <a href="http://netrino.com/Coding-Standard">Embedded C Coding Standard</a>. Pricing for the PC-Lint tool, which runs on Windows, Linux, and other versions of Unix (including Mac OS X), is online at <a href="http://gimpel.com/html/order.htm">http://gimpel.com/html/order.htm</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/barr-code/2011/05/how-to-enforce-coding-standards-automatically/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Embedded Software Training in a Box</title>
		<link>http://embeddedgurus.com/barr-code/2011/05/embedded-software-training-in-a-box/</link>
		<comments>http://embeddedgurus.com/barr-code/2011/05/embedded-software-training-in-a-box/#comments</comments>
		<pubDate>Fri, 06 May 2011 15:40:02 +0000</pubDate>
		<dc:creator>Michael Barr</dc:creator>
				<category><![CDATA[Coding Standards]]></category>
		<category><![CDATA[Efficient C/C++]]></category>
		<category><![CDATA[Firmware Bugs]]></category>
		<category><![CDATA[RTOS Multithreading]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[bugs]]></category>
		<category><![CDATA[education]]></category>
		<category><![CDATA[embedded]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[realtime]]></category>
		<category><![CDATA[rtos]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/barr-code/?p=614</guid>
		<description><![CDATA[I am beaming with pride. I think we have finally achieved the holy grail of firmware training: Embedded Software Training in a Box. Priced at just $599, the kit includes Everything-You-Need-to-Know-to-Develop-Quality-Reliable-Firmware-in-C, including software for real-time safety-critical systems such as medical devices. In many ways, this product is the culmination of about the last fifteen years [...]]]></description>
			<content:encoded><![CDATA[<p><img align="right" src="http://netrino.com/images/BootCampKit.jpg" alt="Embedded Software Training in a Box" />I am beaming with pride. I think we have finally achieved the holy grail of firmware training: <a href="http://netrino.com/Boot-Camp-Box">Embedded Software Training in a Box</a>. Priced at just $599, the kit includes Everything-You-Need-to-Know-to-Develop-Quality-Reliable-Firmware-in-C, including software for real-time safety-critical systems such as medical devices.</p>
<p>In many ways, this product is the culmination of about the last fifteen years of my career. The knowledge and skills imparted in the kit are drawn from my varied experiences as:</p>
<ul>
<li>An embedded software developer working on real products from consumer electronics to medical devices,</li>
<li>An author (you get copies of <a href="http://netrino.com/Embedded-Systems/Books">all three of my books</a> and the most relevant of <a href="http://netrino.com/Embedded-Systems/How-To">my sixty-odd articles</a>),</li>
<li>As a speaker at the <a href="http://esc.eetimes.com">Embedded Systems Conferences</a> since 1998,</li>
<li>Developer of the <a href="http://netrino.com/Boot-Camp">Embedded Software Boot Camp</a> training materials,</li>
<li>As a former technical editor and editor-in-chief of <a href="http://embedded.com">Embedded Systems Design</a> magazine.</li>
</ul>
<p>This kit also&#8211;at long last&#8211;answers the question I&#8217;ve been receiving from around the world since I first started writing articles and books about embedded programming: &#8220;Where/How can I learn to be a great embedded programmer?&#8221; I believe the answer is now as easy as: &#8220;<a href="http://netrino.com/Boot-Camp-Box">Embedded Software Boot Camp in a Box</a>!&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/barr-code/2011/05/embedded-software-training-in-a-box/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Beer and Boards at ESC Silicon Valley</title>
		<link>http://embeddedgurus.com/barr-code/2011/04/beer-and-boards-at-esc-silicon-valley/</link>
		<comments>http://embeddedgurus.com/barr-code/2011/04/beer-and-boards-at-esc-silicon-valley/#comments</comments>
		<pubDate>Thu, 07 Apr 2011 00:52:05 +0000</pubDate>
		<dc:creator>Michael Barr</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[education]]></category>
		<category><![CDATA[embedded]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[realtime]]></category>
		<category><![CDATA[trends]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/barr-code/?p=609</guid>
		<description><![CDATA[It really looks like I&#8217;ve picked the wrong year to miss ESC Silicon Valley (due to a schedule conflict). (The last time I wasn&#8217;t at ESC, it was 1997 and White Zombie was still together. The first thing I&#8217;d really liked to have seen is Steve Wozniak&#8216;s keynote speech. The second thing I&#8217;m really sad [...]]]></description>
			<content:encoded><![CDATA[<p>It really looks like I&#8217;ve picked the wrong year to miss <a href="http://esc.eetimes.com/siliconvalley/">ESC Silicon Valley</a> (due to a schedule conflict). (The last time I wasn&#8217;t at ESC, it was 1997 and <a href="http://en.wikipedia.org/wiki/White_Zombie_(band)">White Zombie</a> was still together.  The first thing I&#8217;d really liked to have seen is <a href="http://en.wikipedia.org/wiki/Steve_Wozniak">Steve Wozniak</a>&#8216;s keynote speech. The second thing I&#8217;m really sad to miss is the just announced &#8220;Beer and Boards&#8221; party/giveaway.</p>
<p><a href="http://esc.eetimes.com/siliconvalley/boards_beer">Beer and Boards</a> sounds really fun. Here&#8217;s how it works: Every &#8220;All Access&#8221; attendee will get to choose one of three free development kits to take home:</p>
<ul>
<li><a href="http://focus.ti.com/lit/ug/swru270a/swru270a.pdf">TI CC2540DK-MINI Bluetooth Low Energy Kit</a></li>
<li><a href="http://www.element14.com/community/groups/xl-star">XL_STAR MMA8451 Accelerometer Kit</a></li>
<li><a href="http://www.em.avnet.com/ctf_shared/evk/df2df2usa/xlx-s6-lx9-microboard-pb020411.pdf">Xilinx Spartan-6 FPGA LX9 MicroBoard Kit</a></li>
</ul>
<p>Once you select your preferred kit you will receive information on the time and place for the relevant Beer and Boards party, at which you will get to drink free beer at a special meet-and-greet with one of your kit&#8217;s designers to talk about your new kit and its capabilities. Three boards spread out over three days.</p>
<p>Nerds drinking beer! I love it. What will they think of next?</p>
<p>Before you register for this year&#8217;s ESC, be sure to check out my earlier post <a href="http://embeddedgurus.com/barr-code/2011/03/save-big-on-embedded-systems-conference-registration/">Save Big on Embedded Systems Conference Registration</a>. Also, remember to use the promo code BARR20 to save an additional 20% off registration and be entered to win a free seat at a future <a href="http://netrino.com/Boot-Camp">Embedded Software Boot Camp</a> or one of 20 free copies of the <a href="http://netrino.com/Coding-Standard">Embedded C Coding Standard</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/barr-code/2011/04/beer-and-boards-at-esc-silicon-valley/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Save Big on Embedded Systems Conference Registration</title>
		<link>http://embeddedgurus.com/barr-code/2011/03/save-big-on-embedded-systems-conference-registration/</link>
		<comments>http://embeddedgurus.com/barr-code/2011/03/save-big-on-embedded-systems-conference-registration/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 15:55:35 +0000</pubDate>
		<dc:creator>Michael Barr</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[education]]></category>
		<category><![CDATA[embedded]]></category>
		<category><![CDATA[trends]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/barr-code/?p=596</guid>
		<description><![CDATA[The big Embedded Systems Conference 2011 Silicon Valley show opens six weeks from today. This should have been my fourteenth consecutive year as a speaker, but I have an unfortunate calendar conflict that first week of May. Judging from the speaker and course lineups, it looks like it&#8217;s going to be a really great ESC [...]]]></description>
			<content:encoded><![CDATA[<p>The big <a href="http://esc.eetimes.com/siliconvalley/">Embedded Systems Conference 2011 Silicon Valley</a> show opens six weeks from today. This should have been my fourteenth consecutive year as a speaker, but I have an unfortunate calendar conflict that first week of May.</p>
<p>Judging from the speaker and course lineups, it looks like it&#8217;s going to be a really great ESC conference again this year. I strongly encourage you to go if you can. Here are five great reasons to <a href="https://esc.embedded.com/sv/2011">register</a> ASAP:</p>
<p>#1: IT&#8217;S CHEAPER THIS WEEK! &#8211; The current early registration pricing expires this Friday, March 25. Registering now will save you $400 off the onsite price of the All Access, 4-Day, and 3-Day Conference Passes or $200 off a 1-Day Pass. (Note there are also <a href="http://esc.eetimes.com/siliconvalley/group_discounts">group discounts</a> available.)</p>
<p>#2: USE PROMO CODE &#8220;BARR20&#8243; TO SAVE AN ADDITIONAL 20%! &#8211; During the registration process there is a place to enter a &#8220;Promo Code&#8221;. No matter what conference package you select, you will receive an additional 20% off the price if you use my special code &#8220;BARR20&#8243;. For the All Access Conference Pass that&#8217;s an additional $479 discount on top of the $400 above. Wow!</p>
<p>#3: GRAND PRIZE: FREE SEAT AT EMBEDDED SOFTWARE BOOT CAMP &#8211; Many people have told me that their company only has a set amount of budget for training and conferences per year and that the Embedded Systems Conference and Embedded Software Boot Camp have to compete for those funds. Well, now you can have your cake and eat it to. One lucky ESC conference attendee will be selected at random to also attend the <a href="http://netrino.com/Boot-Camp">Embedded Software Boot Camp</a> for free (minimum $2,995 value). (To be entered to win, you must use the &#8220;BARR20&#8243; promo code when you register.)</p>
<p>#4: 20 RUNNER-UP PRIZES: EMBEDDED C CODING STANDARD BOOK &#8211; Twenty lucky ESC conference attendees will be selected at random to receive a print copy of the <a href="http://netrino.com/Coding-Standard">Embedded C Coding Standard </a>book. (To be entered to win, you must use the &#8220;BARR20&#8243; promo code when you register.)</p>
<p>#5: THE CONFERENCE CONTENT &#8211; Use the <a href="http://schedule.esc-sv09.techinsightsevents.com/">ESC Schedule Builder</a> to choose from hundreds of training sessions by dozens of expert speakers spread across 25 technical tracks. To this depth and breadth of topics this year are added the <a href="http://www.multicore-expo.com/">6th Annual Multicore Expo</a> and <a href="http://esc.eetimes.com/siliconvalley/ti_tech_days">Texas Instrument&#8217;s Technology Day 2011</a> programs. Wow!</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/barr-code/2011/03/save-big-on-embedded-systems-conference-registration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Do Inline Function Bodies Belong in C Header Files?</title>
		<link>http://embeddedgurus.com/barr-code/2011/03/do-inline-function-bodies-belong-in-c-header-files/</link>
		<comments>http://embeddedgurus.com/barr-code/2011/03/do-inline-function-bodies-belong-in-c-header-files/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 15:03:25 +0000</pubDate>
		<dc:creator>Michael Barr</dc:creator>
				<category><![CDATA[Coding Standards]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[standards]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/barr-code/?p=593</guid>
		<description><![CDATA[Earlier today I received the following question by e-mail from Brazil: I am trying to conform to the rules in your Embedded C Coding Standard book and I just ran into what may be a problem with Rule 6.3.a. Instead of using function-like macros, I&#8217;m using inline functions, as you recommend. However, my compiler (avr-gcc) [...]]]></description>
			<content:encoded><![CDATA[<p>Earlier today I received the following question by e-mail from Brazil:</p>
<blockquote><p>I am trying to conform to the rules in your <a href="http://netrino.com/Coding-Standard">Embedded C Coding Standard</a> book and I just ran into what may be a problem with Rule 6.3.a. Instead of using function-like macros, I&#8217;m using inline functions, as you recommend. However, my compiler (<a href="http://www.avrfreaks.net/wiki/index.php/Documentation:AVR_GCC">avr-gcc</a>) gives an error when I declare a function to be inline at both header and source file. If I put both the inline declaration and function body inside the header file it works fine. This fixes my compiler problem, but isn&#8217;t it a bad practice to place code inside the header file?</p></blockquote>
<p>This is a good question, as it seems at first to be about a conflict between the <a href="http://netrino.com/Coding-Standard">Embedded C Coding Standard</a> and what I refer to as &#8220;Generally Accepted Programming Principles&#8221; (i.e., GAPP not <a href="http://www.fasab.gov/accepted.html">GAAP</a>). It&#8217;s also approaching a frequently asked question, so I thought it&#8217;d also be good to share my e-mailed answer here.</p>
<p>The <a href="http://www.parashift.com/c++-faq-lite/inline-functions.html#faq-9.5">inline keyword</a> is a part of the C++ programming language that was added late to C (in <a href="http://en.wikipedia.org/wiki/C99">C99</a>). In C++, most programs are built out of classes&#8211;with best practice dictating one header file per class definition. Any C++ function may be declared inline. But if the inline function is a public member function (a.k.a., public method) of the class it is necessary to place the code for the inline function inside the header file. This is so that all of the other modules that use the class can see the code they need to have placed inline by the compiler.</p>
<p>Of course, placing the body of any function inside a header file conflicts with GAPP for the C programming language. Here&#8217;s how you should decide what to do:</p>
<p>IF the inline function is a &#8220;helper&#8221; function that&#8217;s only used inside one C module, THEN put it in that .c file only and don&#8217;t mention it in the header file. This is consistent with Rule 4.2.c, which says that &#8220;The header file shall identify only the [functions] &#8230; about which it is strictly necessary for other modules to know.&#8221;</p>
<p>IF, however, the inline function operates on the abstract data type defined in the header file and must be visible to two or more modules, THEN put the body of the inline function inside the header file. There is no rule in the <a href="http://netrino.com/Coding-Standard">Embedded C Coding Standard</a> that strictly prohibits this, so there is no conflict.</p>
<p>See my earlier post <a href="/barr-code/2010/11/what-belongs-in-a-c-h-header-file/">What Belongs in a C .h Header File?</a> for additional suggestions concerning header file contents.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/barr-code/2011/03/do-inline-function-bodies-belong-in-c-header-files/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

