Link to home
Start Free TrialLog in
Avatar of tatikor_143
tatikor_143

asked on

Porting from unix to windows

Hi,

I have some 1000 lines of code which converts binary formatted log file obtained from the server to ascii readable format.When I am compiling it on windows using cygwin as IDE,I am able to get the desired output.The sample of output is as follows:

[0000] 04/12/2006 12:08:58 CCED0763 LCS: Graceful Switchover. Call Processing Stopped at 12:09:01
edi    = 00000000 esi = 00f002fb ebp = 08cdd394 esp = 08cdd364
ebx    = 08cdd36c edx = 08cdd3b0 ecx = 00000000 eax = 00000008
eflags = 00000216 pc = 01a8f3d4

 Return Address Stack:
 011b53fd(lcsRedActiveGswoPendingFSM+18d)
 011b3b46(lcsRedundantActiveFSM+86)
 011b27e6(lcsFSM+96)
 011b2465(lcsRun+1b5)
 0216542c(vxTaskEntry+c)
Stack (top = 0x8cdd364):
 08cdd364:  08cdd3a8 08cdd3ec 00000000 00f002fb 08cdd394 08cdd364 08cdd36c 08cdd3b0
 08cdd384:  00000000 00000008 00000216 01a8f3d4 08cdd3bc 011b53fd 00f002fb 08cdd3a8
 08cdd3a4:  00000019 303a3231 31303a39 00000000 00000000 08cdd3d0 08cdd3c8 011b3b46
 08cdd3c4:  08cdd3ec 08cdd3dc 011b27e6 08cdd3ec 00000000 00000000 08cdd450 011b2465
 08cdd3e4:  08cdd3ec 00000000 0000000a 00000005 eeeeeeee 00000019 0000001c eeeeeeee
 08cdd404:  eeeeeeee ffffffff ffffffff ffffffff eeeeeeee eeeeeeee eeeeeeee 08c23374
 08cdd424:  0226b472 084caf74 eeeeeeee eeeeeeee eeeeeeee eeeeeeee eeeeeeee 08c233f4
 08cdd444:  0226af1a 084caf74 00000000 00000000 0216542c 00000000 00000000 00000000
 08cdd464:  00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
 08cdd484:  00000000 00000037 00873894 08b5b3f0 04c81b1c 0000c42f 00872e14 08cca5e0
 08cdd4a4:  08cdea58 00065c78 00873160 02bd1e50 08ccd480 00000004 00000000 00000037
 08cdd4c4:  00000037 00000000 00000000 00000000 00000000 00000000 08cca7a4 00000000
 08cdd4e4:  00000000 00000000 0087328c 02b4c7c0 011b22b0 08cdd480 08ccd744 08ccd480

but when I ported the same code onto visual studio 2005 and compiling it ,it gives some junk output,the output from visual studio is

[0000] ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ 0763  Graceful Switchover. Call Processing Stopped at 12:09:01
edi    = 00f002fb esi = 08cdd394 ebp = 08cdd364 esp = 08cdd36c
ebx    = 08cdd3b0 edx = 00000000 ecx = 00000008 eax = 00000216
eflags = 01a8f3d4 pc = 08cdd3a8

Interrupt level: 17477
 Return Address Stack:
 08cdd3a8(ebss+563e3a8)
Stack (top = 08CDD36C):
 08cdd36c:  08cdd3ec 00000000 00f002fb 08cdd394 08cdd364 08cdd36c 08cdd3b0 00000000
 08cdd38c:  00000008 00000216 01a8f3d4 08cdd3bc 011b53fd 00f002fb 08cdd3a8 00000019
 08cdd3ac:  303a3231 31303a39 00000000 00000000 08cdd3d0 08cdd3c8 011b3b46 08cdd3ec
 08cdd3cc:  08cdd3dc 011b27e6 08cdd3ec 00000000 00000000 08cdd450 011b2465 08cdd3ec
 08cdd3ec:  00000000 0000000a 00000005 eeeeeeee 00000019 0000001c eeeeeeee eeeeeeee
 08cdd40c:  ffffffff ffffffff ffffffff eeeeeeee eeeeeeee eeeeeeee 08c23374 0226b472
 08cdd42c:  084caf74 eeeeeeee eeeeeeee eeeeeeee eeeeeeee eeeeeeee 08c233f4 0226af1a
 08cdd44c:  084caf74 00000000 00000000 0216542c 00000000 00000000 00000000 00000000
 08cdd46c:  00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
 08cdd48c:  00000037 00873894 08b5b3f0 04c81b1c 0000c42f 00872e14 08cca5e0 08cdea58
 08cdd4ac:  00065c78 00873160 02bd1e50 08ccd480 00000004 00000000 00000037 00000037
 08cdd4cc:  00000000 00000000 00000000 00000000 00000000 08cca7a4 00000000 00000000
 08cdd4ec:  00000000 0087328c 02b4c7c0 011b22b0 08cdd480 08ccd744 08ccd480 04bb2c90

I am just compiling the code on different IDE's.Please help me the steps that has to be taken care when compiled on visual studio 2005.

Please help me out at the earliest.
Avatar of bpmurray
bpmurray
Flag of Ireland image

Since you only show the output, it's impossible to help. If you look at a single problematic area, and examine the code for that, the problem can be broken down and resolved fairly quickly. For example, the first lines are:

Unix:
   [0000] 04/12/2006 12:08:58 CCED0763 LCS: Graceful Switchover. Call Processing Stopped at 12:09:01

Windows:
   [0000] ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ 0763  Graceful Switchover. Call Processing Stopped at 12:09:01

Clearly something is wrong here. What's the code to print this line?
Avatar of tatikor_143
tatikor_143

ASKER

Not only the above lines,please have a look at the stack and its contents.Its compleately different from each other.
gmtime_r(&pReport->timeStamp, &theTime);
strftime(timeString,  sizeof(timeString), "%d/%m/%Y %H:%M:%S", &theTime);

These are the 2 lines that prints the above output in unix.Header file included is <time.h>,but when i include the same header file in visual studio,it throws the error,therefore i commented the above 2 lines and therefore the above output in windows is junk characters for the time stamp.

Do i have to take care about any compiler settings in visual studio because I compiled using cc in unix.
In visul studio ,my output displays junk address but it displays the correct address on unix with the same code.
Avatar of Kent Olsen

Hi tatikor,

Three quick thoughts.  

--  Are both compilations on the same hardware?  If not, are both big-endian machines?
--  Is the log file opened in binary mode.  It won't matter in unix/cygwin, but Windows CR/LF will be a problem.
--  Are there any #pragma statements?  (Expressed or implied?)  The structures may be packed in one platform and word-aligned in the other.



Kent
Hi Kdo,

1) Are both compilations on the same hardware?  If not, are both big-endian machines?
-Both compilations are on the same hardware and both are little endian machines.

2)Is the log file opened in binary mode.  It won't matter in unix/cygwin, but Windows CR/LF will be a problem.
-No,log file is not opened in binary mode.How to set the CR/LF problem in Windows?

Please let me know.

3)Are there any #pragma statements?  (Expressed or implied?)  The structures may be packed in one platform and word-aligned in the other.

-NO,there are no#pragma statements included in the file.
1)
>> gmtime_r(&pReport->timeStamp, &theTime);
>> strftime(timeString,  sizeof(timeString), "%d/%m/%Y %H:%M:%S", &theTime);

gmtime_r() is a re-entrant (thread-safe) version of the standard gmtime() and is not available in Visual C++ (only POSIX).
If your application doesn't make use of threads, try this code instead :

    struct tm *theTime = gmtime(&pReport->timeStamp);
    strftime(timeString,  sizeof(timeString), "%d/%m/%Y %H:%M:%S", theTime);

Notice that I re-defined theTime !!!


2) In the first line, there's also CCED after the date and time. Where is that printed, and what error do you get with that ?

3) Check into Kdo's comments.

4) Also look through the code for other POSIX-only methods etc. That will give you an indication where possible problems lie.

5) Were there any other parts you commented because they generated errors ? That is not the right way to handle errors in most cases ... Tell us the errors, and which code you commented !!
Just looking at the output, there are patterns that strike me as odd, e.g. the consistent spurious "08". This would indicate one of two things: incorrect initialization (remember, C does NOT initialize variables to a particular value unless you decide to do so yourself) and/or incorrect alignment. Are you using any unions or structs that could cause "holes" in memory?
>> e.g. the consistent spurious "08".
That's probably part of the code's base address ... so that's normal.

However, the second output shows that for some reason, the Windows code started reading from the file 4 bytes further - ie. it seems to have skipped 4 bytes somewhere. That's why all the registers have been moved by one, and the stack output is wrong, because a different base address (esp) is used.

As I asked in my last post : did you comment any other code ?
And as Kdo suggested : the fact that you didn't open the log file in binary mode might cause this. Look for the location in the code where the log file is opened (fopen()), and make sure the binary "rb" flag is used.
Hi Infinity,

The above code mentiomed by you for gmtime is not working.It compiles but throws run time error.I added the flag "rb" in the open functio where it opens my binary file,but still the same output.I am using ioctl function,Please tell me whixh header file to be include for the same,I tried searching for ioctl header file in vc,but i couldn't find.

Also,I have not commented any other code.
Hi tatikor,

Is the data read into and handled by a "raw" buffer (char Buffer[SOMESIZE]) or a defined struct/union?  My guess is that there are defined struct/union objects.


I find it most curious that the data in the headers seems to shift by one word.

[0000] 04/12/2006 12:08:58 CCED0763 LCS: Graceful Switchover. Call Processing Stopped at 12:09:01
edi    = 00000000 esi = 00f002fb ebp = 08cdd394 esp = 08cdd364
ebx    = 08cdd36c edx = 08cdd3b0 ecx = 00000000 eax = 00000008
eflags = 00000216 pc = 01a8f3d4

[0000] ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ 0763  Graceful Switchover. Call Processing Stopped at 12:09:01
edi    = 00f002fb esi = 08cdd394 ebp = 08cdd364 esp = 08cdd36c
ebx    = 08cdd3b0 edx = 00000000 ecx = 00000008 eax = 00000216
eflags = 01a8f3d4 pc = 08cdd3a8


