473,795 Members | 2,911 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Auditing C code

I'm working with some legacy C code. Apparently the author didn't know
or care about the difference between int, int16_t, unsigned int, and so
on. He does a lot of bitwise |, &, etc on signed int, without regard to
the size of int and sign flipping. The result is that the code produces
valid results most of the time, and garbage the rest of the time.

I've already lost a few days to auditing the code by hand. Is there
some way to audit the code for a) consistency between passed parameters,
to make sure that all passed parameters are of the same type, and b)
something to warn me if I am doing bitwise |, &, >>, etc on signed ints?
Sep 19 '06 #1
9 1989
CptDondo wrote:
I'm working with some legacy C code. Apparently the author didn't know
or care about the difference between int, int16_t, unsigned int, and so
on. He does a lot of bitwise |, &, etc on signed int, without regard to
the size of int and sign flipping. The result is that the code produces
valid results most of the time, and garbage the rest of the time.

I've already lost a few days to auditing the code by hand. Is there
some way to audit the code for a) consistency between passed parameters,
to make sure that all passed parameters are of the same type,
If you compile the code with a normal compiler using the
maximum warning level you SHOULD see a warning when
the type of the passed parameter differs from the
expected type.
and b)
something to warn me if I am doing bitwise |, &, >>, etc on signed ints?
This will be more difficult since those operations are
well defined for integers. Can you present a specific
case where a problem appears with those operations?
Are you 100% sure that the observed problems come from
those operations?

jacob
Sep 19 '06 #2
jacob navia wrote:
If you compile the code with a normal compiler using the
maximum warning level you SHOULD see a warning when
the type of the passed parameter differs from the
expected type.
OK, thanks. I'll follow up....
>
and b)
>something to warn me if I am doing bitwise |, &, >>, etc on signed ints?


This will be more difficult since those operations are
well defined for integers. Can you present a specific
case where a problem appears with those operations?
Are you 100% sure that the observed problems come from
those operations?
This bit of code would fail occasionally until I changed the int to
unsigned int; now I see I really need to change it uint16_t..... I am
cross-compiling so I am striving for portability across multiple platforms.

unsigned int crc(byte trame[],int n)
{
unsigned int crc,i,j,carry_f lag,a;
crc=0xffff;
for (i=0;i<n;i++)
{
crc=crc^trame[i];
for (j=0;j<8;j++)
{
a=crc;
carry_flag=a&0x 0001;
crc=crc>>1;
if (carry_flag==1)
crc=crc^0xa001;
}
}
trame[n+1]=crc>>8;
trame[n]=crc&255;
return crc;
}
Sep 19 '06 #3
CptDondo wrote:
jacob navia wrote:
>If you compile the code with a normal compiler using the
maximum warning level you SHOULD see a warning when
the type of the passed parameter differs from the
expected type.

OK, thanks. I'll follow up....
>>
and b)
>>something to warn me if I am doing bitwise |, &, >>, etc on signed ints?

This will be more difficult since those operations are
well defined for integers. Can you present a specific
case where a problem appears with those operations?
Are you 100% sure that the observed problems come from
those operations?

This bit of code would fail occasionally until I changed the int to
unsigned int; now I see I really need to change it uint16_t..... I am
cross-compiling so I am striving for portability across multiple platforms.

unsigned int crc(byte trame[],int n)
{
unsigned int crc,i,j,carry_f lag,a;
crc=0xffff;
for (i=0;i<n;i++)
{
crc=crc^trame[i];
for (j=0;j<8;j++)
{
a=crc;
carry_flag=a&0x 0001;
crc=crc>>1;
if (carry_flag==1)
crc=crc^0xa001;
}
}
trame[n+1]=crc>>8;
trame[n]=crc&255;
return crc;
}
This code is exactly the code of the JBUS protocol CRC. In the
original source code we have an UNSIGNED int specified.
Using the published source code for this protocol CRC
in:
http://www.cppfrance.com/codes/CRC-16_31553.aspx
The 0xa001 constant is the polynomial used (x^15+x^13+x^0 or
101000000000000 1
Sep 19 '06 #4
On Tue, 19 Sep 2006 10:22:04 -0700, CptDondo <ya*@NsOeSiPnAe Mr.com>
wrote in comp.lang.c:
I'm working with some legacy C code. Apparently the author didn't know
or care about the difference between int, int16_t, unsigned int, and so
on. He does a lot of bitwise |, &, etc on signed int, without regard to
the size of int and sign flipping. The result is that the code produces
valid results most of the time, and garbage the rest of the time.

I've already lost a few days to auditing the code by hand. Is there
some way to audit the code for a) consistency between passed parameters,
to make sure that all passed parameters are of the same type, and b)
something to warn me if I am doing bitwise |, &, >>, etc on signed ints?
PC-Lint, http://www.gimpel.com, should catch most of this.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Sep 19 '06 #5
jacob navia wrote:
CptDondo wrote:
>I'm working with some legacy C code. Apparently the author didn't
know or care about the difference between int, int16_t, unsigned int,
and so on. He does a lot of bitwise |, &, etc on signed int, without
regard to the size of int and sign flipping. The result is that the
code produces valid results most of the time, and garbage the rest of
the time.

