Showing posts with label software. Show all posts
Showing posts with label software. Show all posts

Wednesday, February 10, 2010

Unpacking 7-bit ASCII

To (finally) complete my series of posts on processing CDMA SMS bearer data and user data fields. In my cases the actual text of the SMS message is packed 7-bit ASCII which corresponds to messages with an encoding flag of ENCODE_7BIT, or 0x10. A packed message then looks something like the following.

|aaaaaaab|bbbbbbcc|cccccddd|ddddeeee|eeefffff|ffgggggg|ghhhhhhh|


Which packs 8 characters (a - h) into 7 octets. To unpack the message we have to pick out each individual character and make it an 8-bit ASCII character.  It helps if we reorganize the data to look at each character individually as follows.

|aaaaaaax| |xxxxxxxx|
|xxxxxxxb| |bbbbbbxx|
|xxxxxxcc| |cccccxxx|
|xxxxxddd| |ddddxxxx|
|xxxxeeee| |eeexxxxx|
|xxxfffff| |ffxxxxxx|
|xxgggggg| |gxxxxxxx|
|xhhhhhhh| |xxxxxxxx|

From this we see that a 7-bit ASCII character can be packed into octets in one of 8 patterns. So to unpack the characters we need to know the current octet, the next octet, and the packing pattern. With that we can apply some bit shifting and bit masks to create an unpacked 8-bit ASCII character. 

I coded this so that the pattern associated to the character 'a' above is pattern 0. And the user data headers cause the SMS message to start at packing pattern 3, which matches the character 'd' above. The routine to decode the SMS message then just becomes a simple loop over the 7-bit ASCII characters while keeping track of the packing pattern.

/* copyright (c) 2010 Steve Hill - All rights reserved */
char*
decode_7bit_ascii( uint_8 *sms, uint_8 len, uint_8 startPat )
{
    uint_8 buffLen = len + 1;
    char *buff     = malloc( sizeof(char) * buffLen );

    memset( buff, 0, sizeof(char) * buffLen );
  
    char   *currChar = buff;        // current char in buff
    char   *lastChar = buff + len;  // last char in buff
    uint_8 *curr     = sms;         // current byte being converted
    uint_8 *next     = curr + 1;    // next byte
    uint_8  currPat  = startPat;    // conversion pattern

    while( currChar < lastChar )
    {
        switch( currPat )
        {
            case 0:     // aaaaaaax xxxxxxxx
                *currChar = ( *curr >> 1 ) & 0x7F;
                break;
            case 1:     // xxxxxxxa aaaaaaxx
                *currChar = (( *curr << 6 ) & 0x40 ) + 
                            (( *next >> 2 ) & 0x3F );
                break;
            case 2:     // xxxxxxaa aaaaaxxx
                *currChar = (( *curr << 5 ) & 0x60 ) + 
                            (( *next >> 3 ) & 0x1F );
                break;
            case 3:     // xxxxxaaa aaaaxxxx
                *currChar = (( *curr << 4 ) & 0x70 ) + 
                            (( *next >> 4 ) & 0x0F );
                break;
            case 4:     // xxxxaaaa aaaxxxxx
                *currChar = (( *curr << 3 ) & 0x78 ) + 
                            (( *next >> 5 ) & 0x07 );
                break;
            case 5:     // xxxaaaaa aaxxxxxx
                *currChar = (( *curr << 2 ) & 0x7C ) + 
                            (( *next >> 6 ) & 0x03 );
                break;
            case 6:     // xxaaaaaa axxxxxxx
                *currChar = (( *curr << 1 ) & 0x7E ) + 
                            (( *next >> 7 ) & 0x01 );
                break;
            case 7:     // xaaaaaaa xxxxxxxx
                *currChar = *curr & 0x7F;
                break;
        }

        currChar++;
        if( currPat ) // stay on current byte if pattern 0
        {
            curr++;
            next++;
        }
        currPat = ++currPat % 8;
    }

    return buff;
}

Saturday, September 20, 2008

Project Backup Script

I am using trac and subversion on my current project. I wrote the following script to do a full backup of trac and subversion and burn the results to a CD.
#!/bin/bash

## Backup subversion and trac and burn the backups to a CD.
##

## applications
##
TRACADMIN=/usr/bin/trac-admin
SVNADMIN=/usr/bin/svnadmin
MKISOFS=/usr/bin/mkisofs
CDRECORD=/usr/bin/cdrecord
DATE=/bin/date

## directory and file paths
##
REPO=/opt/repo/tde
TRACPROJ=/opt/trac
BACKUPDIR=/home/steve/backup
TMPDIR=$$
CDDEVICE=/dev/cdrom
SVNDUMPFILE=$BACKUPDIR/$TMPDIR/temp/svn_dump.txt
DATEFILE=$BACKUPDIR/$TMPDIR/temp/backupdate.txt
LOGFILE=$BACKUPDIR/$TMPDIR/backup.log

if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi

## check for the directory structure and attempt to create if needed
##
if [[ ! -e $BACKUPDIR ]]; then
if ! mkdir $BACKUPDIR; then
exit 1;
fi
fi