Note that the edi value is zero in the first header and non-zero in the second.  Every item after edi is shifted by one.  (edi#2 = esi#1, esi#2 = ebp#2, etc.)

This suggests a simple definition error that isn't identical in the two platforms.  Look for any of the following:

-- A 64-bit definition becomes 32-bit, or vice versa.  
-- Two 16-bit fields are "packed" in one program, but word aligned in the other.  
-- Bit-field differences.


Can you post the struct/union?
Kent
Hi Kent,

I am posting the entire code for your reference which I compiled it on cygwin which gives the correct output.

/* */
#define SOLARIS_OS 1
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include "stderror.h"
#include "rptRdUnix.h"
#include "rptRdTool.h"
#include "rptFile.h"
#include "rptObject.h"
#include "rasTrace.h"
#include "rasTrace.c"
#include <stdlib.h>
#include <endian.h>

//#define  __BIG_ENDIAN 1

//#if defined(__BYTE_ORDER)
//# if __BYTE_ORDER == __BIG_ENDIAN
 //# define AFMT_S16_NE    AFMT_S16_BE
//# elif __BYTE_ORDER == __LITTLE_ENDIAN
//# define AFMT_S16_NE    AFMT_S16_LE
//# else
//# error "could not determine byte order"
//# endif
//# endif
//#include "rasTrace.c"
//#include "sysSymTbl.h"
//#include "symLib.c"
//#include "rasTrace.c"
//#define BEST_FIT        "\t%s: %-30.30s 0x%x\n"
#define SYMBOL_FILE_NOT_FOUND   "Could not find symbol file %s.\n"

/***********************************************************************/
/* Log File Format structure definitions                               */
/***********************************************************************/
/* The version value should be changed when log file/queue format changes */

#define RPT_FILE_VERSION        (('v'<<24)+('1'<<16)+('.'<<8)+'3') /* v3.0 */
#define RPT_FILE_VERSION_30     (('v'<<24)+('1'<<16)+('.'<<8)+'3') /* v3.0 */
//
// /* function to swap 2 bytes (short) */
// #define swaps(x)        ((((x) & 0x00ff) << 8) | \
//                          (((x) & 0xff00) >> 8))
// /* function to swap an integer (4 bytes) */
//
// #define swapl(x)        ((((x) & 0x000000ff) << 24) | \
//                          (((x) & 0x0000ff00) <<  8) | \
//                          (((x) & 0x00ff0000) >>  8) | \
//                          (((x) & 0xff000000) >> 24))
                         
#define RPT_FILE_OPT_FIXED 0x00000001L
#define MAX_REPORT_SIZE   60

#define RD_SEEK_FORWARD  1
#define RD_SEEK_BACKWARD 2
#define RD_SEEK_ABSOLUTE 3
#define RDSTEXT "rds.txt"

typedef struct {
   uint32_t  version;
   uint32_t  options;
   uint32_t  creationTime;
   uint32_t  maximumBytes;
   uint32_t  maximumRecords;
   uint32_t  oldestRecord;
   uint32_t  newestRecord;
   uint32_t  numberOfRecords;
   uint32_t  reserved[24];
} LogFileHeader;

typedef struct {
   LogFileHeader logFileHeader;
   int   fd;
   char* name;
   int   nextWriteLocation;
} ReportFile;

int main ()
{
   RESULT result;
   int n, index, rptHandle;
   FILE *fd;
//    char rptFileName[100] = "LOG00000.RPT\0";
//    char logFileName[100] = "rd_log.txt";
   char rptFileName[100];
   char logFileName[100];
   char *rptFileName_p;
   RptFileInfo   fileInfo;
   
   RptBrowseInfo rdinfo;
   
   printf("Enter the full path and the File Name(i.e. ./LOG00000.RPT)\n");
   printf("to convert:");
   scanf("%s", &rptFileName);

   printf("Enter the output LOG File Name:");
   scanf("%s", &logFileName);
 
   strncpy(rdinfo.rdLogName, logFileName, sizeof(rdinfo.rdLogName));
   rdinfo.rdLogName[sizeof(rdinfo.rdLogName)-1] = '\0';
     
     result = rptFileCreate(&(rdinfo.file));
    if (SUCCEEDED(result) != TRUE)
    {  
      printf ("failed from rptFileCreate\n");
      return 0;
    }
    rptFileName_p = &rptFileName[0];
    result = rptFileOpenLog(rdinfo.file, rptFileName_p);
    if (SUCCEEDED(result) != TRUE)
    {
      printf ("failed from rptFileOpenLog\n");
    }
    printf("rdLogName=%s, logFileName=%s\n", rdinfo.rdLogName, logFileName);
    //fd = open(rdinfo.rdLogName, O_WRONLY | O_CREAT, 0);
     fd = fopen("rd_log.txt", "w");
     if (fd == NULL)
       {
         printf("Failed to open output file, exiting\n");
         return 0;
       }
             
     result = rptFileInfoGet(rdinfo.file, &fileInfo);  
      if (SUCCEEDED(result)) {
          printf("Got the File Info\n");                
          result = rdSeek(&rdinfo, fileInfo.oldestRecord, RD_SEEK_ABSOLUTE);
          if (SUCCEEDED(result))  
            {
              printf("Success from rdSeek, noOfRec=%x, oldRec=%x, newRec=%x\n",
                     fileInfo.numberOfRecords, fileInfo.oldestRecord, fileInfo.newestRecord);
              result = rdPrintNextRecords(&rdinfo, fileInfo.numberOfRecords, TRUE, fd);
            }        
    fclose(fd);
 
    rptFileDelete(rdinfo.file);
    printf("End of program\n");
   return 0;
  }
}
RESULT rptFileCreate(
   RptFileHandle* handle_p
)
{
   ReportFile* rptFile_p = NULL;

   if (NULL == handle_p) {
      printf("Failed E_INVALID_ARG");
      return E_INVALID_ARG;
   }
   rptFile_p = (ReportFile*) malloc(sizeof(*rptFile_p));
   if (NULL == rptFile_p) {
        printf("Failed E_OUTOFMEMORY");
      return E_OUTOFMEMORY;
   }
   memset(rptFile_p, 0 , sizeof(*rptFile_p));
   rptFile_p->fd = -1;
   *handle_p = (RptFileHandle)rptFile_p;
   printf("In rptFileCreate, handle_p = %x\n", handle_p);  
   printf("In rptFileCreate, rptFile_p = %x\n", rptFile_p);  
   return S_OK;
}
/*!
  Delete a ReportFile object.
*/
RESULT rptFileDelete(
   RptFileHandle handle
)
{
   ReportFile* rptFile_p = NULL;

   rptFile_p = (ReportFile*)handle;
   if (NULL == rptFile_p) {
      return E_INVALID_ARG;
   }
   if (rptFile_p->fd >= 0) {
      close(rptFile_p->fd);
   }
   if (rptFile_p->name != NULL) {
      free(rptFile_p->name);
   }
   free(rptFile_p);
   printf("In rptFileDelete\n");
   return S_OK;
}

/*!

  Open a rpt_log file on disk and attach it a ReportFile object.

*/

RESULT rptFileOpenLog(
   RptFileHandle  handle,    /*!< Report file object */
   char*          filename   /*!< Name of the report file on disk */
)
{
   int retVal;
   int nextRecord;
   RESULT result = S_OK;
   ReportFile* rptFile_p = NULL;

   if (NULL == filename) {
      printf("In rptFileOpenLog, Failed filename\n");
      return E_INVALID_ARG;
   }

   rptFile_p = (ReportFile*)handle;
   if (NULL == rptFile_p) {
      printf("In rptFileOpenLog, Failed rptFile_p\n");
      return E_INVALID_ARG;
   }
   if (rptFile_p->name != NULL) {
      free(rptFile_p->name);
      rptFile_p->name = NULL;
   }
   
   printf("In rptFileOpenLog, filename=%s\n", filename);
   
   rptFile_p->fd = open(filename, O_RDWR, 0);
   if (rptFile_p->fd < 0) {
     printf("In rptFileOpenLog, Failed open fd\n");
      return E_FAIL;
   }
   printf("In rptFileOpenLog, fd=%d\n",rptFile_p->fd);
   if (lseek(rptFile_p->fd, 0, SEEK_SET) < 0) {
   printf("In rptFileOpenLog, Failed lseek fd\n");
      result = E_FAIL;
   }

   if (SUCCEEDED(result)) {
      rptFile_p->name = (char*)strdup(filename);
      printf("succeeded open file %s\n", filename);
   } else {
      close(rptFile_p->fd);
   }
   return result;
}

/*!
  Seek to the specified record number within the log file.
 */
RESULT rdSeek(
   RptBrowseInfo* rdinfo_p, /*!< The browse context. */
   int            offset,   /*!< The location to which to seek. */
   int            whence    /*!< Forward, backward or absolute. */
)
{
   RESULT      result;
   int         seekIndex;
   RptFileInfo fileInfo;

   seekIndex = rdinfo_p->nextRecord;
   result = rptFileInfoGet(rdinfo_p->file, &fileInfo);
   if (FAILED(result)) {
      return result;
   }
printf("In rdSeek, got rptFileInfo\n");
   switch (whence) {
     case RD_SEEK_BACKWARD:
      seekIndex = rdinfo_p->nextRecord - offset;
      if(seekIndex < 0) {
         seekIndex += fileInfo.numberOfRecords;
      }
      break;

     case RD_SEEK_FORWARD:
      seekIndex = rdinfo_p->nextRecord + offset;
      if (seekIndex >= fileInfo.numberOfRecords) {
         seekIndex -= fileInfo.numberOfRecords;
      }
      break;

     case RD_SEEK_ABSOLUTE:
      if (offset < 0) {
         seekIndex = fileInfo.oldestRecord;
      } else  if (offset >= fileInfo.numberOfRecords) {
         seekIndex = fileInfo.newestRecord;
      } else {
         seekIndex = offset;
      }
      break;

     default:
      printf("rdSeek: Unexpected seek value %d\n", whence);
      break;
   }

   rdinfo_p->nextRecord = seekIndex;
   return S_OK;
}

/*
*/

RESULT rptFileInfoGet(
   RptFileHandle rptFile,
   RptFileInfo*  info_p
)
{
   int             rc;
   ReportFile*     rptFile_p = NULL;

      printf("In rptFileInfoGet\n");
   rptFile_p = (ReportFile*)rptFile;
   if (NULL == rptFile_p) {
      return E_INVALID_ARG;
   }
      printf("fd=%d\n",rptFile_p->fd);
      ioctl(rptFile_p->fd, FIOSYNC, 0);
   if (lseek(rptFile_p->fd, 0, SEEK_SET) <0) {
      printf("rptFileBoundsGet: failed to seek the header of %s\n", rptFile_p->name);
      return E_FAIL;
   }
   printf("lseek is ok\n");
   rc = read(rptFile_p->fd, (char*)&(rptFile_p->logFileHeader), sizeof(LogFileHeader));
   printf("after reading, rc=%d, size=%d\n", rc, sizeof(LogFileHeader));
   if (rc != sizeof(LogFileHeader)) {
      printf("rptFileBoundsGet: failed to read the header of \"%s\"\n", rptFile_p->name);
      return E_FAIL;
   } else if (rptFile_p->logFileHeader.version != RPT_FILE_VERSION ) {
      printf("rptFileBoundsGet: incorrect version of rpt logfile\n");
      return E_FAIL;
   }
   
   info_p->numberOfRecords = rptFile_p->logFileHeader.numberOfRecords;
   info_p->oldestRecord = rptFile_p->logFileHeader.oldestRecord;
   info_p->newestRecord = rptFile_p->logFileHeader.newestRecord;
   info_p->creationTime = rptFile_p->logFileHeader.creationTime;

   return S_OK;
}

RESULT rdPrintNextRecords(
   RptBrowseInfo* rdinfo_p,  /*!< The browse context. */
   int            nRecords,  /*!< Number of records to print. */
   int            verbose,   /*!< Print style, brief or full. */
   FILE*          fd         /*!< File descriptor to which to print. */
)
{
   int         index;
   int         endRecord;
   RptHandle   rptHandle;
   RptFileInfo fileInfo;
   RESULT      result;

   result = rptFileInfoGet(rdinfo_p->file, &fileInfo);
   if (FAILED(result)) {
      return result;
   }

   index = rdinfo_p->nextRecord;
   endRecord = index;
   while ((endRecord != fileInfo.newestRecord) && ((endRecord - rdinfo_p->nextRecord) < (nRecords - 1))) {
      endRecord = (endRecord + 1) % fileInfo.numberOfRecords;
   }

   while (index != endRecord) {
      rptHandle = rptFileRecordGet(rdinfo_p->file, index);
      if (rptHandle != NULL) {
         fprintf(fd, "[%04d] ", index);
         rptObjectPrint(rptHandle, fd, verbose);
         rptObjectDelete(rptHandle);
      }
      index = (index + 1) % fileInfo.numberOfRecords;
   }
   rptHandle = rptFileRecordGet(rdinfo_p->file, index);
   if (rptHandle != NULL) {
      fprintf(fd, "[%04d] ", index);
      rptObjectPrint(rptHandle, fd, verbose);
      rptObjectDelete(rptHandle);
   }

   rdinfo_p->prevRecord = endRecord;
   if (endRecord != fileInfo.newestRecord) {
      endRecord = (endRecord + 1) % fileInfo.numberOfRecords;
   }
   rdinfo_p->nextRecord = endRecord;
   return S_OK;
}

/*!
  Print a report to the specified fd.
 */
RESULT rptObjectPrint(
   RptHandle h,
   FILE      *fd,
   int       printOptions
)
{
   int           i;
   static int    counterFix = 0;
   struct tm     theTime;
   UINT*         vfp = NULL;
   UINT*         vsp = NULL;
   UINT*         virtualStackTop = NULL;
   UINT*         virtualStackBase = NULL;
   UINT*         realStackTop = NULL;
   SYM_TYPE      symType;
   int           symVal;
   int           addr;
   STATUS        status =1;
   char          timeString[32];
   char          name[MAX_SYS_SYM_LEN];
   char          symbolFileName[80] = "mainos.txtsym";
   symbolAddrs*  loadPts;
   int           numEntries;
   int           functionOffset;
   char          *functionName;
   int           ErrorCode;
   ReportObject* pReport = (ReportObject*)h;
   STATUS        retVal = ERROR;
   long          targetAddr;
//   SYMTAB_ID     sysSymTbl;
   
   
   if (pReport->timeStamp == 0){  /* prekernel */
       if ((pReport->action & ACTION_STRNG_BIT) != 0) {
          retVal = fprintf(fd,"%s %s%04d %s\n", "(prekernel)", pReport->catName, pReport->rptNum, "(cont'd)");
       }
       else{
           retVal = fprintf(fd,"%s %s%04d %s\n", "(prekernel)", pReport->catName, pReport->rptNum, pReport->message);
        }
   } else {
      localtime_r(&pReport->timeStamp, &theTime);
      strftime(timeString,  sizeof(timeString), "%d/%m/%Y %H:%M:%S", &theTime);
      if ((pReport->action & ACTION_STRNG_BIT) != 0) {
         retVal = fprintf(fd,"%s %s%04d %s \n", timeString, pReport->catName, pReport->rptNum,"(cont'd)");
      }
      else{
         retVal = fprintf(fd,"%s %s%04d %s\n", timeString, pReport->catName, pReport->rptNum, pReport->message);
      }
   }
   
   if (retVal == ERROR)
      return E_FAIL;
   if ((printOptions & RPT_PRINT_VERBOSE) != 0) {
      if ((pReport->action & ACTION_STACK_BIT) != 0) {
        if ((pReport->action & ACTION_STRNG_BIT) == 0) {
           regSetPrint(fd, &(pReport->registers));
        }
       
         if (pReport->intLevel > 0) {
            fprintf(fd, "\nInterrupt level: %d", pReport->intLevel);
         }
         realStackTop = (UINT *)regSetSpGet(&(pReport->registers));
         virtualStackTop = (UINT *)(pReport->stack);                                      
         virtualStackBase = (UINT *)(pReport->stack + STACK_ENTRIES);                    
         vfp = (UINT *)(((UINT)regSetFpGet(&(pReport->registers)) - (UINT)realStackTop)    
                      + (UINT)virtualStackTop);                                          
         fprintf(fd,"\n Return Address Stack:");
         vsp = vfp;
             //printf("%x\n",vsp);
         //symbolFileName[80] ="mainos.txtsym";
               if ((numEntries = getLoadAddrs(&loadPts, symbolFileName, &ErrorCode)) == 0)
            {
            switch (ErrorCode)
                  {
                  case LOAD_ADDRS_MALLOC_ERROR:
                        fprintf(stderr, "Unable to allocate memory for symbol file\n");
                        break;
                  case LOAD_ADDRS_FILE_ERROR:
                        fprintf(stderr, SYMBOL_FILE_NOT_FOUND, symbolFileName);
                        break;
                  case LOAD_ADDRS_NAME_ERROR:
                        fprintf(stderr, "Unable to load name from symbol file\n");
                        break;
                  }      
            exit(1);
            }
            
         while (vsp < virtualStackBase)
             {
              counterFix++;
            if (counterFix >= STACK_ENTRIES) {
                counterFix = 0;
                printf("some records in this log file are corrupted \n");
                return E_ABORT;
          }
            // printf("inside while\n");
            addr =vfp[1];  
                  //printf("%08x\n",addr);
                  //fprintf(fd, "\n %08x (Symbol Not Available)", addr);
                  //printf("%d",addr);
            if (interpretRAS(*((long *)&addr),loadPts, numEntries, &functionName, &functionOffset))
                  {
                  //printf(BEST_FIT,
                  //      vsp[1], functionName, functionOffset);
                        //printf("In intrepretras\n");
                        fprintf(fd, "\n %08x (%s+%x)", addr, functionName, functionOffset);
                  }                                                      
        //    status = symFindByValue(sysSymTbl, addr, name, &symVal, &symType);
             if(status=ERROR)
            {
               fprintf(fd, "\n %08x (Symbol Not Available)", addr);
            }
             else {
                fprintf(fd, "\n %08x (%s+%x)", addr, name,addr-symVal);
             }
            if (*vfp < (UINT)realStackTop)  {        
               break;
            }
            vfp = (UINT *)((*vfp - (UINT)realStackTop) + (UINT)virtualStackTop);
            vsp = vfp + 2;

         }

         fprintf(fd,"\nStack (top = %p):", realStackTop);                              
         for( i = 0; i < STACK_ENTRIES; i++) {                                          
            if( (i % 8) == 0 ) {                                                        
               fprintf(fd, "\n %08x: ", (UINT)realStackTop + (i * sizeof(void*)));      
            }                                                                            
            fprintf(fd, " %08x", pReport->stack[i]);                                    
         }                                                                              
         fprintf(fd, "\n\n");
       
      }
   }
   return S_OK;
}

/*!
   Reads a report object from the report file.
 */
RptHandle rptFileRecordGet(
   RptFileHandle handle,
   int recordIndex
)
{
   ReportFile* rptFile_p = NULL;
   RptHandle rptHandle = NULL;

   rptFile_p = (ReportFile*)handle;
   if (NULL != rptFile_p) {
      if (lseek(rptFile_p->fd, FileRecToSeek(rptFile_p, recordIndex), SEEK_SET) > 0) {
//          printf("In rptFileRecordGet, lseek OK, recordIndex=%x, seekIndex=%x, fd=%x\n",
//                 recordIndex, FileRecToSeek(rptFile_p, recordIndex), rptFile_p->fd);
         rptHandle = rptObjectRead(rptFile_p->fd);
      }
   }
   return rptHandle;
}
/*!
 */
RptHandle rptObjectRead(
   int fd
)
{
   int nBytes;
   ReportObject* pReport = NULL;

   pReport = malloc(sizeof(*pReport));
   if (NULL == pReport) {
      return (RptHandle)NULL;
   }
   memset(pReport, 0, sizeof(*pReport));
   nBytes = read(fd, (char*)pReport, sizeof(*pReport));
   if (nBytes <= 0) {
      free(pReport);
      return (RptHandle)NULL;
   }
   return (RptHandle)pReport;
}
/*!
 */
void rptObjectDelete(
   RptHandle h
)
{
   ReportObject* pReport = (ReportObject*)h;

   if (NULL != pReport) {
      free(pReport);
   }
}

/*!

 FileRecToSeek - convert record number to *seek value*

 This procedure takes a record number and detrmines the seek value
 in the log file based on the record size of each log entry

 RETURNS: seek_val - seek value position in file

*/
int FileRecToSeek(
   ReportFile* rptFile_p,
   int rec_num
)
{
   if ((rec_num < 0) || (rec_num > rptFile_p->logFileHeader.numberOfRecords)) {
      /* TBD - report */
      return (sizeof(LogFileHeader));
   }
   return (((rec_num) * rptObjectSizeGet(NULL)) + sizeof(LogFileHeader));
 
}
int rptObjectSizeGet(
   RptHandle h
)
{
   ReportObject* pReport = NULL;

   pReport = (ReportObject*)h;
   if (NULL == pReport) {
      return sizeof(ReportObject);
   } else {
      return sizeof(*pReport);
   }
}

int regSetPrint(
   FILE      *fd,
   REG_SET* pRegs
)
{
   fprintf(fd, "edi    = %08x esi = %08x ebp = %08x esp = %08x\n", pRegs->edi, pRegs->esi , pRegs->ebp, pRegs->esp);  
   fprintf(fd, "ebx    = %08x edx = %08x ecx = %08x eax = %08x\n", pRegs->ebx, pRegs->edx , pRegs->ecx, pRegs->eax);  
   fprintf(fd, "eflags = %08x pc = %08x\n", pRegs->eflags, pRegs->pc);
}

int regSetSpGet(
   REG_SET* pRegs
)
{
   return (pRegs->esp);
}

void regSetSpPut(
   REG_SET* pRegs,
   int      sp
)
{
   pRegs->esp = sp;
}

int regSetFpGet(
   REG_SET* pRegs
)
{
   return pRegs->ebp;
}

void regSetFpPut(
   REG_SET* pRegs,
   int      fp
)
{
   pRegs->ebp = fp;
}

       <<<<<<<stderror.h>>>>>>>>>>

/*!
  \file stderror.h

  Result values are signed integers where values greater than or equal
  to zero mean success and values less than zero indicate an error.

  Result values may be tested to see whether they are success or
  failure codes by using the macros FAILED and SUCCEEDED.

  RESULTs are 32 bit values layed out as follows:

   3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
   1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
  +-+------------+----------------+-------------------------------+
  |S|  Facility  |           Error Code                           |
  +-+------------+----------------+-------------------------------+

  where

  S - Severity - indicates success/fail

  0 - Success
  1 - Fail (COERROR)

  Reserved - Reserved for future use.

  Facility - is the facility code, this is used to unite error codes
  from different families into one global error code space.
 
  Code - is the facility's status code

*/
#ifndef _stderror_h_
#define _stderror_h_
#include <errno.h>

/*!
 Severity values
*/
#define SEVERITY_SUCCESS    0
#define SEVERITY_ERROR      1

/*!
  This macro evaluates a RESULT code to determine whether it represents
  a failure code.  It returns 1 if the code is a failure code or 0 if the
  code is a success code.
 */
#define FAILED(_r_) ((_r_) < 0)

/*!
  This macro evaluates a RESULT code to determine whether it represents
  a success code.  It returns 1 if the code is a success code or 1 if the
  code is a success code.
 */
#define SUCCEEDED(_r_) ((_r_) >= 0)

#define FACILITY_NULL                0
#define FACILITY_POSIX               1
#define FACILITY_VXWORKS             2

#define MAKE_RESULT(sev,fac,code) \
    ((RESULT) (((unsigned long)(sev)<<31) | \
    ((unsigned long)(fac)<<24) | ((unsigned long)(code))) )

/*!
  Unconditional success.
  */
#define S_OK                         0x00000000L

/*!
  Whatever the function was asked to accomplish has already been
  accomplished.  No action was required or performed.
 */
#define S_FALSE                      0x00000001L

#define E_FAIL                       0x80000000L  /* Unspecified failure */
#define E_UNEXPECTED                 0x80ffffffL  /* Encountered a fatal condition that should not have occurred */
#define E_NOTIMPL                    0x80000002L  /* Function is not implemented */
#define E_OUT_OF_MEMORY              0x80000003L  /* A memory allocation failed */
#define E_INVALID_ARG                0x80000004L  /* One or more arguments were invalid */
#define E_POINTER                    0x80000005L  /* An invalid pointer was encountered */
#define E_HANDLE                     0x80000006L  /* An invalid handle was encountered */
#define E_ABORT                      0x80000007L  /* The operation was aborted */
#define E_ACCESS_DENIED              0x80000008L  /* Permission problem */
#define E_DEVICE_NOT_CONNECTED       0x80000009L  /* Attempted to access a device that is offline or does not exist */

/*
  These are for compatibility with the ITGL software, keep until the
  old names have been cleaned up.
*/
#define E_OUTOFMEMORY  E_OUT_OF_MEMORY
#define E_INVALIDARG   E_INVALID_ARG
#define E_ACCESSDENIED E_ACCESS_DENIED

/*!
  The data necessary to complete this operation is not yet available.
*/
#define E_PENDING                    0x8000000aL

/* Not enough storage is available to process this command. */
#define E_BUFFER_TOO_SMALL           0x8000000bL

/* An invalid data record was encountered */
#define E_INVALID_RECORD             0x8000000cL

/*!
  Standard result values based on POSIX defined errno values.

  These can be built dynmically at runtime from the current value of
  errno by using the MAKE_RESULT macro.

  result = MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, errno);
 */
#define E_PERM          MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EPERM)    /* Not owner */
#define      E_NOENT            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ENOENT)   /* No such file or directory */
#define      E_SRCH            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ESRCH)    /* No such process */
#define      E_INTR            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EINTR)    /* Interrupted system call */
#define      E_IO            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EIO)      /* I/O error */
#define      E_NXIO            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ENXIO)    /* No such device or address */
#define      E_2BIG            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, E2BIG)    /* Arg list too long */
#define      E_NOEXEC      MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ENOEXEC)  /* Exec format error */
#define      E_BADF            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EBADF)    /* Bad file number */
#define      E_CHILD            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ECHILD)   /* No children */
#define      E_AGAIN            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EAGAIN)   /* No more processes */
#define      E_NOMEM            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ENOMEM)   /* Not enough core */
#define      E_ACCES            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EACCES)   /* Permission denied */
#define      E_FAULT            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EFAULT)   /* Bad address */
#define      E_NOTEMPTY      MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ENOTEMPTY)/* Directory not empty */
#define      E_BUSY            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EBUSY)    /* Mount device busy */
#define      E_EXIST            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EEXIST)   /* File exists */
#define      E_XDEV            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EXDEV)    /* Cross-device link */
#define      E_NODEV            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ENODEV)   /* No such device */
#define      E_NOTDIR      MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ENOTDIR)  /* Not a directory*/
#define      E_ISDIR            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EISDIR)   /* Is a directory */
#define      E_INVAL            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EINAL)    /* Invalid argument */
#define      E_NFILE            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ENFILE)   /* File table overflow */
#define      E_MFILE            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EMFILE)   /* Too many open files */
#define      E_NOTTY            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ENOTTY)   /* Not a typewriter */
#define      E_NAMETOOLONG      MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ENAMETOOLONG)/* File name too long */
#define      E_FBIG            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EFBIG)    /* File too large */
#define      E_NOSPC            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ENOSPC)   /* No space left on device */
#define      E_SPIPE            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ESPIPE)   /* Illegal seek */
#define      E_ROFS            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EROFS)    /* Read-only file system */
#define      E_MLINK            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EMLINK)   /* Too many links */
#define      E_PIPE            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EPIPE)    /* Broken pipe */
#define      E_DEADLK      MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EDEADLK)  /* Resource deadlock avoided */
#define      E_NOLCK            MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ENOLCK)   /* No locks available */
#define      E_NOTSUP      MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, ENOTSUP)  /* Unsupported value */
#define      E_MSGSIZE      MAKE_RESULT(SEVERITY_ERROR, FACILITY_POSIX, EMSGSIZE) /* Message size */

/*!
  This is the standard return type to be used by all functions.
 */
typedef int32_t RESULT;

#endif /* _stderror_h_ */

                                                   <<<<<<<<<<<<<rptObject.h>>>>>>>>>>>>


#ifndef _rptObject_h_
#define _rptObject_h_
#ifndef SOLARIS_OS
#include <regs.h>
#endif

#define RPT_PRINT_BRIEF    0x00000000
#define RPT_PRINT_VERBOSE  0x00000001
#define RPT_PRINT_SYMBOLIC 0x00000002
#define RPT_PRINT_FULL     0x00000003


#define MAX_DSP_TASKS     100
#define MAX_REPORT_SIZE   60
#define MAX_TASKNAME_SIZE 20
#define MAX_MESG_LEN     256
#define RPTTRAP_SIZE       20              /* number of ints in block */
#define MAX_RPT_ARGS     12                /* max # of args to rptReport  */
#define RAS_ENTRIES      12                /* max # of ret addrs grabbed  */
#define REG_ENTRIES      10                /* # of registers A0-A7, D0-D7 */
#define RPT_ID_TEXT_MAX   32               /* max size of message ID text */
#define RPT_TASK_ORIGIN    8               /* from os, other task specified */
#define RPT_PREKERN_ORIGIN 16              /* from preKernel/OS init code   */
#define      STACK_ENTRIES    104               /* # of stack words to grab    */
#define FRAME_REG  6                       /* frame ptr is register 6    */
#define STACK_REG  7                       /* frame ptr is register 7    */


typedef int  rptArgsType[MAX_RPT_ARGS];
typedef int  rptRegsType[REG_ENTRIES];
typedef int  rptRASType[RAS_ENTRIES];
typedef int  rptStackType[STACK_ENTRIES];

void     rptQgetTrap(int *);
void     rptQputTrap(int *);
 

#ifdef __cplusplus
extern "C" {
#endif

// DECLARE_HANDLE(RptHandle);

RptHandle rptObjectCreate(int rptCategory, int rptNumber);
void rptObjectDelete(RptHandle h);
RptHandle rptObjectCreateLocal(int rptCategory, int rptNumber);
RptHandle rptObjectDuplicate(RptHandle h);
uint16_t rptObjectOriginGet(RptHandle h);
uint16_t rptObjectActionGet(RptHandle h);
void rptObjectActionPut(RptHandle h, uint16_t action);

int16_t rptObjectIntLevelGet(RptHandle h);
void rptObjectIntLevelPut(RptHandle h, int16_t intLevel);

uint16_t rptObjectCategoryGet(RptHandle h);
uint16_t rptObjectNumberGet(RptHandle h);
uint16_t rptObjectIndexGet(RptHandle h);
uint16_t rptObjectOldLostGet(RptHandle h);
uint16_t rptObjectNewLostGet(RptHandle h);
RptHandle rptObjectRead(int fd);
time_t rptObjectTimeStampGet(RptHandle h);

void rptObjectRegistersGet(IN RptHandle h, OUT REG_SET* pRegisters);
void rptObjectRegistersPut(IN RptHandle h, IN REG_SET* pRegisters);

int rptObjectRasGet(IN RptHandle h, IN int stackLen, OUT int* stackBuffer);

int rptObjectStackGet(IN RptHandle h, IN int stackLen, OUT int* stackBuffer);
void rptObjectStackPut(IN RptHandle h, IN int* stackBuffer);

void rptObjectShow(RptHandle h);
void rptObjectCopy(RptHandle pDst, RptHandle pSrc);
int rptObjectSizeGet(RptHandle h);

void rptObjectTextPut(
   RptHandle  h,
   char*         text
);

void rptObjectTextPutf(
   RptHandle  h,
   char*         fmt,
   ...
);

// void rptObjectTextPutvf(
//    RptHandle  report,
//    char*         fmt,
//    va_list       ap
// );

RESULT rptObjectPrint(
   RptHandle h,
   FILE      *fd,
   int       printOptions
);


 typedef struct {
   UINT16        catNum;       /* category of report    */
   UINT16        rptNum;       /* number of report      */
   UINT16        rptIndex;     /* index of report       */
   UINT16        origin;       /* origin code           */
   time_t        timeStamp;    /*!< Time the report object was created */
   UINT16        action;       /* actions for server    */
   INT16         intLevel;     /* interrupt nest level  */
   char          catName[RPT_ID_TEXT_MAX];
   char          message[MAX_MESG_LEN];
   UINT16        mesgIdx;
   REG_SET       registers;    /*!< Register set to be reported */
   int           stack[STACK_ENTRIES];
   rptRASType    ras;          /* return address stack  */

} ReportObject;


#ifdef __cplusplus
}
#endif

#endif

                                               <<<<<<<<<<<rptRdunix.h>>>>>>>>>>>>>>>>

#ifndef _rptRdUnix_h_
#define _rptRdUnix_h_

#ifdef SOLARIS_OS
#define RDSTEXT "rds.txt"
#define GEN_BUFFER_LEN 128                /* General purpose buffer len   */
#define PDT_SHELL_MAX    16
#define FALSE             0
#define TRUE              1
#define STD_OUT           1
#define EOS           '\0'    /* C string terminator */
#define FIOSYNC         21    /* sync to disk */
#define _POSIX_PATH_MAX   255 /* from /Tornado_2.2.1/target/h/limits.h */
#define SEVERITY_ERROR      1 /*stderror.h*/
#define FACILITY_POSIX      1 /*stderror.h*/
#define OK 1
#define ERROR               (-1)

/**************************************************************************/
/* Action bits used by system for determining services and options        */
/**************************************************************************/

#define ACTION_DISP_BIT  0x0001                 /* display service entry  */
#define ACTION_FILE_BIT  0x0002                 /* logfile service entry  */
#define ACTION_ALARM_BIT 0x0004                 /* alarm service entry    */
#define ACTION_PROC_BITS 0x00FF                 /* all process bits-lower */

#define ACTION_STACK_BIT 0x0100                 /* stack capturing option */
#define ACTION_FLUSH_BIT 0x0200                 /* device flushing option */
#define ACTION_STRNG_BIT 0x8000                 /* queue entry string bit */
#define ACTION_OPTN_BITS 0x7F00                 /* all option bits-higher */

#define ACTION_NONE_BITS 0x8000                 /* No actions bit mask    */
#define ACTION_ALL_BITS  0x7FFF                 /* all actions bit mask   */

/* From /sys/fcntlcom.h
 * Flag values for open(2) and fcntl(2)
 * The kernel adds 1 to the open modes to turn it into some
 * combination of FREAD and FWRITE.
 */
#define      _FCREAT            0x0200      /* open with file create */
#define      O_RDONLY      0            /* +1 == FREAD */
#define      O_WRONLY      1            /* +1 == FWRITE */
#define      O_RDWR            2            /* +1 == FREAD|FWRITE */
#define      O_CREAT            _FCREAT

/* vxWorks types */
typedef char            INT8;
typedef short           INT16;
typedef int             INT32;

typedef unsigned char   UINT8;
typedef unsigned short  UINT16;
typedef unsigned int    UINT32;

typedef unsigned char   UCHAR;
typedef unsigned short  USHORT;
typedef unsigned int    UINT;
typedef unsigned long   ULONG;
typedef unsigned long   INSTR; /* from /types/vxTypesOld.h */
typedef signed char     SYM_TYPE;          /* SYM_TYPE */
typedef int             STATUS;

typedef int             BOOL;
/* typedef int             STATUS; */
typedef int             ARGINT;

typedef void            VOID;
typedef int             (*FUNCPTR) ();

typedef struct                  /* REG_SET - 80x86 register set */
    {
    ULONG edi;                  /* general register */
    ULONG esi;                  /* general register */
    ULONG ebp;                  /* frame pointer register */
    ULONG esp;                  /* stack pointer register */
    ULONG ebx;                  /* general register */
    ULONG edx;                  /* general register */
    ULONG ecx;                  /* general register */
    ULONG eax;                  /* general register */
    ULONG eflags;            /* status register (must be second to last) */
    INSTR *pc;                  /* program counter (must be last) */
    } REG_SET;

#define IN
#define OUT
#define INOUT

#define DECLARE_HANDLE(name) typedef struct { int unused; } name##__ ; typedef const name##__ * name                            

DECLARE_HANDLE(RptHandle);
/*
  For compatibility with old ITGL code.
  We should make this go away sometime.
*/
typedef uint32_t Handle;

#define LOG_MAX_SIZE    1000000                  /* logfile size in BYTES */
#define MAX_SYS_SYM_LEN 256     /* system symbols will not exceed this limit */

#endif /* SOLARIS_OS */

#endif

                                                <<<<<<<rptFile.h>>>>>>>>>>>>


#ifndef _rptFile_h_
#define _rptFile_h_

#ifdef SOLARIS_OS
#include "rptRdUnix.h"

#endif

DECLARE_HANDLE(RptFileHandle);

typedef struct {
   uint32_t  creationTime;
   uint32_t  oldestRecord;
   uint32_t  newestRecord;
   uint32_t  numberOfRecords;
} RptFileInfo;

#ifdef __cplusplus
extern "C" {
#endif

RESULT    rptFileReset(RptFileHandle handle);
RESULT    rptFileCreate(RptFileHandle* handle_p);
RESULT    rptFileDelete(RptFileHandle handle);
RESULT    rptFileOpenLog(RptFileHandle handle, char* filename);
void      rptFileCloseLog(RptFileHandle handle);
RESULT    rptFileCreateLog(RptFileHandle handle, char* filename);
RptHandle rptFileRecordGet(RptFileHandle handle, int recordIndex);
RESULT    rptFileRecordPut(RptFileHandle handle, RptHandle report);
RESULT    rptFileInfoGet(RptFileHandle rptFile, RptFileInfo* info_p);
RESULT    rptFileShow(RptFileHandle handle, int verbose);
#ifdef CSE_SERVER
void      rptPostSwo( void );
void      rptPreSwo( void );
#endif

#ifdef __cplusplus
}
#endif

#endif


 This is all my code is............

When I compile the above code on cygwin using gcc,it gives the correct output but when I compile the same on visual studio,It throws the junk ouput.Please help me out as soon as possible.........                                              


















>> The above code mentiomed by you for gmtime is not working.It compiles but throws run time error.
What is the runtime error ?
Is the code making use of threads ?

Try this code instead :

    _gmtime_s(&theTime, &pReport->timeStamp);
    strftime(timeString,  sizeof(timeString), "%d/%m/%Y %H:%M:%S", &theTime);

The _gmtime_s() function is a thread-safe version of gmtime() used in Visual C++ :

http://msdn2.microsoft.com/en-us/library/3stkd9be(VS.80).aspx

>> I added the flag "rb" in the open functio where it opens my binary file,but still the same output.
It was a long shot anyway :)

