Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

C/C++

Illusions of Safety


Prevention by Brute Force

The brute-force approach is to always check the size when you're going to write into a buffer. For example, to copy text into a buffer on the stack, you can check the length of the incoming text:

void process(const char *txt)
{
char buf[MAX_LINE];
if (MAX_LINE <= strlen(txt))
   fatal("buffer overrun");
strcpy(buf, txt);
/* continue normal processing */


This copy operation will never overrun the buffer. But for each copy, it makes two passes through the input text: one to get its length, and one to copy it. That's redundant, and if you do it often enough your application will be too slow. In some cases, though, it may be just what's needed.

Another form of this brute-force approach is to replace strcpy with a function that takes a buffer size in addition to the source and destination pointers and stops copying at the end of the buffer. This can be much cheaper than the separate check that I just looked at. The code for strcpy might look like this:

char *strcpy(char *s1, const char *s2)
{
char *res = s1;
while (*s1++ = *s2++)
      ;

return res;
}

To add the internal length check, you need an additional argument that takes the size of the buffer. You then decrement it each time you copy a character and quit if its value reaches 0. While you're at it, change the return type to tell you whether an error occurred:

unsigned safe_strcpy(char *s1, unsigned s1max, const char *s2)
{
while (s1max-- && (*s1++ = *s2++))
	;
return s1max == UINT_MAX ? 1 : 0;
}


Now the calling code looks like this:

void process(const char *txt)
{
char buf[MAX_LINE];
if (safe_strcpy(buf, MAX_LINE, txt))
	fatal("buffer overrun");
/* continue normal processing */

That's shorter than what you had to write before, but writing all those tests and calls to fatal is tedious, and easily forgotten. So the copy function ought to do that for you. And since you're rewriting a standard library function, you ought to try to make it as broadly useful as the standard library function that it replaces. So instead of automatically aborting the application, you'll provide another library function that calls a user-specified handler function when a constraint violation is detected:

unsigned safe_strcpy(char *s1, unsigned s1max, const char *s2)
{
while (s1max-- && (*s1++ = *s2++))
	;
if (s1max == UINT_MAX)
	{
	constraint_error("buffer overrun");
	return 1;
	}
return 0;
}

Now you have the best of both worlds. If a constraint violation occurs and the user-specified constraint handler, called by the function constraint_error, doesn't terminate the program, the new version of safe_strcpy returns an error code. If you know that the constraint handler terminates the program, the calling code looks like this:

void process(const char *txt)
{
char buf[MAX_LINE];
safe_strcpy(buf, MAX_LINE, txt);
/* continue normal processing */


If you know that the constraint handler doesn't terminate the program, or if you don't know what it does, you have to check the value that safe_strcpy returns, so the calling code looks like the previous version.

That's the essence of the approach that TR 24731 takes to providing safer versions of standard C functions. It provides a new set of functions with the suffix "_s"—such as strcpy_s—that take additional arguments giving the sizes of buffers that can't be directly determined by the function. It also provides runtime constraints on those buffer sizes, and if any runtime constraint is violated, the function calls a user-installed handler. If the handler returns, the function returns an error code.

In many cases, the runtime check is trivial, so there is no noticeable overhead from using the TR's version of a C function. And, as we've seen, it's pretty easy to minimize the cost of doing nontrivial runtime checks. Still, overhead is overhead, and if you care about the size and speed of your application, these checks ought to annoy you. Besides, brute force is usually a symptom of design failure.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.