if [[ -e $BACKUPDIR/$TMPDIR ]]; then
exit 1; # temp dir already exists
else
if ! mkdir $BACKUPDIR/$TMPDIR; then
exit 1
fi
fi

if ! mkdir $BACKUPDIR/$TMPDIR/iso; then
echo "Failed to create $BACKUPDIR$TMPDIR/iso" >> $LOGFILE;
exit 1;
fi

if ! mkdir $BACKUPDIR/$TMPDIR/temp; then
echo "Failed to create $BACKUPDIR/$TMPDIR/temp" >> $LOGFILE;
exit 1;
fi

## dump subversionto SVNDUMPFILE
##
echo "Dumping subversion" >>$LOGFILE
echo "" >>$LOGFILE
if ! $SVNADMIN dump $REPO > $SVNDUMPFILE 2>>$LOGFILE; then
exit 1;
fi

## hot backup trac
##
echo "" >>$LOGFILE
echo "Performing hotcopy of trac" >> $LOGFILE
echo "" >>$LOGFILE
if ! $TRACADMIN $TRACPROJ hotcopy $BACKUPDIR/$TMPDIR/temp/trac \
1>>$LOGFILE 2>>$LOGFILE; then
exit 1;
fi

## create a file with the date time the backup was done
##
echo `$DATE` > $DATEFILE

## create iso file
## mkisofs does not seem to return a status value so we dont know if it
## actually succeeded.
##
echo "" >>$LOGFILE
echo "Making ISO file" >> $LOGFILE
echo "" >>$LOGFILE
$MKISOFS -fRrlJ -o $BACKUPDIR/$TMPDIR/iso/backup.iso \
$BACKUPDIR/$TMPDIR/temp 1>>$LOGFILE 2>>$LOGFILE

## burn the iso file to a cd
## cdrecord does not seem to return a status value so we dont know if it
## actually succeeded.
##
echo "" >>$LOGFILE
echo "Burning the CD" >> $LOGFILE
echo "" >>$LOGFILE
$CDRECORD -eject speed=24 dev=$CDDEVICE $BACKUPDIR/$TMPDIR/iso/backup.iso \
1>>$LOGFILE 2>>$LOGFILE
#if $CDRECORD speed=24 dev=$CDDEVICE $BACKUPDIR/$TMPDIR/iso/backup.iso \
# 1>>$LOGFILE 2>>$LOGFILE; then
# exit 1;
#fi

## clean up if everything was OK
## since we don't know if mkisofs or cdrecord succeeded do not
## automatically delete the director.
##
#rm -rf $BACKUPDIR/$TMPDIR

The only thing in this script to make note of is the line TMPDIR=$$. The TMPDIR variable is will be the name of the temporary directory to backup to and this is set to the PID of the process which is returned by $$.

To automate the backup I run the script through cron. To setup the cron entry I ran the following commands as root.
[root@myhost]# export EDITOR=vi
[root@myhost]# crontab -e
This will bring up a vi editor with root's crontab file. I then added the following line and saved the file.
59 23 * * 5 /home/steve/bin/sp_backup.sh

The script will now be run every Friday at 11:59 PM. The only problems that I encountered with this script is that neither mkisofs or cdrecord seem to return the UNIX standard value of 0 for success and non-zero for failure. I was going to have the script delete all of the directories and files that were created. But because I can't determine if the script was successful I decided to leave the files in place and to manually ensure that the backup was successful.

Wednesday, August 27, 2008

Processing Apache Access Logs

I need to keep track of who is logging in and using our project's issue tracking and wiki sites. I wanted a simple list of who has logged in on what day. I came up with the following command line to give me what I wanted.
cat access_log | awk '{ if ( $3 !~/-/ ) \
{print $3" " substr($4,2, index($4,":")-2 )} }' \
| sort | uniq
This gives me a list of users and login dates grouped by user as follows.
bambam 25/Aug/2008
barney 25/Aug/2008
barney 26/Aug/2008
fred 25/Aug/2008
fred 26/Aug/2008
fred 27/Aug/2008

Wednesday, June 4, 2008

CDMA SMS User Data

In this post I will describe the decoding of the user data portion of the bearer data field of a CDMA SMS message. See my first post for the structure of the bearer data field.

The User Data subparameter is the portion of the Bearer Data field of a CDMA SMS message that contains the actual message or payload. The user data is made up of an integral number of octets and is 0 padded as needed. The user data subparameter is documented in section 4.5.2 of the IS-637 spec. A PDF of this spec is available on the 3GPP2's web site. A PDF of the spec is also available on the TIA's website. The structure of the user data subparameter is:
  • The subparameter ID of 8 bits which is the constant that identifies the start of this subparameter in the bearer data.
  • The subparamter Len of 8 bits which is the number of octets that make up the value portion of this subparameter.
These two portions of the user data are processed as part of the bearer data. The rest of the user data subparameter is processed separately. The remaining fields of the user data are:
  • The message encoding is a 5 bit value that indicates which encoding scheme was used for the message.
  • The message type is an optional 8 bit value that is used only if the encoding is an IS-91 extended protocol message. See the specification document for the details.
  • The num fields is the number of data elements, of the size specified by the encoding and message type, that the message contains.
  • The chari portion contains the actual text or payload of the message.
  • The final portion the message is 0-7 bits of 0 padding as needed to fill the last octet.