>> I am using ioctl function,Please tell me whixh header file to be include for the same,I tried searching for ioctl header file in vc,but i couldn't find.
You can use DeviceIOControl instead of ioctl :

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/devio/base/deviceiocontrol.asp
Hi Infinity,

I am sorry to say that,the above code is also not working.It compiles but,it throws an error...
What error ?
And what's the value of pReport->timeStamp ?? Is it a valid value ?

Because if the log file is read wrong, then this value can very well be wrong too !!

Can you add a line to the source and run it in both environments?

  printf (stdout, " ReportObject size is %d\n", sizeof (ReportObject));


Thanks,
Kent
Hi Kent,

When I added the above line and compiled

using cygwin: ReportObject size is 812.

using Visual Studio : ReportObject size is 864.
Or better yet, modify the rptObjectRead() method as follows, and show us the output :

RptHandle rptObjectRead(
   int fd
)
{
   int nBytes;
   int i = 0;
   ReportObject* pReport = NULL;

   pReport = malloc(sizeof(*pReport));
   if (NULL == pReport) {
      return (RptHandle)NULL;
   }
   memset(pReport, 0, sizeof(*pReport));
   nBytes = read(fd, (char*)pReport, sizeof(*pReport));
   if (nBytes <= 0) {
      free(pReport);
      return (RptHandle)NULL;
   }

   fprintf(stdout, "DUMP of pReport :\n---------------\n\n");
   for (i = 0; i < sizeof(*pReport);) {
     int j = 0;
     for (j = 0;(j < 8) && (i < sizeof(*pReport)); j++, i++) {
       fprintf(stdout, "%02x ", ((unsigned char*)pReport)[i]);
     }
     fprintf(stdout, "  ");
     for (;(j < 16) && (i < sizeof(*pReport)); j++, i++) {
       fprintf(stdout, "%02x ", ((unsigned char*)pReport)[i]);
     }
     fprintf(stdout, "\n");
   }
   fprintf(stdout, "\n");
   fprintf(stdout, "\n");
   fprintf(stdout, "VALUES of pReport :\n-----------------\n\n");
   fprintf(stdout, "catNum = %u (%08x)\n", (unsigned int) pReport->catNum, (unsigned int) pReport->catNum);
   fprintf(stdout, "rptNum = %u (%08x)\n", (unsigned int) pReport->rptNum, (unsigned int) pReport->rptNum);
   fprintf(stdout, "rptIndex = %u (%08x)\n", (unsigned int) pReport->rptIndex, (unsigned int) pReport->rptIndex);
   fprintf(stdout, "origin = %u (%08x)\n", (unsigned int) pReport->origin, (unsigned int) pReport->origin);
   fprintf(stdout, "timeStamp = %u (%08x)\n", (unsigned int) pReport->timeStamp, (unsigned int) pReport->timeStamp);
   fprintf(stdout, "action = %u (%08x)\n", (unsigned int) pReport->action, (unsigned int) pReport->action);
   fprintf(stdout, "intLevel = %d (%08x)\n", (int) pReport->intLevel, (int) pReport->intLevel);
   fprintf(stdout, "catName = <%s> (length = %d)\n", (char*) pReport->catName, strlen(pReport->catName));
   fprintf(stdout, "message = <%s> (length = %d)\n", (char*) pReport->message, strlen(pReport->message));
   fprintf(stdout, "mesgIdx = %u (%08x)\n", (unsigned int) pReport->mesgIdx, (unsigned int) pReport->mesgIdx);
   fprintf(stdout, "registers.edi = %ul (%08x)\n", (unsigned long) pReport->registers.edi, (unsigned long) pReport->registers.edi);
   fprintf(stdout, "registers.esi = %ul (%08x)\n", (unsigned long) pReport->registers.esi, (unsigned long) pReport->registers.esi);
   fprintf(stdout, "registers.ebp = %ul (%08x)\n", (unsigned long) pReport->registers.ebp, (unsigned long) pReport->registers.ebp);
   fprintf(stdout, "registers.esp = %ul (%08x)\n", (unsigned long) pReport->registers.esp, (unsigned long) pReport->registers.esp);
   fprintf(stdout, "registers.ebx = %ul (%08x)\n", (unsigned long) pReport->registers.ebx, (unsigned long) pReport->registers.ebx);
   fprintf(stdout, "registers.edx = %ul (%08x)\n", (unsigned long) pReport->registers.edx, (unsigned long) pReport->registers.edx);
   fprintf(stdout, "registers.ecx = %ul (%08x)\n", (unsigned long) pReport->registers.ecx, (unsigned long) pReport->registers.ecx);
   fprintf(stdout, "registers.eax = %ul (%08x)\n", (unsigned long) pReport->registers.eax, (unsigned long) pReport->registers.eax);
   fprintf(stdout, "registers.eflags = %ul (%08x)\n", (unsigned long) pReport->registers.eflags, (unsigned long) pReport->registers.eflags);
   fprintf(stdout, "registers.pc = %08x\n", (unsigned int) pReport->registers.pc);
   fprintf(stdout, "\nREST NOT SHOWN\n\n");

   return (RptHandle)pReport;
}