I've already lost a few days to auditing the code by hand. Is there
some way to audit the code for a) consistency between passed
parameters, to make sure that all passed parameters are of the same type,

If you compile the code with a normal compiler using the
maximum warning level you SHOULD see a warning when
the type of the passed parameter differs from the
expected type.
and b)
>something to warn me if I am doing bitwise |, &, >>, etc on signed ints?

This will be more difficult since those operations are
well defined for integers.
You sure about that? From 6.5.2:

Some operators (the unary operator ~, and the binary operators <<, >>,
&, ^, and|, collectively described as bitwise operators) are required to
have operands that have integer type. These operators return values that
depend on the internal representations of integers, and have
implementation-defined and undefined aspects for signed types.

--
Clark S. Cox III
cl*******@gmail .com
Sep 20 '06 #6
jacob navia wrote:
CptDondo wrote:
I'm working with some legacy C code. Apparently the author didn't know
or care about the difference between int, int16_t, unsigned int, and so
on. He does a lot of bitwise |, &, etc on signed int, without regard to
the size of int and sign flipping. The result is that the code produces
valid results most of the time, and garbage the rest of the time.

I've already lost a few days to auditing the code by hand. Is there
some way to audit the code for a) consistency between passed parameters,
to make sure that all passed parameters are of the same type,

If you compile the code with a normal compiler using the
maximum warning level you SHOULD see a warning when
the type of the passed parameter differs from the
expected type.
It depends on the compiler. In fact what I recommend is that you use
the maximum warning level on *multiple* compilers plus lint (PC-Lint
which Jack Klein suggests is good) and even SPlint. Without automated
assistance this can be seriously difficult. I find that satisfying the
maximum warning levels on WATCOM C/C++, gcc, MSVC and Intel C++
simultaneously puts me in a pretty good standing.

Its kind of interesting what each compiler misses that the others
don't. WATCOM is the only compiler I know of that can flip the sign of
char, for example. WATCOM also tries to manifest enum's as char's
sometimes which can sometimes have implications on how enums are cast
and passed around. Microsoft's latest compiler is extremely anal about
potential integer type value truncation. Intel finds some really
obscure problems which include the non-abelian nature of the C language
versus ordinary mathematics (because of the order of side-effects).
gcc balks on a lot of inadvertent "windows-isms", and differs in its
header files for POSIX support from most other C compilers.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Sep 20 '06 #7
we******@gmail. com wrote:
Its kind of interesting what each compiler misses that the others
don't. WATCOM is the only compiler I know of that can flip the sign of
char, for example.
Do you mean making "char" either signed or unsigned at your request?
gcc offers "-fsigned-char" and "-funsigned-char"

Thanks for the splint recommendation, looks handy.

Sep 20 '06 #8
On Tue, 19 Sep 2006 11:06:48 -0700,
CptDondo <ya*@NsOeSiPnAe Mr.comwrote
in Msg. <12************ *@corp.supernew s.com>
for (i=0;i<n;i++)
On highest warning level, gcc would tell you about signed-unsigned
comparison here.

robert
Sep 20 '06 #9
In article <12************ *@corp.supernew s.com>
CptDondo <ya*@NsOeSiPnAe Mr.comwrote:
>This bit of code would fail occasionally until I changed the int to
unsigned int; now I see I really need to change it uint16_t..... I am
cross-compiling so I am striving for portability across multiple platforms.
Except for the use of "int n" (which may or may not be a problem
depending on the range supplied for n), and the question of whether
"byte" is a name for an unsigned type -- if it is "unsigned char"
things should be fine -- this code is itself fine:
>unsigned int crc(byte trame[],int n)
{
unsigned int crc,i,j,carry_f lag,a;
crc=0xffff;
This line might be better-written "crc = 0xffffU;", but it should
assign 65535U to crc in every case. (UINT_MAX is required to be
at least 65535U, although it may be greater.)
for (i=0;i<n;i++)
As someone else pointed out, comparing "unsigned int i" with
(signed) int n is not always wise. Fortunately, in this case,
the one "unsigned" will override so that the overall comparison
will be the same as:

i < (unsigned int)n

which will "do the right thing" in most cases. It would be better
to give both i and n the size_t type, though.
{
crc=crc^trame[i];
As long as both crc and trame[i] are bounded by the range 0..65535,
the result in "crc" at this point will also be in that range. The
initial value of "crc" is 65535 and hence is so bounded; we need
only verify that the rest of the loop maintains this invariant.
for (j=0;j<8;j++)
{
a=crc;
carry_flag=a&0x 0001;
Here "a" will be in the same range that "crc" had earlier, and
carry_flag will be either 0 or 1 depending on the least significant
bit of "a" (which is the same as the LSbit of "crc").
crc=crc>>1;
At this point, crc should be in the range [0..32767]. (The LSbit
has been discarded and the remaining value divided by 2.)
if (carry_flag==1)
crc=crc^0xa001;
}
Since "carry_flag " is either 0 or 1 (depending on the low bit of
"crc" before shifting, as saved in "a", which is not actually
needed -- carry_flag could be set based on "crc" instead of "a"),
the test for "== 1" is unnecessary but harmless. Since crc was
in the range 0..32767 [0..0x7fff], the result of the xor is in
the range [0..0xffff] or [0..65535].

Hence, the loop maintains the invariant that crc is in [0..65535],
and a type that holds at least that range (like "unsigned int")
always suffices.
}
trame[n+1]=crc>>8;
trame[n]=crc&255;
return crc;
}
This suggests that "byte" is a typedef-name for "unsigned char",
so my earlier guess that trame[i] is in the range [0..255] seems
reasonable.