The first step I took in decoding the user data was to write a function that determines the message encoding, the size of the data elements, and the starting byte of the message. To this I first start by defining some constants.
// masks and values for processing the user data fields
//
#define ENCODING_MASK 0xF8
#define ENCODE_OCTET 0X00
#define ENCODE_IS41 0X08
#define ENCODE_7BIT 0X10
#define ENCODE_IA5 0X18

#define MST_BYTE_1_MASK 0xE0
#define MST_BYTE_2_MASK 0x1F
#define NF_BYTE_1_MASK 0xE0
#define NF_BYTE_2_MASK 0x1F

// standard sized type definitions
//
typedef char sint_8;
typedef short sint_16;
typedef int sint_32;
typedef long long sint_64;

typedef unsigned char uint_8;
typedef unsigned short uint_16;
typedef unsigned int uint_32;
typedef unsigned long long uint_64;


Then I write the routine to do the initial processing. This function is writtento call another function that is will handle the actual decoding of the message.
void
decode_user_data( uint_8 *userData, size_t sz )
{
uint_8 *ud = userData; // current element
uint_8 *lud = userData + sz - 1; // last element

uint_8 encoding;
uint_8 mst;
uint_8 numFields;
uint_8 *nextByte = ud + 1;

int i;
for( i = 0; i < sz; i++ ) {
printf("%X\n",userData[i]);
}

mst = 7;
encoding = *ud & ENCODING_MASK;
switch( encoding ) {
case ENCODE_OCTET:
mst = 8;
break;

case ENCODE_IS41:
mst = (( *ud << 5 ) & MST_BYTE_1_MASK ) +
(( *nextByte >> 3 ) & MST_BYTE_2_MASK );
ud++;
nextByte++;
break;

case ENCODE_7BIT:
case ENCODE_IA5:
break;

default:
perror( "unknown paramters\n");
exit(0);
}

numFields = (( *ud << 5 ) & NF_BYTE_1_MASK ) +
(( *nextByte >> 3 ) & NF_BYTE_2_MASK );

printf("numFields: %d\n", numFields );
printf("first byte: %X\n", *nextByte);

switch( encoding ) {
case ENCODE_7BIT: {
char *text = decode_7bit_ascii(
nextByte, numFields, 3 );
printf("The text message is: '%s'\n", text );
free( text );
break;
}

case ENCODE_OCTET:
case ENCODE_IS41:
case ENCODE_IA5:
perror( "requested encoding is not implmented\n");
return;
break;
}
}
The only message type that I am concerned about with this is the 7bit packed ASCII. I will show how to unpack this into a NULL terminated string in another post.

Monday, June 2, 2008

CDMA SMS Bearer Data

In December we tested the system I had been developing at Lucent's lab for the EARS project. This test was to prove the feasibility of sending broadcast SMS messages for emergency alerts. This testing was successful, for the most part. The one snag that was encountered was with the Bearer Data portion of the SMS message. The bearer data carriers the message that will be transmitted to the phone and I naively thought that this was just the text. But it turned out the bearer data is encoded according to the IS-637 specification. With a set of hex dumps from Lucent's internal testing tool I set out to figure out how to decode the bearer data so I could learn how to encoded it. Unfortunately, this line of work was stopped, just when I had almost gotten everything figured out. I couldn't let all of that work go to waste, so I finished up that task on my time and I present it to you now.

The structure of the SMS bearer data field in a CDMA system is defined in section 4.5 of the IS-637 spec. A PDF of this spec is available on the 3GPP2's web site. A PDF of the spec is also available on the TIA's website. In short the bearer data field is a series of fields where each field is an integral number of octets and the fields are 0 padded if necessary. The structure of the bearer data is in the form of parameter ID, parameter length, parameter value. Where parameter ID defines what data is being passed. The parameter length is the number of octets of the parameter value. The value of course is the data that we need to provide.

To decode the bearer data field I wrote a simple routine that loops through the data picking out all of the parameters. We were working with a minimal set of parameters of those available. The first step is to define a set of constants that will be used in the routine.
// bearer data subparameter identifiers
//
#define BD_MESSAGE_ID 0x00
#define BD_USER_DATA 0x01
#define BD_USER_RESP_CD 0x02
#define BD_TIMESTAMP 0x03
#define BD_VALIDITY_PER_ABS 0x04
#define BD_VALIDITY_PER_REL 0x05
#define BD_DEFERRED_DELIVERY_ABS 0x06
#define BD_DEFERRED_DELIVERY_REL 0x07
#define BD_PRIORITY_IND 0x08
#define BD_PRIVACY_IND 0x09
#define BD_REPLY_OPT 0x0A
#define BD_NUM_MSGS 0x0B
#define BD_ALERT_ON_DEL 0x0C
#define BD_LANG_IND 0x0D
#define BD_CALLBACK_NUM 0x0E

// standard sized type definitions
//
typedef char sint_8;
typedef short sint_16;
typedef int sint_32;
typedef long long sint_64;

typedef unsigned char uint_8;
typedef unsigned short uint_16;
typedef unsigned int uint_32;
typedef unsigned long long uint_64;