Check for errors in this code, as I wrote it on the fly without testing :)

Bingo.

On of the compilers is using word alignment, the other is using byte alignment (packed).

Correcting this will mean finding the setting in the IDE's compiler options, or adding the correct #pragma statement to the source file.

Because #pragma statements are unique to each vendor/compiler, I can't help much as I don't use the Microsoft C environment.


But that is definitely the cause of the problem.

Kent
The output for the above code is


 ReportObject size is 864
DUMP of pReport :
---------------

b5 00 90 00 74 1f 4d 02   50 1f 4d 02 b8 1d 4d 02
1f 00 00 00 00 00 00 00   01 00 00 00 16 02 00 00
d4 f3 a8 01 74 1f 4d 02   b8 f3 01 01 c0 9d 37 02
b0 52 39 02 00 00 00 00   90 2f 04 01 8c 1f 4d 02
00 00 00 00 00 00 00 00   8c 1f 4d 02 49 30 04 01
b0 52 39 02 9c 63 38 02   00 00 00 00 90 2f 04 01
bc 1f 4d 02 d3 09 05 01   b0 52 39 02 9c 63 38 02
00 00 00 00 90 2f 04 01   00 00 00 00 30 20 70 63
00 36 31 20 02 36 5b 00   90 6f 23 02 d0 1f 4d 02
d4 1f 4d 02 49 30 04 01   9c 63 38 02 08 20 4d 02
00 00 00 00 70 bc d3 08   b8 20 4d 02 c2 38 02 01
9c 63 38 02 60 e1 36 02   3c c4 00 00 00 00 00 00
00 00 00 00 00 00 00 00   00 00 00 00 00 00 00 00
ff ff ff ff 00 00 00 00   00 00 00 00 4e 54 34 4e
36 34 41 41 30 30 00 00   49 6e 00 65 6c 20 38 32
30 34 00 20 00 00 4e 4e   54 4d 4c 39 30 30 30 41
54 34 00 00 dd 4d 00 01   84 3a 38 02 48 20 4d 02
63 70 43 50 50 49 49 00   04 00 00 00 4e 34 54 4e
41 41 34 36 34 30 30 30   54 4e 4e 20 30 39 4c 4d
54 41 30 30 50 43 20 34   20 49 49 50 ff ff ff ff
ff ff ff ff ff ff ff ff   ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff   ff ff ff ff 20 50 70 63
ff ff ff ff 9c 63 38 02   e0 d2 37 02 c0 e0 37 02
c0 f2 37 02 48 15 38 02   63 70 20 30 20 31 36 00
fc db 36 02 3c c4 00 00   00 00 00 00 c4 20 4d 02
96 2b 02 01 60 e1 36 02   e4 20 4d 02 76 62 04 01
60 e1 36 02 07 00 00 00   00 00 00 00 00 00 00 00
00 00 00 00 3c c4 00 00   00 21 4d 02 9a 60 04 01
07 00 00 00 84 1d 4d 02   dc da 07 01 50 0e 37 02
00 00 00 00 00 00 00 00   50 0e 37 02 00 00 00 00
00 00 00 00 01 00 00 00   b5 00 00 00 09 00 00 00
98 13 dc 08 09 00 b5 00   00 00 00 00 dc 0f 74 45
ff ff 00 00 53 52 50 54   00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00   00 00 00 00 00 00 00 00
00 00 00 00 58 53 4d 3a   20 41 6c 61 72 6d 20 73
69 67 6e 61 6c 20 64 65   74 65 63 74 65 64 20 2d
20 63 68 65 63 6b 20 74   68 65 20 50 6f 77 65 72
2f 46 61 6e 20 6d 6f 64   75 6c 65 20 6f 72 20 74
68 65 20 53 79 73 74 65   6d 20 4d 6f 6e 69 74 6f
72 20 6d 6f 64 75 6c 65   20 28 58 53 4d 29 2e 00
18 9e 37 02 0f 00 00 00   00 00 00 00 b5 10 00 00
00 00 00 00 0f 00 00 00   00 00 00 15 94 2e 04 01
00 00 00 00 00 00 00 00   00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00   18 9e 37 02 00 00 00 00
00 00 00 00 b5 10 00 00   00 00 00 00 0f 00 00 00
00 00 00 15 73 75 74 6c   20 30 20 31 73 75 74 6c
20 30 20 31 35 00 00 00   73 75 74 6c 00 00 00 00
73 75 74 6c 00 00 00 00   78 1b 4d 02 d4 97 23 02
e5 4d 00 01 00 00 00 00   c2 4d 00 01 88 1b 4d 02
5b f8 31 00 73 75 74 6c   20 30 20 31 35 00 00 00
24 1c 4d 02 00 00 00 00   98 13 dc 08 b5 00 90 00
00 21 4d 02 f0 20 4d 02   b8 1d 4d 02 1f 00 00 00
00 00 00 00 01 00 00 00   16 02 00 00 d4 f3 a8 01
00 00 00 00 02 00 00 00   00 00 00 00 3c c4 00 00


