Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

27
Dec

ASSERTions explained

Asserts are assumptions on which program or function is based on. Assertion failure often indicates a possible bug in program.
Programmers inserts asserts to minimize debugging time and with help of asserts there is fair chance of catching bugs easy and in early phase of development.

inbreif, Assert asserts what you want to do is what you do

an example how assert works:
assert(cond) used for checking whether cond is true

x=3;
ASSERT(x > 4);

in the above snippet, assert failure happens as x is 3, but assertion says that it should be greater than 4.

implementation of assert:
As a compiler definition, define ASSERT to be one of:
/DASSERT_LEVEL= ASSERT_FATAL
/DASSERT_LEVEL = ASSERT_WARNING

#define ASSERT_FATAL 1
#define ASSERT_WARN  2
 
#ifndef NDEBUG
  #if   (ASSERT_LEVEL == ASSERT_FATAL)
    #define ASSERT(cond) \
    if( !(cond) ) \
    { \
      do { \
        printf( "Assertion " #cond  " failed:%s[%d]",__FILE__,__LINE__); \
      } while (0); \
      DebugBreak(); \
    }
  #elif (ASSERT_LEVEL == ASSERT_WARNING)
    #define ASSERT(cond) \
    if( !(cond) ) \
    { \
      do { \
        printf( "Assertion " #cond  " failed:%s[%d]",__FILE__,__LINE__); \
      } while (0); \
    }         
  #else
    #define ASSERT(cond) ((void)0)
  #endif
#endif

Difference between error handling and assertions:
Error handling handles routine errors occured while assertions should be used for something which
should never happen until unless there is something wrong fundamentally.

Caution with Assertions:
While disabling assertions, the whole assertion code got deleted from base code, so make sure you do not
use any functional code which is required even if we disable assertion.

ex:

int x=5;
 
func()
{
  x++;
  return x;
}
 
ASSERT(func() == 6)
 
b = x; //disabling assertion makes b value as 5 which ideally should be 6
//using b for something

[tags]ASSERTions explained, assert, assert source code, assert implementation, assert program, assert details[/tags]

Popularity: 3%

27
Dec

Little, big endianess explained — part2

Byte order utililities

Previous post little, big endianness explained deals with theoretical part of endianness, now let us write some utility functions for endainness.

Little Endian To Host: Data we are taking here is little endian data and this program converts little endian to host format. program takes a buffer of data and rearranges it to the native order of the machine. if the native order is little endian no conversion happens.

IsLittleEndian function is already listed in previous post, as it is used here, we?ve copied that function?


bool IsLittleEndian()
{
int x=1 ;
if(*(char *) &x == 1)
return true;
else
return false;
}

int LittleEndianToNative(char *data, unsigned int size)
{
char tmp;
char *sptr, *eptr;

if (!data || !size)
{
return -1;
}

if (IsLittleEndian())
{
return 0;
}

sptr = data;
eptr = data + size - 1;

while (sptr <= eptr-1)
  {
    tmp  = *sptr;
    *sptr++ = *eptr;
    *eptr– = tmp;
  }
  return 0;
}

Host to Little Endian:

Data we are taking here is host or native order data and this program converts host to little endian format. program takes a buffer of data and rearranges it to little endian. if the native order is little endian no conversion happens.

int NativeToLittleEndian(char *data, unsigned int size)
{
//conversion process is same
return LittleEndianToNative(data, size);
}

Big Endian To Host:

Data we are taking here is big endian data and this program converts big endian to native order format. program takes a buffer of data and rearranges it to the native order of the machine. if the native order is big endian no conversion happens.


int BigEndianToNative(char *data, unsigned int size)
{
char tmp;
char *sptr, *eptr;

if (!data || !size) { return -1; }

if (!IsLittleEndian())
{
//no conversion required
return 0;
}
sptr = data;
eptr = data + size - 1;

while (sptr <= eptr-1)
  {
    tmp  = *sptr;
    *sptr++ = *eptr;
    *eptr– = tmp;
  }
  return 0;
}

Host to Big Endian:

Data we are taking here is host or native order data and this program converts host to big endian format. program takes a buffer of data and rearranges it to big endian. if the native order is big endian no conversion happens.

int NativeToBigEndian(char *data, unsigned int size)
{
//conversion process is same
return BigEndianToNative(data, size);
}

Popularity: 9%

27
Dec

UTF8 To Unicode conversion program

  1. int UTF8ToUnicode(const unsigned char *Src, int SrcLen, WCHAR *strDest, int DestLen)
  2. {
  3.   int i=0;
  4.   int outputlen=0;
  5.  
  6.   for (i=0 ; i < SrcLen; )
  7.   {
  8.     if (outputlen >= DestLen)
  9.     {
  10.       //overflow detected
  11.       break;
  12.     }
  13.  
  14.     if ( 0xc0 <= Src[i] )
  15.     {
  16.       Dest[outputlen++] = (WCHAR) ((Src[i] & ~0xc0) << 6 | (Src[i+1] & ~0x80));
  17.       i+=2;
  18.     }
  19.     else if ( 0xe0 <= Src[i] )
  20.     {
  21.       strDest[outputlen++] =(WCHAR) (Src[i] << 12 | (Src[i+1] & 0x3f) << 6 | Src[i+2] & 0x3f);
  22.       i+=3;
  23.     }
  24.     else
  25.     {
  26.       Dest[outputlen++] = (WCHAR) Src[i];
  27.       ++i;
  28.     }
  29.   }
  30.  
  31.   Dest[outputlen] = ‘\0′;
  32.   return outputlen;
  33. }

Popularity: 11%

26
Dec

gettimeofday function for windows

The gettimeofday() function obtains the current time, expressed as seconds and microseconds since the Epoch, and store it in the timeval structure pointed to by tv. As posix says gettimeoday should return zero and should not reserve any value for error, this function returns zero. Here is the program, I?ve given definition struct timezeone and for others I didn?t give as all other data types definitions are available in windows include files itself.

#include < time.h >
 
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
  #define DELTA_EPOCH_IN_MICROSECS  11644473600000000Ui64
#else
  #define DELTA_EPOCH_IN_MICROSECS  11644473600000000ULL
#endif
 
struct timezone 
{
  int  tz_minuteswest; /* minutes W of Greenwich */
  int  tz_dsttime;     /* type of dst correction */
};
 
int gettimeofday(struct timeval *tv, struct timezone *tz)
{
  FILETIME ft;
  unsigned __int64 tmpres = 0;
  static int tzflag;
 
  if (NULL != tv)
  {
    GetSystemTimeAsFileTime(&ft);
 
    tmpres |= ft.dwHighDateTime;
    tmpres <<= 32;
    tmpres |= ft.dwLowDateTime;
 
    /*converting file time to unix epoch*/
    tmpres /= 10;  /*convert into microseconds*/
    tmpres -= DELTA_EPOCH_IN_MICROSECS; 
    tv->tv_sec = (long)(tmpres / 1000000UL);
    tv->tv_usec = (long)(tmpres % 1000000UL);
  }
 
  if (NULL != tz)
  {
    if (!tzflag)
    {
      _tzset();
      tzflag++;
    }
    tz->tz_minuteswest = _timezone / 60;
    tz->tz_dsttime = _daylight;
  }
 
  return 0;
}

usage:

struct timeval now; struct timezone tzone;

gettimeofday(&now, NULL);

gettimeofday(&now, &tzone);

download [gettimeofday.c] program..

Popularity: 74%

26
Dec

Unsigned long to string (ultostr)

Here is the code snippet which does conversion from unsigned long to string/ascii. There are library functions exists (ltostr, itoa) to integer to ascii, but there is no library function exists for unsigned long to ascii/string. ltostr converts signed long to string/ascii.

 

char *ultostr(unsigned long value, char *ptr, int base)
{
  unsigned long t = 0, res = 0;
  unsigned long tmp = value;
  int count = 0;
 
  if (NULL == ptr)
  {
    return NULL;
  }
 
  if (tmp == 0)
  {
    count++;
  }
 
  while(tmp > 0)
  {
    tmp = tmp/base;
    count++;
  }
 
  ptr += count;
 
  *ptr = '\0';
 
  do
  {
    res = value - base * (t = value / base);
    if (res < 10)
    {
      * - - ptr = '0' + res;
    }
    else if ((res >= 10) && (res < 16))
    {
        * - - ptr = 'A' - 10 + res;
    }
  } while ((value = t) != 0);
 
  return(ptr);
}

examples of usage of this function:

char ptr[1024];

ultostr(0xf34C5, ptr, 16);
output: "F34C5"

ultostr(0xf34C5, ptr, 10);
output: "996549"

ultostr(07624, ptr, 8);
output: "7624"

ultostr(07624, ptr, 10);
output: "3988"

download unsigned long to string/ascii/char * (ultostr) [ultostr.c].

Popularity: 22%

24
Dec

Bad Standard APIs

Bad APIs at a glance

strcpy — Too easy to create a buffer overrun
strcat   –  Too easy to create a buffer overrun
strncpy   –  Deceptive. Doesn’t always NUL terminate!
strncat   –  Deceptive. Doesn’t always NUL terminate!
wstrcpy   –  Too easy to create a buffer overrun
wstrcat   –  Too easy to create a buffer overrun
wstrncpy   –  Deceptive. Doesn’t always NUL terminate!
wstrncat   –  Deceptive. Doesn’t always NUL terminate!
sprintf   –  Difficult to avoid buffer overruns with complex format strings
vsprintf  –  Difficult to avoid buffer overruns with complex format strings
wsprintf –  Difficult to avoid buffer overruns with complex format strings
gets   –  Impossible to be safe with gets
strtok   –  Not reentrant

strcpy and friends

 The problem

There is no way to limit the number of characters copied to the
destination buffer. Therefore there is potential for a buffer overflow
when the source has a length greater than that of destination buffer.

In the first code example below, the stack buffer aDest can be
overrun if GetString returns a string longer than 9 characters. If an
attacker can manipulate what GetString returns, perhaps because it is
read out of a network protocol or out of a multimedia file, they can
then manipulate the call stack. In the worst case they can cause a jump
to any address on the device by overwriting the return address that is
stored on the stack.

 

Strncpy, strncat

 strncpy is deceptive

Strncpy will never copy past the end of the buffer given it which is
good. However if the input won’t fit into the buffer it will fill the
buffer and NOT terminate it with a NUL. Your string won’t be what you
think it is and code reading the string will read off the end of the
buffer. std_strlcpy will always NUL terminate whether or not the
destination buffer is large enough.

These comments apply to strncat, wstrncpy and wstrncat too.

gets

Gets has no way to bound how much is writes and worse what it writes
by definition comes from an external source. This is probably the most
dangerous function of the lot. Fortunately it is not widely used.

 

sprintf

 Why sprintf is bad

There is no way to limit the number of characters written to the
destination. Therefore there is potential of buffer overflow when the
resulting output has a length greater than that of destination buffer.

strtok

 Why strtok is bad

This function maintains internal state as a global variable. Because
of that it is not re entrant and not safe in a multi-threaded
environment. Calls to it from one thread to parse one string may
interleave with calls to it from another thread to parse another
string. The result will be that pointers one caller will get a pointer
to the other callers string.

Contemporary code is multi-threaded and thus it is not safe to use this. A bug
caused by the use of this function will be very difficult to track down
because it could be in code completely unrelated to the code
manifesting the problem.

 What to do instead

The function strtok_r is safe because the caller passed storage for
the single pointer it can use to maintain the state it needs. Note that
strtok_r should always be checked for a NULL return value.

Scanf

This discussion applies to sscanf as well as scanf. 

Why scanf is bad

If you use %s with scanf without a field length qualifier there is
no limit on how much data it will write to the buffer for the token
matching %s.

Also, as with any form of printf, the format string should be
constant, or if not constant, unmodifiable from out side the software
or the device. If the attacker can change the format string they can
trivially overrun a buffer. 

Using scanf safely

Always specify a length for %s.

Always make the format string a compile time static const string (just use strings in quote marks like "%d %d").

In general scanf is cumbersome and error prone for parsing input.
Often other parsing approaches are better. If all you need is string to
integer conversion, strtoul is better.

[tags]bad standard apis, bad apis, dangerous standard APIs[/tags]

Popularity: 8%

24
Dec

Buffer Overruns (on Mobile Applications) - Part2

What is a buffer overrun

Simply stated it is running a read or write pointer off the end of the allocated buffer into some other buffer. Usually it occurs because pointer arithmatic is bad worse there’s not buffer length checking at all.

 

Why are they bad

Hackers have figured out many ways to exploit buffer overruns to take over the device. In particular they can be used to load and run hostile code. Since handsets at this point in time still run mostly with a single memory space (little memory protection) a clever attacker can potentiall do the following:

  • brick the phone so it has to go back to a service center
  • break SIM locking
  • take protected content
  • reboot the phone

 

Are some worse than others?

In one sense all buffer overruns are the same and horribly bad because of the single memory space. They all give access to the whole handset.

In another sense they are not the same because some are easier to discover than others. For example well known overruns in open source are the easiest.

In another sense they are not all the same because some are easier to exploit than others. A one byte read overrun is not useful for an attacker. An overrun that smashes the stack that is easy to exploit via SMS is very useful.

[tags]buffer overruns, buffer over runs on mobile applications[/tags]

Popularity: 3%

22
Dec

Bit Twiddling/Manipulation Hacks

Contents

[tags]bit manipulation,byte manipulation, bit manipulation source code, bit manipulation programs[/tags]

Popularity: 10%

22
Dec

Operating Systems and Systems Programming

Most Recent Webcasts

 
 
   
View archived webcast
Wed, 12/06
Assorted Topics and Peer-to-Peer Systems
Mon, 12/04
MIDTERM II
View archived webcast
Wed, 11/29
Protection and Security in Distributed Systems II
All Courses Webcast This Semester

       

Date

Title
View archived webcast
Mon, 08/28 Introduction, What is an Operating System Anyway?
View archived webcast
Wed, 08/30 Operating Systems History, Services, and Structure
Mon, 09/04 CS 162: Lecture 3- Holiday
View archived webcast
Wed, 09/06 Concurrency: Processes and Threads
View archived webcast
Mon, 09/11 Thread Dispatching
View archived webcast
Wed, 09/13 Cooperating Threads
View archived webcast
Mon, 09/18 Synchronization
View archived webcast
Wed, 09/20 Implementing Mutual Exclusion, Semaphores, Monitors, and Condition Variables
View archived webcast
Mon, 09/25 Readers and Writers; Language Support for Synchronization
View archived webcast
Wed, 09/27 Tips for working in a Project Team and Cooperating Processes and Deadlock
View archived webcast
Mon, 10/02 Deadlock (con’t) CPU Scheduling
View archived webcast
Wed, 10/04 Protection: Kernel and Address Spaces
View archived webcast
Mon, 10/09 Address Translation
View archived webcast
Wed, 10/11 MIDTERM I
View archived webcast
Mon, 10/16 Address Translation II, Caching and TLBs
View archived webcast
Wed, 10/18 Caching and TLBs II, Caching and Demand Paging
View archived webcast
Mon, 10/23 Page Allocation and Replacement
View archived webcast
Wed, 10/25 Page Allocation and Replacement II, Survey of Iuput and Output Systems
View archived webcast
Mon, 10/30 File Systems and Disk Management
View archived webcast
Wed, 11/01 Filesystems, Naming, and Directories
View archived webcast
Mon, 11/06 Filesystems (con’t) Distributed Systems
View archived webcast
Wed, 11/08 Networks and Distributed Systems
View archived webcast
Mon, 11/13 Network Protocols
View archived webcast
Wed, 11/15 Network Protocols II
View archived webcast
Mon, 11/20 Network Communication Abstractions/RPC
View archived webcast
Wed, 11/22 Distributed File Systems
View archived webcast
Mon, 11/27 Protection and Security in Distributed Systems I
View archived webcast
Wed, 11/29 Protection and Security in Distributed Systems II
Mon, 12/04 MIDTERM II
View archived webcast
Wed, 12/06 Assorted Topics and Peer-to-Peer Systems

 

[tags]Operating Systems and Systems Programming, system programming, operating systems[/tags]

Popularity: 5%

22
Dec

The Structure and Interpretation of Computer Programs

Most Recent Webcasts

 
 
   
View archived webcast
Fri, 12/08
Review
View archived webcast
Wed, 12/06
Logic Programming 2
View archived webcast
Mon, 12/04
Logic Programming 1
All Courses Webcast This Semester

       

Date

Title
View archived webcast
Mon, 08/28 Functional Programming 1
View archived webcast
Wed, 08/30 Functional Programming 2
View archived webcast
Fri, 09/01 Shell Programing
Mon, 09/04 CS 61A: Lecture 4 - Holiday
View archived webcast
Wed, 09/06 Higher-Order Procedures 1
View archived webcast
Fri, 09/08 Higher-Order Procedures 2
View archived webcast
Mon, 09/11 Recursion and Iteration 1
View archived webcast
Wed, 09/13 Recursion and Iteration 2
View archived webcast
Fri, 09/15 UI (Kay) 1
View archived webcast
Mon, 09/18 UI (Kay) 2
View archived webcast
Wed, 09/20 Prog. Method
View archived webcast
Fri, 09/22 Therac
View archived webcast
Mon, 09/25 Data Abstraction 1
View archived webcast
Wed, 09/27 Data Abstraction 2
View archived webcast
Fri, 09/29 Sequences
View archived webcast
Mon, 10/02 Hierarchical Data 1
View archived webcast
Wed, 10/04 Hierarchical Data 2
View archived webcast
Fri, 10/06 Interpreter
View archived webcast
Mon, 10/09 Generic Operators 1
View archived webcast
Wed, 10/11 Generic Operators 2
View archived webcast
Fri, 10/13 Generic Operators 3
View archived webcast
Mon, 10/16 Object-Oriented Programming 1
View archived webcast
Wed, 10/18 Object-Oriented Programming 2
View archived webcast
Fri, 10/20 Object-Oriented Programming 3
View archived webcast
Mon, 10/23 Assignment, State, Environments 1
View archived webcast
Wed, 10/25 Assignment, State, Environments 2
View archived webcast
Fri, 10/27 Assignment, State, Environments 3
View archived webcast
Mon, 10/30 Mutable Data
View archived webcast
Wed, 11/01 Vectors
View archived webcast
Fri, 11/03 Client or Server
View archived webcast
Mon, 11/06 Concurrency 1
View archived webcast
Wed, 11/08 Concurrency 2
Fri, 11/10 CS 61A: Lecture 33 - Holiday
View archived webcast
Mon, 11/13 Metacircular Eval. 1
View archived webcast
Wed, 11/15 Metacircular Eval. 2
View archived webcast
Fri, 11/17 Analyzing Eval.
View archived webcast
Mon, 11/20 Streams 1
View archived webcast
Wed, 11/22 Streams 2
View archived webcast
Fri, 11/24 CS 61A: Lecture 39 - Holiday
View archived webcast
Mon, 11/27 Lazy Eval. 1
View archived webcast
Wed, 11/29 Lazy Eval. 2
View archived webcast
Fri, 12/01 Nondeterministic Eval.
View archived webcast
Mon, 12/04 Logic Programming 1
View archived webcast
Wed, 12/06 Logic Programming 2
View archived webcast
Fri, 12/08 Review

 

[tags]The Structure and Interpretation of Computer Programs, logic programming, functional programming, programming concepts[/tags]

Popularity: 7%

Next Page »