The routine to decode the bearer data just receives an array of octets (unsigned 8 bit integers) and the length of the array. It loops through the data and writes the received parameters to stdout.
void
decode_bearer_data( uint_8 *bearerData, size_t sz )
{
uint_8 *bd = bearerData; // current element
uint_8 *lbd = bearerData + sz - 1; // last element

uint_32 msgID = 0;
uint_8 userDataLen = 0;
uint_8 *userData = NULL;
uint_8 timestamp[6]; // YY MM DD hh mm ss
uint_8 msgDelivery = 1;

while( bd < lbd ){
switch( *bd ){
case BD_MESSAGE_ID:
if( *(++bd) != 3 ){
perror("message ID Len is not 3\n");
}
msgID = (*(++bd) << 16) + (*(++bd) << 8) +
*(++bd) ;
break;

case BD_USER_DATA:
userDataLen = *(++bd);
userData = bd + 1;
bd += userDataLen;
break;

case BD_TIMESTAMP:
if( *(++bd) != 6 ){
perror("timestamp len is not 6\n");
}
timestamp[0] = *(++bd);
timestamp[1] = *(++bd);
timestamp[2] = *(++bd);
timestamp[3] = *(++bd);
timestamp[4] = *(++bd);
timestamp[5] = *(++bd);
break;

case BD_ALERT_ON_DEL:
msgDelivery = *(++bd);
break;

case BD_USER_RESP_CD:
case BD_VALIDITY_PER_ABS:
case BD_VALIDITY_PER_REL:
case BD_DEFERRED_DELIVERY_ABS:
case BD_DEFERRED_DELIVERY_REL:
case BD_PRIORITY_IND:
case BD_PRIVACY_IND:
case BD_REPLY_OPT:
case BD_NUM_MSGS:
case BD_LANG_IND:
case BD_CALLBACK_NUM:
printf(
"sub parameter is not implemented: %X\n",
*bd);
exit(1);
break;

default:
printf("unknown sub parameter: %X\n", *bd);
exit(1);
}
bd++;
}

printf("BEARER DATA\n");
printf("msgID: %x\n", msgID);
printf("timesamp %x/%x/%x %x:%x:%x\n",
timestamp[0], timestamp[1], timestamp[2],
timestamp[3], timestamp[4], timestamp[5] );
printf("alert on delivery: %x\n", msgDelivery);

printf("\nPROCESSING USER DATA\n\n");
decode_user_data( userData, userDataLen );
}

The User Data field is the bearer data parameter that actually contains the message that we want to send. This field is additionally encoded and may contain data encoded in several different schemes. The text message data I was working with is encoded as packed 7 bit ASCII characters. I will cover this in another post.

Wednesday, April 9, 2008

Parsing Socket Connections With Flex and Bison, part II

I left my first post on parsing socket connections with Flex and Bison with a note about a small memory leak. In this post I will show how to fix this leak.

I used Valgrind, which is a profiling and instrumenting application, to test for memory leaks. The command line I used to run the test server was:
valgrind --suppressions=./mysupps.supp --log-file-exactly=valgrind.log --leak-check=full --show-reachable=yes --leak-resolution=high --num-callers=40 -v ./stubserver

The process as describe in the first post, is that a statically allocated input buffer is populated every time the socket is read. Then yy_scan_string is called with the buffer so flex will start processing that buffer. The yy_scan_string function returns a YY_BUFFER_STATE handle each time it is called, see chapter 12 of the Flex Manual. Each YY_BUFFER_STATE handle consists of 3 allocations totaling 92 bytes of memory. Which can be seen in the Valgrind output file, which has been simplified for space.
searching for pointers to 3 not-freed blocks.
checked 59,892 bytes.

8 bytes in 1 blocks are still reachable in loss record 1 of 3
at 0x4022765: malloc
by 0x804D607: yyalloc
by 0x804D3D1: yy_scan_bytes
by 0x804D3B1: yy_scan_string
by 0x80491FE: yywrap
by 0x804C1ED: yylex
by 0x8049A9C: yyparse
by 0x8048EE2: main

36 bytes in 1 blocks are still reachable in loss record 2 of 3
at 0x4022862: realloc
by 0x804D621: yyrealloc
by 0x804D266: yyensure_buffer_stack
by 0x804CCD2: yy_switch_to_buffer
by 0x804D373: yy_scan_buffer
by 0x804D43C: yy_scan_bytes
by 0x804D3B1: yy_scan_string
by 0x80491FE: yywrap
by 0x804C1ED: yylex
by 0x8049A9C: yyparse
by 0x8048EE2: main

48 bytes in 1 blocks are still reachable in loss record 3 of 3
at 0x4022765: malloc
by 0x804D607: yyalloc
by 0x804D2E9: yy_scan_buffer
by 0x804D43C: yy_scan_bytes
by 0x804D3B1: yy_scan_string
by 0x80491FE: yywrap
by 0x804C1ED: yylex
by 0x8049A9C: yyparse
by 0x8048EE2: main