VALUES of pReport :
-----------------

catNum = 181 (000000b5)
rptNum = 144 (00000090)
rptIndex = 8052 (00001f74)
origin = 589 (0000024d)
timeStamp = 38608720 (024d1f50)
action = 31 (0000001f)
intLevel = 0 (00000000)
catName = <&#9786;> (length = 1)
message = <É/&#9830;&#9786;î&#9660;M&#9787;> (length = 8)
mesgIdx = 18720 (00004920)
registers.edi = 4294967295l (ffffffff)
registers.esi = 4294967295l (ffffffff)
registers.ebp = 4294967295l (ffffffff)
registers.esp = 4294967295l (ffffffff)
registers.ebx = 4294967295l (ffffffff)
registers.edx = 37212896l (0237d2e0)
registers.ecx = 37221056l (0237f2c0)
registers.eax = 807432291l (30207063)
registers.eflags = 37149692l (0236dbfc)
registers.pc = 00000000

REST NOT SHOWN
Hello experts,

As per the kdo reference,I think its definitely with the compiler settings.Can anyone help me to set the compiler options in visual studio.I need the help desparately.

Microsoft has a writeup here:  http://msdn2.microsoft.com/en-us/library/2e70t5y1.aspx

I'd start by placing this line in front of the struct:

#pragma pack push 4