It seems a bit odd to store the crc of the input data in the input
data, as well as returning it. The routine would be more generally
useful if the crc were not stored anywhere but just returned.
Alternatively, the output region could be given as a parameter.
(For source compatibility one might then:

#define COMPAT_CRC(arr, size) new_crc(arr, size, (arr) + (size))

and change calls to crc(x,y) to COMPAT_CRC(x,y) , verifying that
the parameters are OK when macro-ized like this.)

(The routine can be sped up enormously by performing the CRC
calculations one 8-bit-unit at a time, with a 256-entry table, but
that is a separate issue. This also makes the code somewhat harder
to eyeball as "obviously correct" -- here, only the magic xor value
need be inspected to make sure it has the right powers of two in
it.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Sep 24 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2048
by: cxw0106 | last post by:
Is there any way to implement File Auditing in .NET? Thanks.
0
1073
by: William F. O'Neill | last post by:
The gentleman at my company who is responsible for the DB(SQL Server 2000) told me today that he wants to clean out all the unused tables from the DB, and asked if I had any suggestions on how to do this. The first thing I thought of was auditing. Isn't there a capability in SQL Server to list out all the used tables, through the DB auditing capabilities?
4
1361
by: byrocat | last post by:
I know that there are tools like Lumigent, but an wondering about the internal facilities to track events such as table creation, security operations (add login, add role), and such. Under Sybase, there is a set of procedures that permit you to set theses events and to record the results for later extraction and analysis. The Profiler seems to have a lot of the same functionality but this appears to be more along the lines of running...
1
1866
by: Felipe Schnack | last post by:
Hey all! I had an idea to implement a very simple (IMHO) auditing mechanism for an application I'm developing, and thought some people here could give some hints, opinions, etc about it. I was thinking about implementing update and delete triggers for all my tables that I want to be audited, and these triggers would create automatically the auditing message for me. Basically, the update triggers would store the row values in the OLD and NEW...
10
2625
by: Paulo Jan | last post by:
Hi all: Let's say I'm designing a database (Postgres 7.3) with a list of all email accounts in a certain server: CREATE TABLE emails ( clienteid INT4, direccion VARCHAR(512) PRIMARY KEY, login varchar(128) NOT NULL,
0
1521
by: RdR | last post by:
Is it true that DB2 will have an auditing tool to be used for auditing requirements such as Sarbanes-Oxley, etc? Something called Websphere Compliance Auditing? Rumours have it that IBM has a new tool that will get useful data for auditing from the DB2 logs through a log analyzer or log scraping mechanism and feed it to a SQL based database Target, or a Q replication target or use Web Publishing. Any dates announced? Thanks, RdR
4
1441
by: Ed Rauscher | last post by:
Does ayone know what Class is used to enable Registry Auditing? Any help would be great.
14
1894
by: Jonas | last post by:
Hi! I'm developing the middletiers of an ASP.NET application in VB.NET. I've got a business logic layer in which I would like to perform auditing to a database. Instead of making an auditing call in every method of my classes, would it be a workable way to implement IDisposable in the base class to all the BLL-classes and then in the Dispose method to do the audit call? Do I then have to make sure that all uses of the BLL-classes end...
6
5223
by: Rico | last post by:
Hello, I'm creating an audit table and associated triggers to be able to capture any updates and deletes from various tables in the database. I know how to capture the records that have been updated or deleted, but is there any way that I can cycle through a changed record, look at the old vs new values and capture only the values that have changed? To give you a better idea of what I'm trying to do, instead of creating a copy of the...
0
1874
by: dba | last post by:
Hi folks, I would just like to share with you SQL CodeSecure, a newly released database protection and auditing tool from SqlLabs: SQL CodeSecure provides ultimate protection from unauthorized creation, modification and deletion of database objects. It provides flexibility through various protection types and granularity at different protection levels. CodeSecure comes with a full-featured auditing tool that keeps track of all changes...
0
9672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9519
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10215
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10165
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9043
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7541
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.