LEAK SUMMARY:
definitely lost: 0 bytes in 0 blocks.
possibly lost: 0 bytes in 0 blocks.
still reachable: 92 bytes in 3 blocks.
The leak is that unless we recover the memory we leak 92 bytes of memory every time yy_scan_string is called. To recover the memory allocated in the YY_BUFFER_STATE handle Flex provides the function yy_delete_buffer which is described in chapter 12 of the Flex Manual. To prevent the memory leak I created a buffer_state variable, as a void*, which is accessible to all of the parser source. This variable is initialized to NULL at application startup. Then the yy_wrap and parser_init functions call yy_delete_buffer on buffer_state if it is not NULL. And the yy_wrap function must set the buffer_state to NULL after it has been deleted to ensure that it is not deleted twice. Then when the functions set buffer_state to the return value of yy_scan_string. So the process including the memory management, with the changes highlighted, is:
  • The application calls parser_init( connfd, connfd, NULL, NULL )
    • parser_init sets the input and output file descriptors
    • parser_init sets the callbacks to the defaults
    • if buffer_state is not NULL call yy_delete_buffer
    • parser_init initializes the buffer and calls yy_scan_string
  • the application calls yyparse to start the parser
    • flex finds that the input buffer is empty and calls yywrap
      • if buffer_state is not NULL
        • call yy_delete_buffer
        • set buffer_state to NULL
      • yywrap calls the read callback.
        • the read callback reads from the socket and populates the buffer.
      • if data was read
        • yywrap calls yy_scan_string
        • yywrap returns 0
      • else return 1

Friday, March 14, 2008

Binary-Coded Decimal

Introduction

For the EARS project I needed to interface to some custom built transmitter hardware and to telecoms equipment. Both of these systems wanted to receive numeric data in BCD, or Binary-Coded Decimal, format. And if your computer engineering knowledge is as old, rusty, and forgotten as mine, a lot of review is in order.


The Basics

A byte is typically 8 bits and an 8 bit byte is called an octet. A byte can be divided two 4 bit nibbles each of which contains a single hexadecimal digit. Where a hexadecimal digit is a numeric value in base 16 and represents a decimal value of 0 to 15 or 0x0 to 0xf in hex notation, and a byte is represented as two hex digits. A BCD value then is a binary representation of a decimal number. So a BCD representation of the number 129 may be 0x129, which consists of three hex digits one for each decimal digit. The straight binary representation takes only a single byte and would be the hex value 0x81 or the binary value of 10000001. A BCD value may be unpacked in which each decimal digit takes an entire byte, or packed in which each decimal digit takes one nibble. So the unpacked representation of 129 takes 3 bytes and is the value 0x010209. The packed BCD value will only take two bytes and is the value 0x0129.


Converting

The goal is to convert a string of numbers into its BCD representation. It is very easy to convert an ASCII numeric character to its hexadecimal equivalent. From the table of ASCII characters we see that the character '0' is the hex value 0x30 and '9' is the value 0x39. So we just need to subtract 0x30 from each numeric character to get its binary representation. This is of course easy if one uses the appropriate programming language, which in all cases where one needs portability, performance, and maximum bit twiddling functionality, is C.

A simple search with your favorite search engine will result in many pages of information and example code. As most of my work is required to fit in the mythical realm of 5 9s I require a bit more robustness than you will probably find in your search. So my implementation is as follows.


Prototypes

Since I only need to go from a string to BCD I wrote two functions, a2ubcd to convert to unpacked BCD, and a2pbcd to convert to packed BCD. The prototypes of the functions are:


int a2ubcd( const char *str, uint_8 *bcd, size_t sz );
int a2pbcd( const char *str, uint_8 *bcd, size_t sz );

The function comments are basically also identical so following is the comment for the a2ubcd function.

Convert a string to an unpacked BCD array.
Converts the numbers in the string to an unpacked BCD number.

The BCD number is represented as an array of bytes with each byte being one digit. The LSD of the number will be the last element of the array, and if the BCD array is larger than the number of digits the BCD number will be padded with leading 0s.

The string to convert must be a null terminated string with the first character being a number. The conversion will start at the last numeric character found. If the BCD array is not large enough to hold the number it is truncated and an error is returned.

@param str The string to convert to BCD.
@param bcd The array to hold the BCD number.
@param sz The length of bcd.

@returns RET_OK on success.
RET_INVALID_PARAM if str or bcd is NULL, sz <= 0, or if the first character of str is not a numeric. RET_OUT_OF_RANGE if bcd is not large enough to hold the number.

The return values are obviously defined constants. The uint_8 type is an unsigned 8bit integer, which is most likely an unsigned short.


Implementation

As much as I would like to just paste my code in I do not have the rights to do so. Hopefully, the pseudo-coded description will suffice.


function a2ubcd
receives: char *str, uint_8 *bcd, size_t sz
returns: status code

begin
if str or bcd is NULL return invalid param
if sz <= 0 return invalid param
if the first character of str is not a number
return invalid param

set currChar to the first character of str
set nextChar to the second character of str

while nextChar is not NULL and nextChar is a number
set currChar to nextChar
set nextChar to the next character of str
end while

set currDigit to the last element of bcd
while currDigit is an element of bcd
if currChar is an element of str
set currDigit to currChar - 0x30
set currChar to the previous character of str
else
set currDigit to 0
end if
end while

if currChar is an element of str
return out of range
else
return OK
end