and then after the struct adding:

#pragma pack pop



Kent

Hi Kdo,

Do you want me to add in this way.....

#pragma pack push 4

struct
{



};
#pragma pack pop

infront of every structure...

The alignment is probably the Microsoft default of 8 and you need 4.

You can place the pair around every struct, but it definitely easier to just insert them so that all structs are between the two #pragma statements.

But make sure that no #include statements are in between them or you'll affect other behavior.


Kent
Hi Kdo,

I tried placing the above 2 statements around every structure and I tried the other way also and compiled but it s throwing the same output.

Are you still running with the line that reports the structure size?

Go ahead and put it back in.  Then we'll experiment with the correct syntax/values for the #pragma statement.


Kent
Just a few questions, tatikor_143 :

1) are you sure that the UNIX output is the correct output ? How did you verify that ?
2) The output you gave for the extra code I added, was that for the same log file as in your first post ?
3) The output you gave for the extra code I added, was that with the Windows code or the UNIX code ?
4) The registers are defined as ULONG, which seems to be 8 bytes in this case - Is that how it's written in the log file ? Are registers written as 8 bytes in the log file ? Same for time_t.
Hi Kdo,

After running with the line that reprts the structure size and also inserting the pragma statements,it prints the same size i,e 864.

Ok.  Let's simplify.  Try this:


#pragma pack 4


structure definitions


#pragma pack 8


Even,after trying the above one,it shows the same size and output.

We really, really, really want to see an 812.   :)

Maybe the structure is aligned on half-word or bytes.

Try replacing the '4' with '2'.  If that's the wrong size, try using '1'.


Kent
Kdo,



I tried all the possibilities,but it throws the same size and output..........
I couldn;t get your point........i,e 812.
How about my questions ?
1) are you sure that the UNIX output is the correct output ? How did you verify that ?

-Iam sure that unix output is the correct output bcos I verified the same with reports that are generated on the live switch and it shows the same.

2) The output you gave for the extra code I added, was that for the same log file as in your first post ?

-yes,exactly....its the same log file.

3) The output you gave for the extra code I added, was that with the Windows code or the UNIX code ?

-Its with the Windows code.


4) The registers are defined as ULONG, which seems to be 8 bytes in this case - Is that how it's written in the log file ? Are registers written as 8 bytes in the log file ? Same for time_t

-yes,its written as 8 bytes in the log file.....

One good thing is.......I am able to get the exact time stamp after trying with _gmtime32_s.My only concern now is with stack and its contents......
Well for gcc, you can use -fpack-struct and this will jam all structures together. You haven't mentioned what gcc flags you're using - this would have a huge impact.
Hi bpmurray,

I am not using gcc on windows.I am using visual studio on windows to compile my program
>> -yes,exactly....its the same log file.
The weird thing is that I can't find the same information anywhere. For example, the value of esi (00f002fb) is nowhere to be found in the dump !! And that dump is the contents of the file.
And on top of that, the values output by my code do not correspond at all with the ones output by your Windows code.
Or am I missing something ?

>> -yes,its written as 8 bytes in the log file.....
Then all I can tell is that the Windows code retrieves the correct values from the log file, UNLESS the UNIX code leaves gaps in the structs. The Windows code doesn't as far as I can tell from the output of my code.

So, either the log file is generated incorrectly, or the struct is incorrect.

What's the structure of the file ? The struct suggests that the first two bytes are the value catNum, the next two bytes are the value rptNum, etc. Are there gaps in the file ?
Hi tatikor,

I found a description of the Visual Studio (compiler) command line switches here:

  http://forums.mozillazine.org/viewtopic.php?t=338845

Instead of the #pragma statements (which the compiler is obviously ignoring) use this command line switch:

  /Zp4



Kent
How exactly it should be included in the program?

Hi Kdo,

I the project properties tab,I set the tab for structure allignment options to /Zp4 and I also tried with all other options but still the same output.
>> I the project properties tab,I set the tab for structure allignment options to /Zp4 and I also tried with all other options but still the same output.
I think the Visual C++ code is already correctly aligned on 4 bytes, so it's normal that the behaviour doesn't change.

Can you confirm that this is the file structure :

    2 bytes : catNum
    2 bytes : rptNum
    2 bytes : rptIndex
    2 bytes : origin
    8 bytes : timeStamp
    2 bytes : action
    2 bytes : intLevel
    32 bytes : catName
    256 bytes : message
    2 bytes : mesgIdx
    8 bytes : edi
    8 bytes : esi
    8 bytes : ebp
    8 bytes : esp
    8 bytes : ebx
    8 bytes : edx
    8 bytes : ecx
    8 bytes : eax
    8 bytes : eflags
    4 bytes : pc
    104*4 bytes : stack
    12*4 bytes : ras

For a total of 850 bytes.
If not, then can you show the correct structure of the file ? ie. how many bytes for each value ?
Oh, and can you do a few sizeof()'s in both the UNIX and the Windows code ? I suspect that you'll find differences :

    sizeof(UINT16)
    sizeof(ULONG)
    sizeof(time_t)
    sizeof(int)

Can you post the values of these sizeof()'s for both the UNIX and the Windows code ?
Hi tatikor_143,

To change structure packing in VC:

1. Right click on project - Select Settings...
2. Select the C/C++ Tab.
3. Select Category : Code Generation
4. Select the Struct member Alignment you wish.

Paul
Hi Infinity,

I am very glad to inform that I got the output on windows same as on unix after changing the structure reportObject.In Unix the reortObject size was 812 but it was 856 on Windows.Then I changed the size of the structure members to set the size same as on Unix.It worked well and I am able to see the exact output on Windows also.

But one concern with the timestamp........

On windows it is not accepting _gmtime_s() function.I tried with _gmtime32_s(),It works well but when I compile and run,it throws an popup window error in between and it terminates the program without showing the error.Please help me out in this also.....

and one more issue is.........

On winows

Stack (top = 0888CDD8):

on Unix

Stack (top = 0x888cdd8):

How can I get the same output for the above in windows also.

The statement the print this is fprintf(fd,"\nStack (top = %p):", realStackTop);

I tried chaniging p to x but didn't work.


Thanks for all your efforts and time ..........

Please help to resolve the above issues also......


"%x" will display hex values with lower case letters.
"%X" will display hex values with upper case letters.

Hi Kdo,
I tried %x already,It displays addresses in lower case only but my concern is how to display it as 0x?
>> I am very glad to inform that I got the output on windows same as on unix after changing the structure reportObject.
So, the registers weren't 8 bytes, but 4 bytes in the file ?

>> The statement the print this is fprintf(fd,"\nStack (top = %p):", realStackTop);
Use %08x instead of %p. Note the 0 to add 0's to the front of the address if needed :

    fprintf(fd,"\nStack (top = %08x):", (unsigned int) realStackTop);

>> On windows it is not accepting _gmtime_s() function.I tried with _gmtime32_s(),It works well but when I compile and run,it throws an popup window error in between and it terminates the program without showing the error.Please help me out in this also.....

Check the return value of _gmtime32_s(). Is it equal to EINVAL ? If so, an error occurred, and you shouldn't use theTime !
What's the sizeof(time_t) ? Is it 4 bytes or 8 bytes (ie. 32 bits or 64 bits) ?

Refer to this page for more info :

http://msdn2.microsoft.com/en-us/library/3stkd9be(VS.80).aspx

Oh btw, theTime is still defined as follows, isn't it ?

    struct tm theTime;
>> I tried %x already,It displays addresses in lower case only but my concern is how to display it as 0x?
Oh, you want to display as 0x ? Then you need to add that yourself :

    fprintf(fd,"\nStack (top = 0x%08x):", (unsigned int) realStackTop);

or :

    fprintf(fd,"\nStack (top = 0x%p):", realStackTop);
Hi Infinity,


size of time_t is now 4 bytes and it is also struct tm theTime.
And is the return value of _gmtime32_s() OK ? And that of strftime() - is it > 0 ?
Hi Kdo,

I tried finding out the return values but its not printing the return values.It terminates before that.
Ok, that's weird - there seems to be something wrong with the _gmtime32_s() implementation. Try this :

    gmtime_r(&(pReport->timeStamp), &theTime);
    strftime(timeString,  sizeof(timeString), "%d/%m/%Y %H:%M:%S", &theTime);

with this define :

    #define gmtime_r(clock, result)     (*((struct tm*) (result)) = *gmtime((const time_t*) (clock)), ((struct tm*) (result)))

and theTime defined like this :

    struct tm theTime;


If that still doesn't work, then try this test program :

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define gmtime_r(clock, result)     (*((struct tm*) (result)) = *gmtime((const time_t*) (clock)), ((struct tm*) (result)))

int main(void) {
  time_t timeStamp = 0;
  struct tm theTime = { 0 };
  char timeString[32] = { 0 };
  time(&timeStamp);
 
  gmtime_r(&timeStamp, &theTime);
  strftime(timeString,  sizeof(timeString), "%d/%m/%Y %H:%M:%S", &theTime);

  fprintf(stdout, "gmtime_r : %s\n", timeString);

  system("PAUSE");  
  return 0;
}
When I ran the above program separatly in an new sorce file,it gave the output as

gmtime_r : 05/01/2007 21:10:55

but when I included in my program,it throws the same erroe and terminates .
OK, two things :

1) can you remove the #include <endian.h> and see if it compiles ? I don't think you need it.

2) can you check the value of pReport->timeStamp just before the gmtime call, and post it here ?
1)I have not added  <endian.h> this time bcos I dont reqire this anymore.

2) Here are the values of pReort->timestamp

1165234138
1165234140
1165234140
1165234140
1165234140
1165234140
1165234140
1165234140
1165234140
endian.h is not interfering now, and the timestamps look ok.

Can you post the exact code you are using now and that generates the error ?
Hi tatikor_143

For the formatting issue, try "%P" instead of "%p". This will only be defined under windows so if you can use %X it would be more portable.

On the time issue, it sounds like you may have have the wrong libraries linked. What libraries are you linking with? The compile and link command lines should be enough.

Paul
Hi Infinity,