The packed BCD conversion function is mostly identical to the unpacked version. The differences being in the while loop that sets the bcd values. The packed version of this loop is.


set currDigit to the last element of bcd

while currDigit is an element of bcd
set highNibble to '0'
set lowNibble to '0'
if currChar is an element of str
set lowNibble to currChar
set currChar to the previous character of str
end if

if currChar is an element of str
set highNibble to currChar
set currChar to the previous character of str
end if

set currDigit to ((highNibble - 0x30) shift left 4) + lowNibble - 0x30
end while

Monday, February 18, 2008

arrrggg -- strlcat II, the solaris files

So after my adventures with strlcat on Friday, I tried out my tests on Solaris today. And sadly I must report that it works the same as on Cygwin and the Mac. Though (fortunately ?) our implementation also works the same. So at least everything fails the specification consistently.

Friday, February 15, 2008

arrrggg -- strlcat

So, I am using strlcat and strlcpy in the project I'm working on. We had to implement our own version of these for Linux since it does not come with them. Well today I had a frustrating day of writing unit tests for this code. I developed the tests in cygwin as I wanted to validate that the native implementation and our implementation work the same. However, I find that cygwin doesn't work according to the available doc. So I went home to try it on my Mac and Linux boxes. So what do I find...

Well lets start with the return values section of Apple's man page:
RETURN VALUES
The strlcpy() and strlcat() functions return the total length of the string they tried to create.

Sun even documents this in better detail. The return value is:
min(sz, strlen(dest)) + strlen(src)

Well that seems simple enough, so what are the results of the tests. The dest in my tests is a 5 character array. I will represent the contents of this as a string literal.

0 == strlcat( "", "", 0 ) yes it does

3 == strlcat( "", "bbb", 0 ) no it returns 0

2 == strlcat( "aa", "", 5 ) yes it does

2 == strlcat( "", "bb", 5 ) yes it does

4 == strlcat( "aa", "bb", 5 ) yes it does

5 == strlcat( "", "abcde", 5 ) no this returns 4

9 == strlcat( "aaaa", "abcde", 5 ) no this returns 4

? == strlcat( "aa", "abcd", 1 )
Well what should the last one return. The case of dest not having a NULL within size characters is an error condition. I think that this should return 5 (size + strlen(src) ). But, no matter what I think, it actually returns 0.

So of course this means that the example that they give in the man page does not work.
if ( strlcpy( pname, dir, sizeof( pname ) ) >= sizeof( pname ) )
goto toolong;

As we can see from my example above, strlcat( "aaaa", "abcde", 5) only returns 4. And last I checked 4 is less than 5.

On Monday I'll have to try this out on Solaris to see what it says.

And don't get me started on the topic of the routines not validating their input. This is supposed to be a standard library, it should not cause a core dump when it receives bad input. Would it be so terribly difficult to return 0 and set errno if you got a NULL pointer?

Monday, February 11, 2008

Parsing Socket Connections With Flex and Bison

I developed a parser for my my current project using Flex and Bison. The development work was done reading from stdin by redirecting files. However, the intent of the system was for it to be run by inetd. Since inetd maps the accepted socket to stdin and stdout for you I didn't really foresee any problems. For testing and demo purposes I wrote a simple network version that accepted a connection and mapped it to stdin and stdout like inetd. However, I found that my program would block every time that it tried to write to the socket.

I traced the problem down to Flex but never came up with a reason for why it was happening. While looking into the problem I found the Lemon parser. The documentation for the Lemon parser mentioned reading from a socket into a buffer and then parsing that buffer. This was the key to solving the problem. My solution may seem to be a little convoluted but seems to work well. So here it is.

First I defined two functions, one that reads from a file descriptor and one that writes. These functions have prototypes of:

int parse_read(int fd, char *buff, int size, int *read )
int parse_write(int fd, char *buff, int size)


I then wrote a parser initialization routine parser_init with a prototype of.

void parser_init( int infd, int outfd, PARSE_READ inFunc, PARSE_WRITE outFunc)

The parser_init function will save the input and output file descriptors, the input and output call back functions, and initialize the buffer. Once this is done it calls the flex function yy_scan_string. I did create two default functions that are used if NULL is passed for the callback parameters. But allowing for different input and output functions to be used makes things like unit testing much easier.

I then wrote a yywrap function in my Bison input file. The yywrap function, which is called when flex's input buffer is empty, calls the read callback function to get more data. If the callback returns 0, success, yywrap calls yy_scan_string again.

This probably does not make too much sense until you see it in action. So hopefully this will help to illustrate how all of the pieces come together, connfd is our connected socket and the default read and write routines will be used.
  • The application calls parser_init( connfd, connfd, NULL, NULL )
    • parser_init sets the input and output file descriptors
    • parser_init sets the callbacks to the defaults
    • parser_init initializes the buffer and calls yy_scan_string
  • the application calls yyparse to start the parser
    • flex finds that the input buffer is empty and calls yywrap
      • yywrap calls the read callback.
        • the read callback reads from the socket and populates the buffer.
      • yywrap calls yy_scan_string
      • yywrap returns 0 to have flex continue, if there was data available.
And that is the process, which actually seems to work quite well. Except for the small memory leak, but that is another post.

Thursday, December 13, 2007

Setting Environment Variables From Make Targets -- part II

I ran into a issue with the way that GNU make acts between cygwin and Solaris. In my previous post I used two instances of the same target, one to export the environment variable and one that executes the test. For example:

TST_CONFIG_MODULE := $(d)/test_config
...
check_config : export TST_DIR:= \
$(dir $(TST_CONFIG_MODULE) )
check_config : $(TST_CONFIG_MODULE)
$(TST_CONFIG_MODULE)


This is how it is documented in the GNU make manual and how it works under Cygwin. However, this fails on Solaris. The version of make installed on Solaris is only a couple of point releases different than the one on Cygwin so I wouldn't expect this to be an new feature. The immediate solution that I came up with is the same one that I used for the main check target.


check_config : $(TST_CONFIG_MODULE)
@for m in $(TST_CONFIG_MODULE) ; do \
export TST_DIR=`dirname $$m`; \
$$m;
done

Sunday, October 7, 2007

Setting Environment Variables From Make Targets

In my current project I needed to pass some pass information to some of my automated unit test programs. I needed the path that the program is being executed from to be able to read test data. As I am using a unit test framework I didn't have access to the command line variables and didn't want to take the time to change the framework to support this. So I decided to define an environment variable with the path information for the program. The unit tests can be run in two different ways, which needed different mechanisms to define the environment variable. The makefiles are setup with rules to run a single set of tests (e.g. make check_config), or running all unit tests (e.g. make check).

To support running a single set of unit tests the make file defines two targets. One that exports the environment variable and one that executes the test. For example:

TST_CONFIG_MODULE := $(d)/test_config
...
check_config : export TST_DIR:= \
$(dir $(TST_CONFIG_MODULE) )
check_config : $(TST_CONFIG_MODULE)
$(TST_CONFIG_MODULE)

Where the TST_CONFIG_MODULE defines the test program. The first check_config target exports an environment variable TST_DIR that is the directory component of, $(d), of TST_CONFIG_MODULE. The make file has to be structured this way as $(d) will not be valid by the time the target is evaluated.

For the second case the makefiles add test modules to the macro CHECK_MODULES and the check target just executes each element of this macro. As this is executed in a shell the target becomes:


check : $(CHECK_MODULES)
@for m in $(CHECK_MODULES) ; do \
export TST_DIR=`dirname $$m`; \
$$m;
done


It is a bit of a kludge to use the dirname executable to get the directory path from the test program name. Doing this assumes that we have dirname installed and that it is on the path. Bash has a built in to do this, ${dirname file}, but there does not seem to be such a builtin in sh.

Setting a Macro to Wildcarded Files

I found a mistake in one of my macro definitions. The macro was to hold all of the public header files and was defined as:

HEADERS := $(d)/*.h

This only set HEADERS to src/include/*.h instead of setting it to the files. To get they desired result the macro was changed to:

HEADERS := $(wildcard $(d)/*.h)

Friday, June 8, 2007

Allowing Local Overrides in Make

I've been setting up a new project at work. I wanted to set up the makefile to allow a programmer to override settings without making changes to the makefiles. Make, unfortunately, does not provide a direct way to do this. I added a shell command to test for the existence of local file, and if found to return it. Make then tests the local file macro and includes the local rules file if defined. Adding the local rules file to svn ignore help to prevent any accidental changes to the makefiles. To illustrate here is the makefile.

## our directories
##
BASE_DIR := $(PWD)
RULES_DIR := rules
DOC_DIR := doc
SRC_DIR := src

## misc definitions
##
KERNEL := $(shell uname -s)
MACHINE := $(shell uname -m)
RULES_FILE := $(KERNEL)_$(MACHINE).mk
LOCAL_RULES := $(shell if [[ -e rules.local ]]; then echo rules.local; fi )

## load rules
##
dir := $(RULES_DIR)
include $(dir)/$(RULES_FILE)

# local overrides
ifdef LOCAL_RULES
include $(LOCAL_RULES)
endif

dir := $(DOC_DIR)
include $(dir)/Rules.mk

dir := $(SRC_DIR)
include $(dir)/Rules.mk

Sunday, April 22, 2007

Calendar Dimension

While working on a data mart and reporting system for a project I needed a way of pulling data for specific time periods for reports. This was done by using a calendar dimension, which is a table that specifies time frames primarily for reporting purposes. The dimension can be setup for any level of granularity that one needs. Since my smallest reporting period was a single month I setup a table like:
CREATE TABLE calendar_dim(
calendar_id NUMBER,
year NUMBER,
quarter NUMBER,
month_number NUMBER,
month_name VARCHAR2,
month_abbr VARCHAR2 )

The calendar_dim table is then populated with the calendar data that you need like:
1, 2006, 1, 1, 'January', 'JAN'
2, 2006, 1, 2, 'February', 'FEB'

Each table that contains dated information has a calendar_id column like:

CREATE TABLE foo_bar(
calendar_id NUMBER NOT NULL,
foo VARCHAR,
bar NUMBER )

The calendar dimension can then be used to control the time frame that queries are run for. As an example the following query sums the value bar over the first quarter of the year 2006.
SELECT fb.foo, SUM(fb.bar)
FROM foo_bar fb, calendar_dim c
WHERE
fb.calendar_id = c.calendar_id AND
c.year = 2006 AND
c.quarter = 1
GROUP BY
fb.foo;

Sunday, April 15, 2007

Implementing Non-Recursive Make

I had to take over the web application piece of a project that I worked on after it became abandonware from the software vendor. I needed a build system for this project and decided to implement it using non-recursive make having previously read Peter Miller's paper. I based mine on the non-recursive make system presented by Emile van Bergen, but I ran into several problems with his approach. These are my notes on how I resolved my problems.

Documentation and Suggested Reading


Length Limit of Macros


The original presentation for implementing non-recursive make had individual macros defined to contain all of the source or object files. However, due to the sheer number of files in the webapp project, almost 2,000 after code generation, the upper bound for the length of a macro was exceeded. To resolve this problem my Makefile defines macros to hold the names of directory targets. Where each directory target is dependent upon the contents of per-directory macros, which contain the source or object files for that directory.

For example the Makefile contains:

...
CALLENTRY := $(DIR_LIBS)/fbCallEntry.jar
CALLENTRY_TGT :=
...
dir := com/fb/callentry
include $(dir)/Rules.mk
...

$(CALLENTRY) : $(COMMON) $(CALLENTRY_TGT)
@echo
...

The Rules.mk files in the callentry sub directories contain something like:

...
d := $(dir)
CALLENTRY_TGT += $(d)
...
CALLENTRY_SRCS_$(d) := \
$(d)/CallEntryObjectRegistry.java \
$(d)/CallHistoryItem.java \
$(d)/Customer.java

CALLENTRY_OBJ_$(d) := $(CALLENTRY_SRCS_$(d):%.java=%.class)
...

$(d) : $(CALLENTRY_OBJ_$(d))
$(d)/Rules.mk

CALLENTRY_OBJ_$(d) : CALLENTRY_SRCS_$(d)

Clean Targets


One of the goals was to keep the directory level details in the directory's Rules.mk file. However, this makes it difficult to implement directory level clean targets. The difficulty arises in that you no longer know the directory path after the rules.mk file has been loaded. The solution to this problem was to encode the directory path into the per-directory clean target, and then extract the directory path by using make's substitution rules.

For example the Makefile contains:

...
CLN_TGT :=
REAL_CLN_TGT :=

DIST_CLN_TGT:=
...

clean :$(CLN_TGT)

realclean : clean $(REAL_CLN_TGT)

distclean : realclean $(DIST_CLEAN_TGT)
...

The Rules.mk files in the callentry subdirectories contain something like:

...
CLN_TGT += CLN_$(d)
...

CLN_$(d) :
rm -f $(subst CLN_,,$@)/*.class
...

Tuesday, April 3, 2007

VIM

The VIM (VI iMproved) editor is available for most platforms and is available as a native Window's GUI application as the program gvim. The VIM editor has many customization features which are controlled by the vimrc configuration file.

VIMRC
The vimrc file may exist in several different locations and different names depending on your platform and installation. You can access vim's online help for additional information with the command :h vimrc. The default vimrc file does some nice things like setting up syntax highlighting so it is recommended that you either modify the default file or copy it for a user specific customizations. These are the settings that I use.

  • ai or autoindent This option automatically indents to the level of the previous line.
  • et or expandtab Insert an appropriate number of spaces instead of tabs.
  • sw or shiftwidth The number of spaces to use for each step of auto indent. Set this option to 4.
  • ts or tabstop The number of spaces a tab character counts for. Set this option to 4.
  • sts or softabstop The number of spaces a tab counts for while editing. Set this option to 4.
  • fdm or foldmethod This option enables code folding in the editor. I set this option to indent.

I set the last line of my vimrc file to:
set ai et sw=4 ts=4 sts=4 fdm=indent


Splitting Windows
  • :sp to split the current window into two views.
  • C-w C-w jumps between the windows.
  • C-w+ or C-w- to increase or decrease the view size.
  • C-wc or :q will close the selected view.

Using Tags
To enable tags do :set tag=.
C-] or C-W] follows tag for item under cursor (existing or split window).
C-T returns to your previous spot.
Searching tags :tag / or :tag for completion
:ts will list multiple matches.

Code Folding
The indent fold method works very well for source code if one uses good and consistent indentation. In this case vim will fold the code based upon the level of indentation. For example:


public void preInit(URL url) {
+--- 46 lines: or the default if no config files was specified.------- } // end preInit

public void init()
{
+--- 60 lines: preInit(getCodeBase());-------------------------------- } // end init

If one wants to use folding but not for source code then the fold method can be set to marker (fdm=marker). A marker will define a folding level for a hierarchy of
folds. A marker is the string { { { # where the # is a numeral defining the fold level. For example:

VIM {{{1
* To insert tabs when in expandtab (et) mode use C-V

windows {{{2 * :[#]sp to split the current window into two views


From command mode the following basic commands can be used to control the folding.
  • zR Open all folds
  • zo Open one fold under the cursor.
  • zO Open all folds under the cursor recursively.
  • zc Close one fold under the cursor.
  • zC Close all folds under the cursor recursively.

Misc Notes
  • To insert tabs when in expandtab (et) mode use {{C-V}}