Please find the code below
 
  struct tm theTime;
 _gmtime32_s(&pReport->timeStamp, &theTime);
 strftime(timeString,  sizeof(timeString), "%d/%m/%Y %H:%M:%S", &theTime);

One more issue is;

I am using ioctl on Windows,Could you please tell me the header that has to included for ioctl.
Infinity08>> Can you post the exact code you are using now and that generates the error ?

I meant the complete code - like you posted earlier. I'll try to compile it over here, and see if I get the same problem.


tatikor_143>> I am using ioctl on Windows,Could you please tell me the header that has to included for ioctl.

As I said earlier :

Infinity08>> You can use DeviceIOControl instead of ioctl :
Infinity08>> http://msdn.microsoft.com/library/default.asp?url=/library/en-us/devio/base/deviceiocontrol.asp

ioctl is not supported under Windows - it is a UNIX call.
Hi Infinity,

I will post the code soon.

I am not able to convert all the records from the binary log file to ascii format.The issue is the binary log file contains 172 records.When I am running it on Unix.It is displaying all the records but when I run On Visual Studio it prints till 31 records and it directly jumps to 145th record and it prints till 170.I tried to resolve the error but I couldn't find the possible solution

I would be thankful to you if you can help in this.

Thanks
-tatikor
Hi Infinity,

I resolved the timing issue aftyer reading the documents.In windows there is a bit change in passing the arguments.

in Unix:

gmtime32_s(&pReport->timeStamp, &theTime);
 strftime(timeString,  sizeof(timeString), "%d/%m/%Y %H:%M:%S", &theTime);

in Windows:

_gmtime32_s(&theTime, &(pReport->timeStamp));
 strftime(timeString,  sizeof(timeString), "%d/%m/%Y %H:%M:%S", &theTime);

It worked well and giving the required output.

My one and only issue is now

As I mentioned in my previous comment,I am not able to diaplay all the records as on unix.It continously prints till 32 and the skips directly to 145 leaving all the records in between.


Pls help me to resolve this issue.
Hi,

I am trying to allocate memory to a structure during run time using calloc function in visual studio but I am able to allocate only few chunks of memory.How to get the required memory from heap i,e how to get more memory from heap during run time.
>> I resolved the timing issue aftyer reading the documents.In windows there is a bit change in passing the arguments.

Must have missed the () for the & operator ... sorry. Copy-paste isn't always good :)

>> I am not able to diaplay all the records as on unix.It continously prints till 32 and the skips directly to 145 leaving all the records in between.

In rptFileInfoGet(), check if these values are correct :

   info_p->numberOfRecords = rptFile_p->logFileHeader.numberOfRecords;
   info_p->oldestRecord = rptFile_p->logFileHeader.oldestRecord;
   info_p->newestRecord = rptFile_p->logFileHeader.newestRecord;
   info_p->creationTime = rptFile_p->logFileHeader.creationTime;

And in rptObjectRead(), add a few diagnostic messages whenever NULL is returned :

   if (NULL == pReport) {
      fprintf(stderr, "rptObjectRead : ALLOCATION FAILED\n");    /* <- this line */
      return (RptHandle)NULL;
   }

   if (nBytes <= 0) {
      fprintf(stderr, "rptObjectRead : READ FAILED\n");    /* <- this line */
      free(pReport);
      return (RptHandle)NULL;
   }

And then check the error output for these messages.


>> I am trying to allocate memory to a structure during run time using calloc function in visual studio but I am able to allocate only few chunks of memory.How to get the required memory from heap i,e how to get more memory from heap during run time.

Just ask for more memory ...

How much memory are you trying to allocate ? And what is the code you're using for that ?
Hi Infinity,

I inserted the above diag messages.It throws read failed error so many times.
Could you please tell me the possible solution for the above issue.I need the experts help desparately.
Try this function :

RptHandle rptObjectRead(
   int fd
)
{
   int nBytes;
   ReportObject* pReport = NULL;

   pReport = (ReportObject*) malloc(sizeof(ReportObject));
   if (NULL == pReport) {
      return (RptHandle)NULL;
   }
   memset(pReport, 0, sizeof(ReportObject));
   nBytes = fread((char*)pReport, sizeof(ReportObject), 1, fd);
   if (nBytes <= 0) {
      free(pReport);
      return (RptHandle)NULL;
   }
   return (RptHandle)pReport;
}

Also modify all occurrences of :

int fd -> FILE *fd
open() -> fopen() : http://www.cplusplus.com/reference/clibrary/cstdio/fopen.html
read() -> fread() : http://www.cplusplus.com/reference/clibrary/cstdio/fread.html
lseek() -> fseek() : http://www.cplusplus.com/reference/clibrary/cstdio/fseek.html
write() -> fwrite() : http://www.cplusplus.com/reference/clibrary/cstdio/fwrite.html
close() -> fclose() : http://www.cplusplus.com/reference/clibrary/cstdio/fclose.html

The function arguments change, so you'll have to modify the code around these functions too !!!

And if there are other I/O operations, replace them with their standard stdio.h equivalent.

Some examples (look good at all the changes - some of them might get overlooked on first sight - do a diff if needed) :

1) in rptFileOpenLog(), this :

   rptFile_p->fd = open(filename, O_RDWR, 0);
   if (rptFile_p->fd < 0) {
     printf("In rptFileOpenLog, Failed open fd\n");
      return E_FAIL;
   }
   printf("In rptFileOpenLog, fd=%d\n",rptFile_p->fd);
   if (lseek(rptFile_p->fd, 0, SEEK_SET) < 0) {
   printf("In rptFileOpenLog, Failed lseek fd\n");
      result = E_FAIL;
   }

   if (SUCCEEDED(result)) {
      rptFile_p->name = (char*)strdup(filename);
      printf("succeeded open file %s\n", filename);
   } else {
      close(rptFile_p->fd);
   }

becomes :

   rptFile_p->fd = fopen(filename, "rw");
   if (rptFile_p->fd == NULL) {
     printf("In rptFileOpenLog, Failed fopen fd\n");
      return E_FAIL;
   }
   printf("In rptFileOpenLog, fd=%d\n",(int) rptFile_p->fd);
   if (fseek(rptFile_p->fd, 0, SEEK_SET) != 0) {
   printf("In rptFileOpenLog, Failed fseek fd\n");
      result = E_FAIL;
   }

   if (SUCCEEDED(result)) {
      rptFile_p->name = (char*)strdup(filename);
      printf("succeeded open file %s\n", filename);
   } else {
      fclose(rptFile_p->fd);
   }


2) in rptFileRecordGet(), this :

      if (lseek(rptFile_p->fd, FileRecToSeek(rptFile_p, recordIndex), SEEK_SET) > 0) {
//          printf("In rptFileRecordGet, lseek OK, recordIndex=%x, seekIndex=%x, fd=%x\n",
//                 recordIndex, FileRecToSeek(rptFile_p, recordIndex), rptFile_p->fd);
         rptHandle = rptObjectRead(rptFile_p->fd);
      }

becomes :

      if (fseek(rptFile_p->fd, FileRecToSeek(rptFile_p, recordIndex), SEEK_SET) != 0) {
//          printf("In rptFileRecordGet, lseek OK, recordIndex=%x, seekIndex=%x, fd=%x\n",
//                 recordIndex, FileRecToSeek(rptFile_p, recordIndex), rptFile_p->fd);
         rptHandle = rptObjectRead(rptFile_p->fd);
      }
Hi Experts,

I need  help from you people in reolving an issue regarding BIg Endian Little Endian .

My code works for all the report log files and it converts the given  binary report log file into ascii format but it converts only those report log files which has been generated on pentium machine bcos I am running the application on Windows.I am not able to convert the report log files which are generated on motorola machine bcos it mismatches with the big endian format.

Is there any possibilty that I can use my existing code for both motorola and pentium logs so that I can use myu application for both types opf logs.

I need the help on this as soon as possible.Pls help me to do the same.
Do you have a way to detect on which machine the log file has been generated ? ie. little endian or big endian.

If so, you can just execute different code ...
Yes,I have a way to detect the machine type of the log file.
You can use a functions like these to switch endianness :

UINT16 switch_endian_2(UINT16 *x) {
  if (x) {
    return (*x = (((*x << 8) & 0xFF00) | ((*x >> 8) & 0x00FF)));
  }
  else {
    return 0;
  }
}

UINT32 switch_endian_4(UINT32 *x) {
  if (x) {
    return (*x = (((*x << 24) & 0xFF000000) | ((*x << 8) & 0x00FF0000) | ((*x >> 8) & 0x0000FF00) | ((*x >> 24) & 0x000000FF)));
  }
  else {
    return 0;
  }
}

to switch 2 bytes and 4 bytes respectively (IN PLACE). The first can be used for UINT16, the second for time_t, int, etc.

Use like this :

    UINT16 test = 0x1234;
    switch_endian_2(&test); // now : test = 0x3412

    unsigned int test = 0x12345678;
    switch_endian_4(&test); // now : test = 0x78563412
Hi Infinity,

Could you Please help me to solve this.

When I am trying to convert a log report,it prints some records and after a while it terminates throwing an error message saying "unable to allocate memory for symbol file".Please help me out on this as this causing a serious breakout to my project since it is not converting all the records.This is the only issue left for me.

In   <<<convRprfile.c>>>>

      if ((numEntries = getLoadAddrs(&loadPts, *symbolFileName, &ErrorCode))==0 )
            {
                  
            switch (ErrorCode)
                  {
                  case LOAD_ADDRS_MALLOC_ERROR:
                        fprintf(stderr, "Unable to allocate memory for symbol file\n");
                        break;
                  case LOAD_ADDRS_FILE_ERROR:
                        fprintf(stderr, SYMBOL_FILE_NOT_FOUND, symbolFileName);
                        break;
                  case LOAD_ADDRS_NAME_ERROR:
                        fprintf(stderr, "Unable to load name from symbol file\n");
                        break;
                  }      
            exit(1);
            }

  and in rasTrace.c it gets called.

                     

/* MISC: RENAME: RASTRACC rasTrace = */
/* EDITION AA03, TOOLS LEN.128 (97/10/09 11:51:08) -- CLOSED */
/**********************************************************************
 * Module: rasTrace.c
 *
 * Modification history:
 *                  1.0, 09/16/92, Michael Powers
 *                   written
 *
 * Description: Given a Thor symbol table and a list of RAS values,
 *            this routine prints the RAS trace in terms of procedure
 *            names and offsets.
 *
 *
 **********************************************************************/
 
#include <stdio.h>
#include <sys/param.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#include "stdafx.h"
#include "rasTrace.h"



 
#define MAXBUF            1024
#define NAME_SIZE      1024
 
static int countEntries(FILE *stream);
static int readSymFile(FILE *stream, char *name, int *address);
static char *strDup(char *origStr);
 

/**********************************************************************
 *
 * Function      : getLoadAddrs
 *
 * Description      : read the symbol file for the start address of each
 *              SL-1 routine. Create the array of symbolAddrs.
 *
 * Returns      : int 0 and error code set if failure,
 *                  otherwise count of entries
 *            
 *
 *
 *
 **********************************************************************/
int getLoadAddrs(symbolAddrs **array, char *symFile, int *ErrorCode)
{
#define      ARRAY_BASE_SIZE      1000000
#define      ARRAY_SIZE_INCR      1000
      FILE *stream;
      int address;
      char name[NAME_SIZE];
      long arrayActualSize;
    int i=0;

      stream = fopen(symFile, "r+");
      if (!stream)
      {  
            *ErrorCode = LOAD_ADDRS_FILE_ERROR;
            return(0);
      }
   
      *array = (symbolAddrs *)calloc(ARRAY_BASE_SIZE , sizeof(symbolAddrs));

      if (!*array)
      {  
            printf("Hai\n");//It throws error from here........
            *ErrorCode = LOAD_ADDRS_MALLOC_ERROR;
            return(0);
      }
      arrayActualSize = ARRAY_BASE_SIZE;
 
      /*
       *  fill the array
       */
//      i = 0;
      while (readSymFile(stream, name, &address))
            {/* get the next entry */
            /*
             *
             */
            //      printf("hello\n");
            //if ((name[0] != '_') && (name[1] != '_'))
            //      {/* one of ours */
                  if (i >= arrayActualSize)
                        {/* reallocate the array */
                        arrayActualSize += ARRAY_SIZE_INCR;
                        free(*array);
                  
                        *array = (symbolAddrs *)realloc(*array,
                              arrayActualSize *sizeof(symbolAddrs));
                        if (!*array)
                              {
                              *ErrorCode = LOAD_ADDRS_MALLOC_ERROR;
                              return(0);
                              }
                        }/* reallocate the array */
                  (*array)[i].address = address;
                  (*array)[i].name = strDup(name);
                  if (!(*array)[i].name)
                        {
                        *ErrorCode = LOAD_ADDRS_NAME_ERROR;
                        return(0);
                        }
                  
                  
                  ++i;
                  
            //      }/* one of ours */
            }/* get the next entry */

      //printf("Hai\n");            
      
       fclose(stream);
 
      *ErrorCode = LOAD_ADDRS_OK;
       return(i-1);
      
}      /* end of function getLoadAddrs */
 

/**********************************************************************
 *
 * Function      : interpretRAS
 *
 * Description      : Find the closest global for this address, print it
 *              and the offset
 *
 * Input
 *
 * Output
 *       functionName -      buffer passed in by caller to hold resultant
 *                  function namem
 *      functionOffset-      Resultant offset into the function
 * Returns      : void
 *
 *
 *
 **********************************************************************/
int interpretRAS(long targetAddr, symbolAddrs *loadPts, int numEntries,
              char **functionName, int *functionOffset)
{
      
      int closestGlobal;
      int smallestOffset;
      int i=0;
    int foundOne;
    foundOne = 0;
      smallestOffset = 0x7fffffff;
      for (i=0; i<=numEntries; i++)
            {/* check this entry */
             if (loadPts[i].address <= targetAddr)
                  {/* could be in this function */
                  if ((targetAddr - loadPts[i].address) < smallestOffset)
                        {/* better fit */
                             smallestOffset = targetAddr - loadPts[i].address;
                              closestGlobal = (i);
                              foundOne = 1;
                        }/* better fit */
            }/* could be in this function */
            }/* check this entry */
      if (foundOne)
      {/* return the best fit to caller */

            *functionName = loadPts[closestGlobal].name;
            *functionOffset = smallestOffset;
            
            return (1);
      }/* print the best fit */
      else
      {
            return(0);
      }

}      /* end of function interpretRAS */
 

/**********************************************************************
 *
 * Function      : countEntries
 *
 * Description      : Count the number of entries in this file that start
 *              with __. Rewind the file.
 *
 * Returns      : int = the count
 *
 *
 *
 **********************************************************************/
//static int countEntries(FILE *stream)
//{
      //static int count;
      //int address;
      //char name[NAME_SIZE];
 
      //count = 0;
      //while (readSymFile(stream, &name[0], &address))
      //      {/* get the next entry */
      //      if ((name[0] == '_') && (name[1] == '_'))
            //      count++;
      //      //}/* get the next entry */
   // rewind(stream);
      //printf("%d",count);
      //return(count);

//}      /* end of function countEntries */
 

/**********************************************************************
 *
 * Function      : readSymFile
 *
 * Description      : read the next line from the file, set the name and
 *              address values.
 *
 * Returns      : int = 1 if successful, 0 otherwise
 *
 *
 *
 **********************************************************************/
static int readSymFile(FILE *stream, char *name, int *address)
{
#define SYM_FORMAT      "%x %c %[^\n] \n"
      static char buffer[MAXBUF];
      static char dummy[2];
      
      if (fgets(buffer, MAXBUF, stream) != NULL)    
            {/* read a line at a time */          
            if (sscanf(buffer, SYM_FORMAT, address, &dummy, name) == 3)
                  
            //      printf("Hai\n");
                  return(1);
               
            }/* read a line at a time */
 
      return(0);
}      /* end of function readSymFile */
 

/**********************************************************************
 *
 * Function      : strDup
 *
 * Description      : replacement for strdup
 *
 * Returns      : char *, ptr to copy of string
 *
 *
 *
 **********************************************************************/
static char *strDup(char *origStr)
{
      int len;
      char *newStr;
 
      if (!origStr)
            {/* nothing to dup */
            return(NULL);
            }/* nothing to dup */
 
      len = strlen(origStr);
      
      newStr = malloc(len+1);
      if (!newStr)
            {/* bad malloc */
            return(NULL);
            }/* bad malloc */
      
      strcpy(newStr, origStr);
      
      return(newStr);
}      /* end of func strDup */

                                                                 <<rasTrace.h>>>>>>


#ifndef RASTRACE_H
#define RASTRACE_H


 
typedef struct
{
      char *name;
      long address;
      
} symbolAddrs;
 
#define      LOAD_ADDRS_OK      1
#define      LOAD_ADDRS_MALLOC_ERROR      2
#define      LOAD_ADDRS_FILE_ERROR      3
#define      LOAD_ADDRS_NAME_ERROR      4
 
int getLoadAddrs(symbolAddrs **array, char *symFile, int *ErrorCode);
int interpretRAS(long targetAddr, symbolAddrs *loadPts, int numEntries,
              char **functionName, int *functionOffset);
#endif /* RASTRACE_H */
/* EDITION AA01, TOOLS LEN.150 (98/05/26 09:34:06) -- CLOSED */
#ifndef RASTRACE_H
#define RASTRACE_H
 
typedef struct
{
      char *name;
      long address;
      
} symbolAddrs;
 
#define      LOAD_ADDRS_OK      1
#define      LOAD_ADDRS_MALLOC_ERROR      2
#define      LOAD_ADDRS_FILE_ERROR      3
#define      LOAD_ADDRS_NAME_ERROR      4
 
int getLoadAddrs(symbolAddrs **array, char *symFile, int *ErrorCode);
int interpretRAS(long targetAddr, symbolAddrs *loadPts, int numEntries,
              char **functionName, int *functionOffset);
#endif /* RASTRACE_H */

Sounds like you are corrupting your heap. This would do it:

                        free(*array);
                 
                        *array = (symbolAddrs *)realloc(*array,
                              arrayActualSize *sizeof(symbolAddrs));

Dont free before realloc.

Paul
Hi Paul,

I tried the above solution but the thing is its not entering into the loop which reallocates the memory on heap.

Besides I decreased the size of ARRAY_BASE_SIZE to 200000 instead of 1000000 then It prints more number of records than the previous one and prints the same error after some time leaving most of the records.

 
Now its entering inside the loop where it reallocates the memory after reducing the size of ARRAY_BASE_SIZE .But it still printing the same error but from the place where iot reallocates the memory and leaving some records to convert.
Make sure that all memory is cleaned up (this could be due to a memory leak). ie. for every call to malloc/calloc/realloc, there has to be a corresponding call to free.
HI Infinity,

I tried placing free at the apporpriate locations to free the memory,but it is throwing run time error.
Then you didn't place them at the correct locations :) Where did you place them ?
In getloadAddrs function at the end of the function before return.
I hope you didn't free the array in that function, because the information in the array will be used outside of the function too. That would explain the runtime error.

Question : do you understand pointer- and allocation mechanics in C ?
Hi Infinity,

Even though the array is used outside the function,since it is in a while loop it returns to the same function again and terminates from there.

The above code function works well in unix without throwing memory allocation error.

Question : do you understand pointer- and allocation mechanics in C ?

Answer: Yes, I understand the concept of  pointer and memory allocation in C.
malloc returns a pointer and returns the memory asked by the user and the starting address will be stored in the pointer whereas in calloc memory is allocated but fills all the memory with '/0'.when we free it looks at the padding bits to know the memory allocated and frees the allocated memory.

Correct me if I am wrong.
 
>> Even though the array is used outside the function,since it is in a while loop it returns to the same function again and terminates from there.
That doesn't matter. Once you free the memory, you can't use it any more. In rptObjectPrint() you call getloadAddrs() and use the returned array after that. But at the end of getloadAddrs(), you freed the array.
The fact that it works under Unix, doesn't mean the code is correct. It only means that the memory was not yet re-used by the application the moment you wanted to use it.

>> Answer: Yes, I understand the concept of  pointer and memory allocation in C.
What you explained is not the concept, but the internal operation.
Each memory block has a life cycle : it gets allocated, then used, and at the end it gets freed. Before and after this life cycle, the memory should NOT be used unless for very specific cases (not the case for this program). When you want to use a block of code, you need to allocate it BEFORE you use it, and de-allocate it AFTER you don't need it any more. And you need to do that in all cases, even for error cases.
If a block of memory remains in memory without getting freed, that part of the memory can NOT be re-used by the application. So, if you don't free (large) blocks of memory, you'll soon run out of memory, and the next allocation will fail.

So, you need to check whether every block of heap memory you use has an allocation BEFORE it and a de-allocation AFTER it, for ALL cases.

Note that the above does not apply to stack memory !! Only to heap memory !!
Hi Infinity,

Thanks for your suggestion.....

array is local to getloadaddrs function,then how can we free it in rptobjectprint function from where the function being called and moreover when it returns from that particular function memory is freed automatically without using any free.

Thanks
Okay, basic C memory lesson :

We'll look at two types of memory :

1) stack memory : this memory does not need to be allocated using malloc or calloc. Instead, the stack pointer is incremented to make enough room to contain the variable. When the function returns, the stack pointer is decremented again, so the variable can not be used any more.
Here are some examples of variables that are stored in stack memory :

        int test;
        char arr[10];
        float *ptr; /* note that in this case, only the pointer is put on the stack, not the actual memory containing the float */

2) heap memory : this memory contains all data blocks that were allocated using malloc and calloc. The allocated memory block stays available untill you call a free on it. Even if you exit a function. However, you need to take care of de-allocation yourself by using free once you don't need it any more, otherwise the memory will not be available for re-use.
Here are some examples of variables that are stored in heap memory :

        char *str = malloc(20); /* a 20 characters long string (including null byte) in heap memory, pointed to by the stack variable str */
        float *ptr = calloc(1, sizeof(float)); /* a float in heap memory, pointed to by the stack variable ptr */


And an example that shows a function that allocates memory for a string, and is called from another function, that prints it and then frees it :

    char *fun1() {
      char *str = (char*) calloc(22, sizeof(char));
      strncpy(str, "this is a test string", 21);
      str[21] = '\0';
      return str;
    }

    void fun2() {
      char *str2 = fun1();
      fprintf(stdout, "%s\n", str2);
      free(str2);
      return;
    }

str and str2 are context variables, and are on the stack when the function they're in is executed. They will both point to the same 22 characters long string on the heap. After returning from fun2(), that string will not be available on the heap any more.

Does that make things clearer ?
Hi Infinity,

I tried a lot to resolve the memory leak problem but I couldn't.Could you please tell where exactly thr free has to be placed so that I can reallocate the memory for the further calls to calloc.

A prompt response is highly apprecited.

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Infinity,

I already posted the code.

Thanks
There have been several changes to the code since then, haven't there ? If I'm not working with the latest code, I'll probably re-introduce old bugs or propose wrong solutions.

No, I have not changed anything in the code except fot the structure reportObjectPrint structure and this structure in no where involved for this issue?
Sorry I haven't had the time to dive into the code and look for possible memory leaks. I'm quite busy at work, and this would take an hour at least and probably more.

Anyway, did you have any luck finding it yourself ?

Something that can help you in understanding how and when your code allocates and de-allocates memory, is by adding debug output that shows exactly what happens in your code. In this case, what you're especially interested in is the (de-)allocation of memory of course ...