/*
 * get_toc_byte_sex() guesses the byte sex of the table of contents of the
 * library mapped in at the address, addr, of size, size based on the first
 * object file's bytesex.  If it can't figure it out, because the library has
 * no object file members or is malformed it will return UNKNOWN_BYTE_SEX.
 */
__private_extern__
enum byte_sex
get_toc_byte_sex(
char *addr,
uint32_t size)
{
     uint32_t magic;
     uint32_t ar_name_size;
     struct ar_hdr *ar_hdr;
     char *p;

	ar_hdr = (struct ar_hdr *)(addr + SARMAG);

	p = addr + SARMAG + sizeof(struct ar_hdr) +
	    rnd(strtoul(ar_hdr->ar_size, NULL, 10), sizeof(short));
	while(p + sizeof(struct ar_hdr) + sizeof(uint32_t) < addr + size){
	    ar_hdr = (struct ar_hdr *)p;
	    if(strncmp(ar_hdr->ar_name, AR_EFMT1, sizeof(AR_EFMT1) - 1) == 0)
		ar_name_size = strtoul(ar_hdr->ar_name + sizeof(AR_EFMT1) - 1,
				       NULL, 10);
	    else
		ar_name_size = 0;
	    p += sizeof(struct ar_hdr);
	    memcpy(&magic, p + ar_name_size, sizeof(uint32_t));
	    if(magic == MH_MAGIC || magic == MH_MAGIC_64)
		return(get_host_byte_sex());
	    else if(magic == SWAP_INT(MH_MAGIC) ||
		    magic == SWAP_INT(MH_MAGIC_64))
		return(get_host_byte_sex() == BIG_ENDIAN_BYTE_SEX ?
		       LITTLE_ENDIAN_BYTE_SEX : BIG_ENDIAN_BYTE_SEX);
	    p += rnd(strtoul(ar_hdr->ar_size, NULL, 10), sizeof(short));
	}
	return(UNKNOWN_BYTE_SEX);
}
static
void
swap_objc_image_info(
struct objc_image_info *o,
enum byte_sex target_byte_sex)
{
	o->version = SWAP_INT(o->version);
	o->flags = SWAP_INT(o->flags);
}
static
void
swap_objc_property(
struct objc_property *op,
enum byte_sex target_byte_sex)
{
	op->name = SWAP_INT(op->name);
	op->attributes = SWAP_INT(op->attributes);
}
static
void
swap_objc_property_list(
struct objc_property_list *pl,
enum byte_sex target_byte_sex)
{
	pl->entsize = SWAP_INT(pl->entsize);
	pl->count = SWAP_INT(pl->count);
}
static
void
swap_ivar_list_t(
struct ivar_list_t *il,
enum byte_sex target_byte_sex)
{
	il->entsize = SWAP_INT(il->entsize);
	il->count = SWAP_INT(il->count);
}
static
void
swap_method_list_t(
struct method_list_t *ml,
enum byte_sex target_byte_sex)
{
	ml->entsize = SWAP_INT(ml->entsize);
	ml->count = SWAP_INT(ml->count);
}
static
void
swap_message_ref(
struct message_ref *mr,
enum byte_sex target_byte_sex)
{
	mr->imp = SWAP_INT(mr->imp);
	mr->sel = SWAP_INT(mr->sel);
}
static
void
swap_method_t(
struct method_t *m,
enum byte_sex target_byte_sex)
{
	m->name = SWAP_INT(m->name);
	m->types = SWAP_INT(m->types);
	m->imp = SWAP_INT(m->imp);
}
static
void
swap_ivar_t(
struct ivar_t *i,
enum byte_sex target_byte_sex)
{
	i->offset = SWAP_INT(i->offset);
	i->name = SWAP_INT(i->name);
	i->type = SWAP_INT(i->type);
	i->alignment = SWAP_INT(i->alignment);
	i->size = SWAP_INT(i->size);
}
static
void
swap_class_t(
struct class_t *c,
enum byte_sex target_byte_sex)
{
	c->isa = SWAP_INT(c->isa);
	c->superclass = SWAP_INT(c->superclass);
	c->cache = SWAP_INT(c->cache);
	c->vtable = SWAP_INT(c->vtable);
	c->data = SWAP_INT(c->data);
}
Example #11
0
static PyObject *
i_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
    long val;
    int field;
    if (get_long(value, &val) < 0)
        return NULL;
    memcpy(&field, ptr, sizeof(field));
    field = SWAP_INT(field);
    field = SET(field, (int)val, size);
    field = SWAP_INT(field);
    memcpy(ptr, &field, sizeof(field));
    _RET(value);
}
static
void
swap_protocol_list_t(
struct protocol_list_t *pl,
enum byte_sex target_byte_sex)
{
	pl->count = SWAP_INT(pl->count);
}
static
void
swap_class_ro_t(
struct class_ro_t *cro,
enum byte_sex target_byte_sex)
{
	cro->flags = SWAP_INT(cro->flags);
	cro->instanceStart = SWAP_INT(cro->instanceStart);
	cro->instanceSize = SWAP_INT(cro->instanceSize);
	cro->ivarLayout = SWAP_INT(cro->ivarLayout);
	cro->name = SWAP_INT(cro->name);
	cro->baseMethods = SWAP_INT(cro->baseMethods);
	cro->baseProtocols = SWAP_INT(cro->baseProtocols);
	cro->ivars = SWAP_INT(cro->ivars);
	cro->weakIvarLayout = SWAP_INT(cro->weakIvarLayout);
	cro->baseProperties = SWAP_INT(cro->baseProperties);
}
Example #14
0
static PyObject *
i_get_sw(void *ptr, Py_ssize_t size)
{
    int val;
    memcpy(&val, ptr, sizeof(val));
    val = SWAP_INT(val);
    GET_BITFIELD(val, size);
    return PyInt_FromLong(val);
}
Example #15
0
static PyObject *
I_get_sw(void *ptr, Py_ssize_t size)
{
    unsigned int val;
    memcpy(&val, ptr, sizeof(val));
    val = SWAP_INT(val);
    GET_BITFIELD(val, size);
    return PyLong_FromUnsignedLong(val);
}
Example #16
0
static PyObject *
I_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
    unsigned long val;
    unsigned int field;
    if (get_ulong(value, &val) < 0)
        return  NULL;
    memcpy(&field, ptr, sizeof(field));
    field = (unsigned int)SET(field, (unsigned int)val, size);
    field = SWAP_INT(field);
    memcpy(ptr, &field, sizeof(field));
    _RET(value);
}
Example #17
0
void selectPostTool(int x, int y)
{
	switch(shape.type)
	{
	case SELECT_RECTANGLE:
		{
			if(shape.x1 > shape.x2) SWAP_INT(shape.x1, shape.x2);
			if(shape.y1 > shape.y2) SWAP_INT(shape.y1, shape.y2);
			
			shape.w = shape.x2 - shape.x1;
			shape.h = shape.y2 - shape.y1;
			
			shape.type = SELECTED_RECTANGLE;
		}
		break;
	case SELECTED_RECTANGLE:
		{
			RESET_SHAPE();
		}
		break;
	}
}
static
void
swap_protocol_t(
struct protocol_t *p,
enum byte_sex target_byte_sex)
{
	p->isa = SWAP_INT(p->isa);
	p->name = SWAP_INT(p->name);
	p->protocols = SWAP_INT(p->protocols);
	p->instanceMethods = SWAP_INT(p->instanceMethods);
	p->classMethods = SWAP_INT(p->classMethods);
	p->optionalInstanceMethods = SWAP_INT(p->optionalInstanceMethods);
	p->optionalClassMethods = SWAP_INT(p->optionalClassMethods);
	p->instanceProperties = SWAP_INT(p->instanceProperties);
}
Example #19
0
File: sel.c Project: bion/ats
void do_smartsel (GtkWidget *widget, gpointer data)
{
  int i;
  float linamp= (float)pow(10., (double)(sdata->tres/20.));
  float amp, ampsum=0., rmspow, max_peak=0.;
  int x, temp;

  if(sdata->from >  sdata->to) {
    SWAP_INT(sdata->from,sdata->to)
  }

  set_selection(h.viewstart, h.viewend,0,main_graph->allocation.width,
		     main_graph->allocation.width);
  vertex1=0; vertex2=1; //something IS selected
  //set_avec(selection.to - selection.from);

  for(i=0; i<(int)atshed.par; i++) selected[i]=FALSE; //unselect all

  for(i=sdata->from; i < sdata->to+1; i+=sdata->step) {

    if(i >(int)atshed.par-1 || i >(int)sdata->to) break;
    
    for(x=h.viewstart; x < h.viewend; x++) {  //amplitude evaluation
      amp    =ats_sound->amp[i][x];
      switch(sdata->met) {
      case 0: //peak
	if(amp > max_peak) max_peak=amp;
	break;
      case 1: //RMS POW
	ampsum+= amp*amp; 
	break;
      }
    }
   
    switch(sdata->met) {
    case 0: //peak
      if(max_peak >= linamp) selected[i]=TRUE;	
      break;
    case 1: //RMS POW
      rmspow= (float)sqrt((double)ampsum / (double)h.diff ); 
      if(rmspow >= linamp) selected[i]=TRUE;	
      break;
    }

    ampsum=max_peak=0.;
  }

  draw_pixm();
  gtk_widget_destroy (GTK_WIDGET (data));
}
Example #20
0
int chunk_get_ints_endian_safe(Chunk* chunk, int* result, int nb) {
  int i = 0;
  int *src = (int*) (chunk->content + chunk->nb);
  int size = sizeof(int);
  if ((chunk->nb + (size * nb)) <= chunk->max) {
    for (i = 0; i < nb; i++) {
      result[i] = SWAP_INT(src[i]);
    }
    chunk->nb += (nb * size);
    return 0;
  }
  printf("error in chunk_get_ints_endian_safe !\n");
  on_error();
  return 1;
}
static
void
swap_category_t(
struct category_t *c,
enum byte_sex target_byte_sex)
{
	c->name = SWAP_INT(c->name);
	c->cls = SWAP_INT(c->cls);
	c->instanceMethods = SWAP_INT(c->instanceMethods);
	c->classMethods = SWAP_INT(c->classMethods);
	c->protocols = SWAP_INT(c->protocols);
	c->instanceProperties = SWAP_INT(c->instanceProperties);
}
Example #22
0
int chunk_add_ints_endian_safe(Chunk* chunk, int* ptr, int nb) {
  int i = 0;
  int *dest;
  int size = sizeof(int);
  int r = 0;
  if (chunk->max < (chunk->nb + (nb * size))) {
    r = chunk_size_up (chunk, (nb * size));
    if (r < 0) {
      printf("error in chunk_add_ints_endian_safe !\n");
      on_error();
      return 1;
    }
  }
  dest = (int*) (chunk->content + chunk->nb);
  for (i = 0; i < nb; i++) {
    dest[i] = SWAP_INT(ptr[i]);
  }
  chunk->nb += (nb * size);
  return 0;
}
Example #23
0
int matout(char *fullname,char *varname,void *data,int nrows,int ncols,char vartype, char *mode, char endianess)
{
  int  size;
  long nelem;
  int  type,namelen;
  int  mrows,mcols,imagf;
  int i;
  FILE *fs;
  
  mrows = nrows;
  mcols = ncols;
  nelem = mrows*mcols;

  switch (vartype) {
  case 'd':   /* 8-byte doubles */
    type=00;
    size=8;
    double *vard=data;
    if (endianess=='B') { for (i=0;i<nelem;i++) SWAP_DOUBLE(vard[i]); };
    break;
  case 'r':    /* 4-byte reals */
    type=10;
    size=4;
    float *varf=data;
    if (endianess=='B') { for (i=0;i<nelem;i++) SWAP_FLOAT(varf[i]); };
    break;
  case 'l':    /* 4-byte int, row-wise */
    type=20;  
    size=4;
    int *varl=data;
    if (endianess=='B') { for (i=0;i<nelem;i++) SWAP_INT(varl[i]); };
    break;
  case 's':    /* 2-byte signed shorts */
    type=30;
    size=2;
    short *vars=data;
    if (endianess=='B') { for (i=0;i<nelem;i++) SWAP_SHORT(vars[i]); };
    break;
  case 'u':    /* 2-byte unsigned shorts */
    type=40;
    size=2;
    short *varus=data;
    if (endianess=='B') { for (i=0;i<nelem;i++) SWAP_SHORT(varus[i]); };
    break;
    //  case 't':    /* 2-byte unsigned shorts saved as "text" */
    //    type=41;
    //    nbytes = mrows*mcols*2;
  case 't':    /* 1-byte unsigned shorts saved as "text" */
    type=51;
    size=1;
    break;
  case 'b':    /* 1-byte unsigned chars */
  case 'c':    /* 1-byte signed chars */
    type=50;
    size=1;
    break;
  default:
    return (-1);
  }

  if (disable_disk_writing) return (0);

  for (i=0 ; i<nfiles ; i++) {
    if (! *matfile[i]) break;
    if (!strcmp(fullname,matfile[i])) break;
  }
  if (i<nfiles) {
    fs = fd[i];
  } else {
    fs = NULL;
  }
  if (fs == NULL) {
    if ((fs=fopen(fullname,mode))==NULL) {
      sprintf(message,"%s could not be opened because of reason %d",fullname,errno);;
      warn(message);
      return (-1);
    }
    strcpy(matfile[i],fullname);
    fd[i] = fs;
    if ((i==nfiles) && (nfiles<MAXFILES-1)) nfiles++;
  }
  
  imagf=0;
  if (endianess=='B') SWAP_INT(type);
  if (fwrite(&type,sizeof(int),1,fs) != 1) {
    writerr();
    return (-1);
  }
  if (endianess=='B') SWAP_INT(mrows);
  if (fwrite(&mrows,sizeof(int),1,fs) != 1) {
    writerr();
    return (-1);
  }
  if (endianess=='B') SWAP_INT(mcols);
  if (fwrite(&mcols,sizeof(int),1,fs) != 1) {
    writerr();
    return (-1);
  }
  if (endianess=='B') SWAP_INT(imagf);
  if (fwrite(&imagf,sizeof(int),1,fs) != 1) {
    writerr();
    return (-1);
  }
    
  namelen=strlen(varname)+1;
  if (endianess=='B') SWAP_INT(namelen);
  if (fwrite(&namelen,sizeof(int),1,fs) != 1) {
    writerr();
    return (-1);
  }
  if (endianess=='B') SWAP_INT(namelen);
  if (fwrite(varname,(unsigned int)namelen,1,fs) != 1) {  
    writerr();
    return (-1);
  }

  if (fwrite(data,size,nelem,fs) != nelem) {
    writerr();
    return (-1);
  }

  matclose(fullname);
  
  return (0);
}
Example #24
0
void matscan(FILE *fs, int maxVarsToSearch, int returnString)
{
  int  info[5];
  long i;
  long fileptr,tfileptr,tfp;
  long nbyt=0,nelem,skip;
  int  type;
  int  mrows,mcols;
  int  imagf;
  int  namelen;
  long varNumber = 0;
  char varname[80];
  char *stype="";
  int varnum=0;
  Array *a= PushDataBlock(NewArray(&stringStruct, (Dimension *)0));
  long extra=1;
  
  fileptr = ftell(fs);

  if (DEBUG) printf("Entering matscan\n");

  while (1) {
    tfileptr = ftell(fs);
    if (DEBUG) printf("at address %ld \n",tfileptr);
    if (fread(info,4,5,fs)==5) {

      if (info[4] & 0xffff0000) {	// convert header from little endian to big indian
        // info[0] changed to info[4] 2006/3/15 as double type can be 0, hence
        // no way to know big from little endian info[0] for doubles.
        if (DEBUG) printf("swapping!\n");
        for (i=0;i<5;i++) SWAP_INT(info[i]);
      }

      info[0] = info[0]%1000;

      tfp = ftell(fs);

      if (DEBUG) printf("at address %ld \n",tfp);
      if (DEBUG) printf("info = %d %d %d %d %d\n",info[0],info[1],info[2],info[3],info[4]);

      type = info[0]%1000;

      if ((namelen = info[4])<80L) {
        if (fread(varname,1,info[4],fs)==(int)info[4]) {
          if (type==0) {
            // 8-byte doubles 
            stype=p_strcpy("double*8"); nbyt=8;
          } else if (type==10) {
            // 4-byte reals 
            stype=p_strcpy("real*4  "); nbyt=4;
          } else if ((type==120) || (type==20)) {
            // 4-byte int 
            stype=p_strcpy("int*4   "); nbyt=4;
          } else if (type==30) {
            // 2-byte signed (30) shorts 
            stype=p_strcpy("short*2 "); nbyt=2;
          } else if (type==40)  {
            // 2-byte unsigned (40) shorts 
            stype=p_strcpy("ushort*2"); nbyt=2;
          } else if ((type==50) || (type==51))  {
            // 1-byte signed or unsigned chars (50) or text (51)
            stype=p_strcpy("char*1  "); nbyt=1; 
          } else {
            sprintf(message,"Unknown data type %d",type);
            YError(message);
          }
          
          if (returnString) {
            if (varnum!=0) a= PushDataBlock((void *)GrowArray(a, extra));
            a->value.q[varnum] = p_malloc(81);
            sprintf(a->value.q[varnum],"%30s  %s array [%d,%d]",varname,   \
                    stype,info[1],info[2]);
            varnum++;
          } else {
            printf("%30s  %s array [%d,%d]\n",varname,stype,info[1],info[2]);
          }

          mrows=info[1];
          mcols=info[2];
          nelem=mrows*mcols;
          imagf=info[3];
          if (imagf) nbyt=2*nbyt;
          skip = nbyt*nelem;
          if (DEBUG) printf("skiping data part: %ld bytes\n",skip);
          if (skip) fseek(fs,nbyt*nelem,SEEK_CUR);
        }
      }
    } else {
      break;
    }
    if (maxVarsToSearch) {
      if (++varNumber >= maxVarsToSearch) {
        break;
      }
    }
  }
}
Example #25
0
// This routine searches for the existence of "var"
// The search can be limited to the next "maxVarsToSearch" by setting maxVarsToSearch>0
int matfind(FILE *fs, char *var, int maxVarsToSearch)
{
  int  info[5];
  long i;
  long fileptr,tfileptr,tfp;
  long nbyt,nelem,skip;
  long rest,prec;
  int type,mrows,mcols;
  int imagf;
  int namelen;
  long varNumber = 0;
  char varname[80];
  char string[200];

  if (*var=='*') return (1);      // requested variable name matches any array name
  fileptr = ftell(fs);

  if (DEBUG) printf("Entering matfind\n");

  while (1) {

    tfileptr = ftell(fs);

    if (DEBUG) printf("at address %ld \n",tfileptr);

    if (fread(info,4,5,fs)==5) {

      if (info[4] & 0xffff0000) {	// convert header from big endian to little indian
        // info[0] changed to info[4] 2006/3/15 as double type can be 0, hence
        // no way to know big from little endian info[0] for doubles.
        if (DEBUG) printf("swapping!\n");
        for (i=0;i<5;i++) SWAP_INT(info[i]);
      }

      info[0] = info[0]%1000;

      tfp = ftell(fs);

      if (DEBUG) printf("at address %ld \n",tfp);
      if (DEBUG) printf("info = %d %d %d %d %d\n",info[0],info[1],info[2],info[3],info[4]);

      if ((namelen = info[4])<80L) {
        if (fread(varname,1,info[4],fs)==(int)info[4]) {
          if (DEBUG) printf("variable name: %s\n",varname);
          if (matchvarname(varname,var)) {    // success if a (possibly wildcard in "var") match
            fseek(fs,tfileptr,SEEK_SET);
            return (1);
          } else {
            type = *info - 10*(*info/10);
            rest = (*info - type)/10;
            prec = rest - 10*(rest/10);
            switch (prec) {
            case 0: nbyt = 8; break;
            case 1: nbyt = 4; break;
            case 2: nbyt = 4; break;
            case 3: nbyt = 2; break;
            case 4: nbyt = 2; break;
            case 5: nbyt = 1; break;
            default:
              sprintf(string,"Precision specification not available");
              warn(string);
              fseek(fs,fileptr,SEEK_SET);
              return (0);
            }
            mrows=info[1];
            mcols=info[2];
            nelem=mrows*mcols;
            imagf=info[3];
            if (imagf) nbyt=2*nbyt;
            skip = nbyt*nelem;
            if (DEBUG) printf("skiping %ld bytes\n",skip);
            if (skip) fseek(fs,nbyt*nelem,SEEK_CUR);
          }
        }
      }
    } else {
      break;
    }
    if (maxVarsToSearch) {
      if (++varNumber >= maxVarsToSearch) {
        break;
      }
    }
  }
  //lseek(fh,fileptr,SEEK_SET);
  fseek(fs,fileptr,SEEK_SET);
  return(0); 

}
Example #26
0
void Y_ml4read(int nArgs)

{
  char *filename="";
  char *varname="";
  int leave_open = 0;
  
  if (nArgs==2) {
    filename=YGetString(sp-nArgs+1);
    varname=YGetString(sp-nArgs+2);
    leave_open = 0;
  } else if (nArgs==3) {
    filename=YGetString(sp-nArgs+1);
    varname=YGetString(sp-nArgs+2);
    leave_open=YGetInteger(sp-nArgs+3);
  }

  unsigned long bytes_read;
  int type,namelen;
  unsigned long nElements,nBytesToRead;
  int mrows,mcols,imagf;
  FILE *fs;
  int fileptr;
  int endian = 'L';
  int size=0,i;

  fs = openmat(filename);
  if (fs == NULL) YError(p_strncat("Can't open file ",filename,0));

  if (!matfind(fs,varname,50000)) YError(p_strncat("No Such variable ",varname,0));

  fileptr = ftell(fs);
  if (DEBUG) printf("@ position %d\n",fileptr);
  
  bytes_read = fread(&type,sizeof(int),1,fs);
  if (bytes_read==0) {
    matclose(filename);
    YError("Premature end of file");; // end of file
  }
  fread(&mrows,sizeof(int),1,fs);
  fread(&mcols,sizeof(int),1,fs);
  fread(&imagf,sizeof(int),1,fs);
    
  fread(&namelen,sizeof(int),1,fs);

  if (namelen & 0xffff0000) {
    if (DEBUG) printf("Big endian file\n");
    endian = 'B';
    SWAP_INT(type);
    SWAP_INT(mrows);
    SWAP_INT(mcols);
    SWAP_INT(imagf);
    SWAP_INT(namelen);
  }
  type = type%1000;

  if (DEBUG) printf("rows,cols,namelen= %d %d %d\n",mrows,mcols,namelen);

  if (namelen>255) {
    fseek(fs,fileptr,SEEK_SET);  // leave file ptr at begginning of this variable
    matclose(filename);
    YError("Variable name too long!");
  }

  fread(tempvarname,(unsigned int)namelen,1,fs);
  //  if ((*varname!='*') && strcmp(varname,tempvarname)) {  // error if not same varname
  if (!matchvarname(tempvarname,varname)) {  // error if not same varname
    fseek(fs,fileptr,SEEK_SET);  // leave file ptr at begginning of this variable
    matclose(filename);
    YError(p_strncat("Can't find variable",varname,0));
  }

  nElements = (unsigned)mrows*(unsigned)mcols;
  
  Dimension *tmp=tmpDims;
  tmpDims=0;
  FreeDimension(tmp);
  if (mrows<=1) {
    tmpDims= NewDimension(mcols, 1L, (Dimension *)0);
  } else if (mcols<=1) {
    tmpDims= NewDimension(mrows, 1L, (Dimension *)0);
  } else {
    tmpDims= NewDimension(mrows, 1L, (Dimension *)0);
    tmpDims= NewDimension(mcols, 1L, tmpDims);
  }
  
  if (type==0) {
    // 8-byte doubles
    size = 8;
    Array *a= PushDataBlock(NewArray(&doubleStruct, tmpDims));
    double *data = a->value.d;
    bytes_read = fread((void *)data,size,nElements,fs);
    if (endian=='B') { for (i=0;i<nElements;i++) SWAP_DOUBLE(data[i]); }

  } else if (type==10) {
    // 4-byte reals
    size = 4;
    Array *a= PushDataBlock(NewArray(&floatStruct, tmpDims));
    float *data = a->value.f;
    bytes_read = fread((void *)data,size,nElements,fs);
    if (endian=='B') { for (i=0;i<nElements;i++) SWAP_FLOAT(data[i]); }

  } else if ((type==120) || (type==20)) {
    // 4-byte int
    size = 4;
    Array *a= PushDataBlock(NewArray(&intStruct, tmpDims));
    int *data = a->value.l;
    bytes_read = fread((void *)data,size,nElements,fs);
    if (endian=='B') { for (i=0;i<nElements;i++) SWAP_INT(data[i]); }

  } else if (type==30) {
    // 2-byte signed (30) shorts
    size = 2;
    Array *a= PushDataBlock(NewArray(&shortStruct, tmpDims));
    short *data = a->value.s;
    bytes_read = fread((void *)data,size,nElements,fs);
    if (endian=='B') { for (i=0;i<nElements;i++) SWAP_SHORT(data[i]); }

  } else if (type==40) {
    // 2-byte unsigned (40) shorts
    size = 2;
    Array *a= PushDataBlock(NewArray(&shortStruct, tmpDims));
    short *data = a->value.s;
    Array *b= PushDataBlock(NewArray(&longStruct, tmpDims));
    long *data2 = b->value.l;
    bytes_read = fread((void *)data,size,nElements,fs);
    if (endian=='B') { for (i=0;i<nElements;i++) SWAP_SHORT(data[i]); }
    for (i=1;i<=nElements;i++) *(data2++) = (((long)*(data++))|0xFFFF0000)+65535;

  } else if (type==50) {
    // 1-byte signed or unsigned chars (50)
    size = 1;
    Array *a= PushDataBlock(NewArray(&charStruct, tmpDims));
    char *data = a->value.c;
    bytes_read = fread((void *)data,size,nElements,fs);

  } else if (type==51) {
    // text (51)
    size = 1;
    Array *a= PushDataBlock(NewArray(&stringStruct, (Dimension *)0));
    char *buf;
    a->value.q[0] = buf = p_malloc(nElements+1);
    if (DEBUG) printf("strlen: %d\n",(int)strlen((void *)a->value.q[0]));
    //    bytes_read = fread(a->value.q[0],1,nElements,fs);
    bytes_read = fread(buf,1,nElements,fs);
    *((char *)buf + nElements) = 0;  // append a NULL to text string

  } else {
    matclose(filename);
    sprintf(message,"Unknown type %d",type);
    YError(message);
  }

  if (bytes_read!=nElements) {
    fseek(fs,nElements*size,SEEK_CUR);
    matclose(filename);
    if (DEBUG) printf("read:%ld expected:%ld\n",bytes_read,nBytesToRead);
    YError("Premature end of file");
  }

  if (!leave_open) matclose(filename);
}
Example #27
0
int CMakeSip::makeReq(int id, PHONE_CFG * cfg, ADDR *addrExt,STR_64 *str64ExtADDR)
{
   unsigned int iMeth=0;
   unsigned int uiFromLoc=0;
   unsigned int uiFromLen=0;
   strDstAddr.s=(unsigned char *)&spSes->dstSipAddr.strVal;
   strDstAddr.len=(int)spSes->dstSipAddr.uiLen;
   
   
   if(cfg){
      
      if(strcmp(&cfg->szSipTransport[0],"TLS")==0){iIsTCP=0;iIsTLS=1;}
      else if(strcmp(&cfg->szSipTransport[0],"TCP")==0){iIsTCP=1;iIsTLS=0;}
      else if(strcmp(&cfg->szSipTransport[0],"UDP")==0){iIsTCP=0;iIsTLS=0;}
      else {iIsTCP=0;iIsTLS=0;}
      
   }
   
   char *s=buf;
   
   int iPrevId=spSes->cs.iSendS;
   spSes->cs.iSendS=id;
   if(id!=METHOD_ACK)
   {
      if(iPrevId!=spSes->cs.iSendS)
      {
         if(spSes->cs.iSendS==METHOD_OPTIONS){
            spSes->sSendTo.setRetransmit(2,5*T_GT_SECOND);
         }
         else if(iIsTCP || iIsTLS)
            spSes->sSendTo.setRetransmit(7,5*T_GT_SECOND);
         else if(spSes->cs.iSendS==METHOD_REGISTER)
            spSes->sSendTo.setRetransmit(7,1*T_GT_SECOND);
         else  if(spSes->cs.iSendS==METHOD_INVITE)
            spSes->sSendTo.setRetransmit(7,(cfg==NULL || cfg->iNetworkIsMobile)?(6*T_GT_SECOND):(3*T_GT_SECOND));
         else
            spSes->sSendTo.setRetransmit();
      }
      spSes->cs.iWaitS=200;
   }
   else
   {
      spSes->cs.iWaitS=0;
   }
   
   //TODO getITFromZZ
   unsigned int uiCSeq;
#if 1
   if(cfg && id==METHOD_REGISTER)
   {
      if(!cfg->uiSipCSeq){
         //next reg should be with greater CSeq, even app restarts, if call-id is same
         //problem was with SIP Thor on OpenSIPS XS 1.4.5, but not  with FreeSwitch
         
         int get_time();
         cfg->uiSipCSeq=(unsigned int)get_time();
         cfg->uiSipCSeq-=1000000000;
      }
      cfg->uiSipCSeq++;
      uiCSeq=(unsigned int)cfg->uiSipCSeq;
   }
   else if(spSes){
      if(id!=METHOD_ACK && id!=METHOD_CANCEL)spSes->uiSipCseq++;
      uiCSeq=spSes->uiSipCseq;
   }
   else {
      uiCSeq=getTickCount();
      while(uiCSeq>1000000000)uiCSeq-=1000000000;
   }
#else
   static unsigned int  ss=User::TickCount();
   ss++;
   uiCSeq=ss;
   
#endif
   if(!uiCSeq)uiCSeq=1;

   int iReplaceRoute=0;
   
   if(iContactId >(int)sMsg->hldContact.uiCount)
      iContactId=0;

   GET_METH(id,iMeth);
   
   //TODO do we need to send route with cancel msg
#define METHOD_CANCEL_IGNORE 0
   
   struct HOLDER_CONTACT *hc = &sMsg->hldContact;
   HLD_ROUTE *hrr = &sMsg->hldRecRoute;
   
   //do i need to check "&& spSes->sSIPMsg.hldRecRoute.uiCount"?
   if(hc->uiCount<1 && spSes && spSes->sSIPMsg.hldContact.uiCount && sMsg->sipHdr.dstrStatusCode.uiVal>=300){
      hc = &spSes->sSIPMsg.hldContact;
      hrr = &spSes->sSIPMsg.hldRecRoute;
   }
   
   
   if(hc->x[iContactId].sipUri.dstrSipAddr.uiLen && (id & (METHOD_CANCEL_IGNORE|METHOD_REGISTER))==0)
   {
      if(hrr->uiCount)//TODO caller calle
      {
         iReplaceRoute=!hasRouteLR(hrr,0);
      }
      if(iReplaceRoute)
      {
         strDstAddr.s=(unsigned char *)hrr->x[0].sipUri.dstrSipAddr.strVal;
         strDstAddr.len=(int)hrr->x[0].sipUri.dstrSipAddr.uiLen;
      }
      else
      {
         strDstAddr.s=(unsigned char *)hc->x[iContactId].sipUri.dstrSipAddr.strVal;
         strDstAddr.len=(int)hc->x[iContactId].sipUri.dstrSipAddr.uiLen;
      }
   }
   //HDR
   ADD_DSTR(s,uiLen,sip_meth[iMeth]); ADD_CHAR(s,uiLen,' ');
   ADD_L_STR(s,uiLen,strDstAddr.s, strDstAddr.len);ADD_0_STR(s,uiLen," SIP/2.0\r\n");
   
   switch(id)
   {
      case METHOD_INVITE:
         sMsg->hdrCSeq.dstrID.uiVal=uiCSeq;
         break;
      case METHOD_ACK:
      case METHOD_CANCEL:
         uiCSeq=sMsg->hdrCSeq.dstrID.uiVal;
         break;
         
      case METHOD_REFER:
         //  ADD_STR(s,uiLen,"Refer-To: <");
         //ADD_DSTR(s,uiLen,spSes->str32Forward);
         //ADD_0_STR(s,uiLen,">\r\n");
         break;
         
      case METHOD_REGISTER:
         if(sMsg->hdrCSeq.dstrID.uiVal)uiCSeq=sMsg->hdrCSeq.dstrID.uiVal+1;//ast
         sMsg->hdrCSeq.dstrID.uiVal=uiCSeq;
      case METHOD_OPTIONS:
         
         ADD_STR(s,uiLen,"Allow: INVITE,ACK,CANCEL,OPTIONS,MESSAGE,BYE,INFO\r\n");
         if(id==METHOD_OPTIONS)
         {
            ADD_STR(s,uiLen,"Accept: application/sdp, text/plain\r\n");
         }
         break;
         
   }
   //TODO test asterisk add
   if((id & METHOD_REGISTER) && cfg && !cfg->reg.bUnReg && cfg->iUseOnlyNatIp==0 && sMsg &&  sMsg->hldVia.x[0].dstrRecived.uiLen<32)
   {
      if(sMsg->hldVia.x[0].dstrRecived.strVal && sMsg->hldVia.x[0].dstrRecived.uiLen){
         //TODO hi addr
         
         if(str64ExtADDR)
            spSes->pIPVisble=str64ExtADDR;
         
         memcpy(spSes->pIPVisble->strVal
                ,sMsg->hldVia.x[0].dstrRecived.strVal
                ,sMsg->hldVia.x[0].dstrRecived.uiLen);
         
         spSes->pIPVisble->uiLen=sMsg->hldVia.x[0].dstrRecived.uiLen;
         
         if(sMsg->hldVia.x[0].dstrRPort.uiVal)
            spSes->uiUserVisibleSipPort=sMsg->hldVia.x[0].dstrRPort.uiVal;
         
         if(addrExt)
         {
            addrExt->ip=ipstr2long(sMsg->hldVia.x[0].dstrRecived.uiLen,sMsg->hldVia.x[0].dstrRecived.strVal);
            
            SWAP_INT(addrExt->ip);
            addrExt->setPort((unsigned int)spSes->uiUserVisibleSipPort);
            
            
         }
      }
      else if(sMsg->hldVia.x[0].dstrRPort.uiVal){
         //  printf("[reg rport=%d ]",sMsg->hldVia.x[0].dstrRPort.uiVal);
         spSes->uiUserVisibleSipPort=sMsg->hldVia.x[0].dstrRPort.uiVal;
         addrExt->setPort((unsigned int)spSes->uiUserVisibleSipPort);
      }
   }
   
   if(iIsTCP)ADD_STR(s,uiLen,"Via: SIP/2.0/TCP ")
      else if(iIsTLS)ADD_STR(s,uiLen,"Via: SIP/2.0/TLS ")
         else ADD_STR(s,uiLen,"Via: SIP/2.0/UDP ")
            ADD_DSTR(s,uiLen,(*spSes->pIPVisble));
   
   if(spSes->uiUserVisibleSipPort!=DEAFULT_SIP_PORT)
      uiLen += sprintf(s + uiLen, ":%u", spSes->uiUserVisibleSipPort);
   
   ADD_STR(s,uiLen,";rport");
   ADD_STR(s,uiLen,";branch=z9hG4bK");
   ADD_L_STR(s,uiLen,sMsg->dstrCallID.strVal,4);
   if(id!=METHOD_CANCEL)
   {
      ADD_L_STR(s,uiLen,s,2);
   }
   else
   {
      ADD_STR(s,uiLen,"IN");
   }
   
   uiLen += sprintf(s + uiLen, "%u",uiCSeq^0x123);
   
   
   
   
   ADD_CRLF(s,uiLen);
   
   uiLen += sprintf(s + uiLen, "CSeq: %u ", uiCSeq);
   ADD_DSTRCRLF(s,uiLen,sip_meth[iMeth])
   
   
   
   if((id & (METHOD_REGISTER|METHOD_CANCEL))
      || (spSes->cs.iCaller  && (sMsg==NULL || sMsg->hdrCSeq.uiMethodID==0)))
   {
      
      ADD_FSTR(s,uiLen,"From: ",6);
      {
         uiFromLoc=uiLen;
         if(cfg->user.nick[0]){
            ADD_CHAR(s,uiLen,'"');
            ADD_0_STR(s,uiLen,cfg->user.nick);
            ADD_CHAR(s,uiLen,'"');
         }
         uiLen+=sprintf(s+uiLen," <%.*s>",D_STR(spSes->userSipAddr));
         
         uiFromLen=uiLen-uiFromLoc;
         
         if(spSes->str16Tag.uiLen)
         {
            ADD_0_STR(s,uiLen,";tag=");
            ADD_DSTRCRLF(s,uiLen,spSes->str16Tag);
         }
         else ADD_CRLF(s,uiLen);
         
      }
      {
         
         if((sMsg->hdrTo.dstrTag.uiLen==0 && id!=METHOD_REGISTER)
            || (id & METHOD_CANCEL)
            )
         {
            //  puts("a4");
            ADD_FSTR(s,uiLen,"To: <",5);
            //vajag lai straadaatu 3xx vispaar sho laikam jau nevajag,
            //jo es jau iedoshu liidzi sMsg kuru saneemu
            if(spSes && spSes->sSIPMsg.hdrTo.sipUri.dstrSipAddr.uiLen==0)
            {
               spSes->sSIPMsg.hdrTo.sipUri.dstrSipAddr.strVal=
               (char *)&spSes->sSIPMsg.rawDataBuffer+spSes->sSIPMsg.uiOffset;
               ADD_DSTR((char *)&spSes->sSIPMsg.rawDataBuffer, spSes->sSIPMsg.uiOffset,spSes->dstSipAddr);
               
               spSes->sSIPMsg.hdrTo.sipUri.dstrSipAddr.uiLen=spSes->dstSipAddr.uiLen;
               //varbuut sho saglabaat pie get new ses
            }
            if(sMsg->hdrTo.sipUri.dstrSipAddr.strVal)
            {
               ADD_DSTR(s,uiLen,sMsg->hdrTo.sipUri.dstrSipAddr);
            }
            else
            {
               ADD_DSTR(s,uiLen,spSes->dstSipAddr);
            }
            ADD_FSTR(s,uiLen,">\r\n",3);
            
            // puts("a5");
         }
         else if (id==METHOD_REGISTER)
         {
            //  DEBUG(0,"make register---------")
            ADD_FSTR(s,uiLen,"To: ",4);
            memcpy(s+uiLen,s+uiFromLoc,uiFromLen);
            uiLen+=uiFromLen;
            ADD_CRLF(s,uiLen);
         }
         else
         {
            ADD_DSTRCRLF(s,uiLen,sMsg->hdrTo.dstrFullRow);
            //  puts("a6");
         }
      }
   }
   else
   {
      //TODO use full row
      //      char *pMeth1;
      //    char *pMeth2;
      DSTR *fromAddr;
      DSTR *toAddr;
      DSTR *tag;
      //   puts("a7");
      
      if(sMsg->sipHdr.dstrStatusCode.uiVal)
      {
         fromAddr=&sMsg->hdrFrom.sipUri.dstrSipAddr;
         toAddr=&sMsg->hdrTo.sipUri.dstrSipAddr;
         tag=&sMsg->hdrTo.dstrTag;
         //    puts("a8");
      }
      else
      {
         toAddr=&sMsg->hdrFrom.sipUri.dstrSipAddr;
         fromAddr=&sMsg->hdrTo.sipUri.dstrSipAddr;
         tag=&sMsg->hdrFrom.dstrTag;
         //  puts("a9");
      }
      
      uiLen+=sprintf(s+uiLen,"From: <%.*s>", D_STR(*fromAddr));
      if(spSes->str16Tag.uiLen)
      {
         ADD_0_STR(s,uiLen,";tag=");
         ADD_DSTRCRLF(s,uiLen,spSes->str16Tag);
      }
      else ADD_CRLF(s,uiLen);
      

      uiLen+=sprintf(s+uiLen,"To: <%.*s>", D_STR(*toAddr));
      
      if(tag->uiLen && !fToTagIgnore)
      {
         ADD_0_STR(s,uiLen,";tag=");
         ADD_DSTRCRLF(s,uiLen,(*tag));
      }
      else ADD_CRLF(s,uiLen);
   }
   
   ADD_FSTR(s,uiLen,"Call-ID: ",9);
   ADD_DSTRCRLF(s,uiLen,sMsg->dstrCallID);
   ADD_STR(s,uiLen,"Max-Forwards: 70\r\n");
   
   if(id==METHOD_REGISTER){
      if(cfg && cfg->szUA[0]){
         ADD_STR(s,uiLen,"User-Agent: ");
         ADD_0_STR(s,uiLen,cfg->szUA);ADD_CRLF(s,uiLen);
      }
      else{
         ADD_STR(s,uiLen,USER_AGENT);
      }
   }
   
   
   if(id != METHOD_CANCEL_IGNORE && (hrr->uiCount || iReplaceRoute))//(toMake & (METHOD_BYE |METHOD_ACK)) && ???
   {
      
      uiLen+=addRoute(s+uiLen, 255, hrr, "Route: ",
                      !((sMsg->hdrCSeq.uiMethodID && sMsg->sipHdr.dstrStatusCode.uiVal) ||
                        (spSes->cs.iCaller && sMsg->hdrCSeq.uiMethodID==0))
                      ,iReplaceRoute, &hc->x[iContactId].sipUri.dstrSipAddr);
      
   }
   
   if(id & (METHOD_INVITE | METHOD_OPTIONS |METHOD_MESSAGE |METHOD_REGISTER|METHOD_REFER|METHOD_SUBSCRIBE|METHOD_PUBLISH|METHOD_UPDATE))
   {
      //unsigned int uiPos;
      if(cfg && cfg->user.nick[0]){
         uiLen+=sprintf(s+uiLen,"Contact: \"%s\" <sip:",cfg->user.nick);//sUserCfg.szUserName);
      }
      else {ADD_STR(s,uiLen,"Contact: <sip:");}
      //uiPos=uiLen;
      
      //TODO if register store contact addr and use it until next reg
      
      if(cfg  && (cfg->isOnline() || (id & METHOD_REGISTER)))
      {
         if(*cfg->user.nr)
            uiLen+=sprintf(s+uiLen,"%s@",cfg->user.nr);
         else if(*cfg->user.un)
            uiLen+=sprintf(s+uiLen,"%s@",cfg->user.un);
      }
      
      ADD_DSTR(s,uiLen,(*spSes->pIPVisble));
      
      
      if(spSes->uiUserVisibleSipPort!=DEAFULT_SIP_PORT)
         uiLen+=sprintf(s+uiLen,":%u",spSes->uiUserVisibleSipPort);
      
      
      
      if(iIsTCP) {ADD_STR(s,uiLen,";transport=tcp>")}else
         if(iIsTLS) {ADD_STR(s,uiLen,";transport=tls>")} else
         { ADD_FSTR(s,uiLen,">",1)}
Example #28
0
/* 
 * return an ascii representation of the integral part of the number
 * and set fract to be an ascii representation of the fraction part
 * the container for the fraction and the integral part or staticly
 * declare with fix size 
 */
static CWT_CHAR* numtoa(double number, int base, int precision, CWT_CHAR ** fract)
{
	register int i, j;
	double ip, fp; /* integer and fraction part */
	double fraction;
	int digits = MAX_INT - 1;
	static CWT_CHAR integral_part[MAX_INT];
	static CWT_CHAR fraction_part[MAX_FRACT];
	double sign;
	int ch;

	/* taking care of the obvious case: 0.0 */
	if (number == 0.) {
		integral_part[0] = _T('0');
		integral_part[1] = _T('\0');
		fraction_part[0] = _T('0');
		fraction_part[1] = _T('\0');
		return integral_part;
	}

	/* for negative numbers */
	if ((sign = number) < 0.) {
		number = -number;
		digits--; /* sign consume one digit */
	}

	fraction = integral(number, &ip);
	number = ip;

  /* do the integral part */
	if ( ip == 0.) {
		integral_part[0] = _T('0');
		i = 1;
	} else {
		for ( i = 0; i < digits && number != 0.; ++i) {
			number /= base;
			fp = integral(number, &ip);
			ch = (int)((fp + PRECISION)*base); /* force to round */
			integral_part[i] = (ch <= 9) ? ch + _T('0') : ch + _T('a') - 10;

			if (! isxdigit(integral_part[i])) /* bail out overflow !! */
				break;
			number = ip;
		}
	}
     
	/* Oh No !! out of bound, ho well fill it up ! */
	if (number != 0.)
		for (i = 0; i < digits; ++i)
			integral_part[i] = _T('9');

	/* put the sign ? */
	if (sign < 0.)
		integral_part[i++] = _T('-');

	integral_part[i] = _T('\0');

	/* reverse every thing */
	for ( i--, j = 0; j < i; j++, i--)
		SWAP_INT(integral_part[i], integral_part[j]);

	/* the fractionnal part */
	for (i=0, fp=fraction; precision > 0 && i < MAX_FRACT ; i++, precision--	) {
		fraction_part[i] = (int)((fp + PRECISION)*10. + _T('0'));
		if (! isdigit(fraction_part[i])) /* underflow ? */
			break;
		fp = (fp*10.0) - (double)(long)((fp + PRECISION)*10.);
	}

	fraction_part[i] = _T('\0');

	if (fract != (CWT_CHAR **)0)
		*fract = fraction_part;

	return integral_part;
}
void test_cu_buildbuffers_tagged(void) {

    int i, p, rc;
    int errcount;
    int *outcount;
    int *msgptr;
    void **buffers;
    MBIt_Board *board; /* mock board */
    char *header_byte, *bufptr;
    
    /* requirements of using mock_filter2 as board filter */
    assert(TCU_CommSize < MSGCOUNT/2);
    assert(MSGCOUNT >= 1000);
    
    /* Test needs at least 4 procs */
    if (TCU_CommSize < 4) return;
    
    /* create outcount array */
    outcount = (int *)malloc(sizeof(int) * TCU_CommSize);
    assert(outcount != NULL);
    
    /* create array of buffer ptrs */
    buffers = (void **)malloc(sizeof(void*) * TCU_CommSize);
    assert(buffers != NULL);
    SET_ALL_NULL(buffers);
    
    /* --- test where all remote procs are readers --- */
    
    /* create board */
    board = mock_board_create();
    assert(board != NULL);
    assert(board->data != NULL);
    assert(board->synced_cursor == 0);
    assert(board->data->count_current == 0);
    /* different filter */
    board->filter = &mock_filter2;
    
    /* by default, all remote procs are readers */
    mock_board_populate(board, MSGCOUNT);
    assert(board->data->count_current == MSGCOUNT);
    rc = MBI_CommUtil_TagMessages(board, outcount);
    CU_ASSERT_EQUAL_FATAL(rc, MB_SUCCESS);
    CU_ASSERT_PTR_NOT_NULL_FATAL(board->tt);
    for (p = 0; p < TCU_CommSize; p++)
    {
        if (p == TCU_CommRank)
        {
            CU_ASSERT_EQUAL_FATAL(outcount[p], -1);
        }
        else
        {
            CU_ASSERT_EQUAL_FATAL(outcount[p], 2);
        }
    }
    
    rc = MBI_CommUtil_BuildBuffers_Tagged(board, buffers, outcount);
    CU_ASSERT_EQUAL(rc, MB_SUCCESS);
    for (p = 0; p < TCU_CommSize; p++)
    {
        if (p == TCU_CommRank)
        {
            CU_ASSERT_PTR_NULL(buffers[p]);
        }
        else
        {
            CU_ASSERT_PTR_NOT_NULL(buffers[p]);
            if (buffers[p] != NULL)
            {
                /* check header */
                header_byte = (char *)buffers[p];
                CU_ASSERT_EQUAL(*header_byte, ALLZEROS);
                
                /* check buffer content */
                bufptr = (char *)(buffers[p]) + 1;
                errcount = 0;
                for (i = 0; i < outcount[p]; i++)
                {
                    msgptr = (int *)bufptr;
                    bufptr += board->data->elem_size;
                    
                    if (*msgptr != p + i) errcount++;
                }
                CU_ASSERT_EQUAL(errcount, 0);
            }
        }
    }
    /* reset */
    FREE_EACH_BUFFER(buffers);
    mock_board_delete(&board);
    
    
    /* --- test where only some procs are readers --- */
    
    /* create board */
    board = mock_board_create();
    assert(board != NULL);
    assert(board->data != NULL);
    assert(board->synced_cursor == 0);
    assert(board->data->count_current == 0);
    /* different filter */
    board->filter = &mock_filter2;
    
    /* update reader_list */
    assert(TCU_CommSize > 3);
    board->reader_list[0] = (TCU_CommRank + 1) % TCU_CommSize;  
    board->reader_list[1] = (TCU_CommRank + 2) % TCU_CommSize;  
    if (board->reader_list[0] > board->reader_list[1]) 
    {
        SWAP_INT(board->reader_list[0], board->reader_list[1], i);
    }
    board->reader_count = 2;
    
    mock_board_populate(board, MSGCOUNT);
    rc = MBI_CommUtil_TagMessages(board, outcount);
    CU_ASSERT_EQUAL_FATAL(rc, MB_SUCCESS);
    CU_ASSERT_PTR_NOT_NULL_FATAL(board->tt);
    for (p = 0; p < TCU_CommSize; p++)
    {
        if (p == board->reader_list[0] || p == board->reader_list[1] )
        {
            CU_ASSERT_EQUAL_FATAL(outcount[p], 2);
        }
        else
        {
            CU_ASSERT_EQUAL_FATAL(outcount[p], -1);
        }
    }
    
    rc = MBI_CommUtil_BuildBuffers_Tagged(board, buffers, outcount);
    CU_ASSERT_EQUAL(rc, MB_SUCCESS);
    for (p = 0; p < TCU_CommSize; p++)
    {
        if (outcount[p] == -1)
        {
            CU_ASSERT_PTR_NULL(buffers[p]);
        }
        else
        {
            CU_ASSERT_PTR_NOT_NULL(buffers[p]);
            if (buffers[p] != NULL)
            {
                /* check header */
                header_byte = (char *)buffers[p];
                CU_ASSERT_EQUAL(*header_byte, ALLZEROS);
                
                /* check buffer content */
                bufptr = (char *)(buffers[p]) + 1;
                errcount = 0;
                for (i = 0; i < outcount[p]; i++)
                {
                    msgptr = (int *)bufptr;
                    bufptr += board->data->elem_size;
                    
                    if (*msgptr != p + i) errcount++;
                }
                CU_ASSERT_EQUAL(errcount, 0);
            }
        }
    }
    /* reset */
    FREE_EACH_BUFFER(buffers);
    mock_board_delete(&board);
    
    free(outcount);
    free(buffers);
}
Example #30
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;
    struct linkedit_data_command *ld;
    struct rpath_command *rpath;
    struct encryption_info_command *ec;
    struct dyld_info_command *dc;
    uint32_t flavor, count;
    unsigned long nflavor;
    char *p, *state, *cmd_name;

	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:
		cmd_name = "LC_ID_DYLIB";
		goto check_dylib_command;
	    case LC_LOAD_DYLIB:
		cmd_name = "LC_LOAD_DYLIB";
		goto check_dylib_command;
	    case LC_LOAD_WEAK_DYLIB:
		cmd_name = "LC_LOAD_WEAK_DYLIB";
		goto check_dylib_command;
	    case LC_REEXPORT_DYLIB:
		cmd_name = "LC_REEXPORT_DYLIB";
		goto check_dylib_command;
	    case LC_LAZY_LOAD_DYLIB:
		cmd_name = "LC_LAZY_LOAD_DYLIB";
		goto check_dylib_command;
check_dylib_command:
		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)",
			  cmd_name, 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)",
			  cmd_name, 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 = *((uint32_t *)state);
			state += sizeof(uint32_t);
			count = *((uint32_t *)state);
			state += sizeof(uint32_t);
			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 %u 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 = *((uint32_t *)state);
			state += sizeof(uint32_t);
			count = *((uint32_t *)state);
			state += sizeof(uint32_t);
			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 %u 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 = *((uint32_t *)state);
			state += sizeof(uint32_t);
			count = *((uint32_t *)state);
			state += sizeof(uint32_t);
			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 %u 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 = *((uint32_t *)state);
			state += sizeof(uint32_t);
			count = *((uint32_t *)state);
			state += sizeof(uint32_t);
			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 %u 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 = *((uint32_t *)state);
			state += sizeof(uint32_t);
			count = *((uint32_t *)state);
			state += sizeof(uint32_t);
			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 %u 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 = *((uint32_t *)state);
			state += sizeof(uint32_t);
			count = *((uint32_t *)state);
			state += sizeof(uint32_t);
			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 %u 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 = *((uint32_t *) state);
		    state += sizeof(uint32_t);
		    count = *((uint32_t *) state);
		    state += sizeof(uint32_t);
		    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){
		    arm_thread_state_t *cpu;

		    nflavor = 0;
		    p = (char *)ut + ut->cmdsize;
		    while(state < p){
			flavor = *((uint32_t *)state);
			state += sizeof(uint32_t);
			count = *((uint32_t *)state);
			state += sizeof(uint32_t);
			switch(flavor){
			case ARM_THREAD_STATE:
			    if(count != ARM_THREAD_STATE_COUNT){
				error("in swap_object_headers(): malformed "
				    "load commands (count "
				    "not ARM_THREAD_STATE_COUNT for "
				    "flavor number %lu which is a ARM_THREAD_"
				    "STATE flavor in %s command %lu)",
				    nflavor, ut->cmd == LC_UNIXTHREAD ? 
				    "LC_UNIXTHREAD" : "LC_THREAD", i);
				return(FALSE);
			    }
			    cpu = (arm_thread_state_t *)state;
			    state += sizeof(arm_thread_state_t);
			    break;
			default:
			    error("in swap_object_headers(): malformed load "
				  "commands (unknown flavor for flavor number "
				  "%lu in %s command %lu can't byte swap it)",
				  nflavor, ut->cmd == LC_UNIXTHREAD ?
				  "LC_UNIXTHREAD" : "LC_THREAD", i);
			    return(FALSE);
			}
			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;

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

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

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

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

	    case LC_DYLD_INFO:
	    case LC_DYLD_INFO_ONLY:
		dc = (struct dyld_info_command *)lc;
		if(dc->cmdsize != sizeof(struct dyld_info_command)){
		    error("in swap_object_headers(): malformed load commands "
			  "(LC_DYLD_INFO 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:
	    case LC_REEXPORT_DYLIB:
	    case LC_LAZY_LOAD_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 = *((uint32_t *)state);
			*((uint32_t *)state) = SWAP_INT(flavor);
			state += sizeof(uint32_t);
			count = *((uint32_t *)state);
			*((uint32_t *)state) = SWAP_INT(count);
			state += sizeof(uint32_t);
			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 = *((uint32_t *)state);
			*((uint32_t *)state) = SWAP_INT(flavor);
			state += sizeof(uint32_t);
			count = *((uint32_t *)state);
			*((uint32_t *)state) = SWAP_INT(count);
			state += sizeof(uint32_t);
			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 = *((uint32_t *)state);
			*((uint32_t *)state) = SWAP_INT(flavor);
			state += sizeof(uint32_t);
			count = *((uint32_t *)state);
			*((uint32_t *)state) = SWAP_INT(count);
			state += sizeof(uint32_t);
			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 = *((uint32_t *)state);
			*((uint32_t *)state) = SWAP_INT(flavor);
			state += sizeof(uint32_t);
			count = *((uint32_t *)state);
			*((uint32_t *)state) = SWAP_INT(count);
			state += sizeof(uint32_t);
			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 = *((uint32_t *)state);
			*((uint32_t *)state) = SWAP_INT(flavor);
			state += sizeof(uint32_t);
			count = *((uint32_t *)state);
			*((uint32_t *)state) = SWAP_INT(count);
			state += sizeof(uint32_t);
			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 = *((uint32_t *)state);
			*((uint32_t *)state) = SWAP_INT(flavor);
			state += sizeof(uint32_t);
			count = *((uint32_t *)state);
			*((uint32_t *)state) = SWAP_INT(count);
			state += sizeof(uint32_t);
			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 = *((uint32_t *) state);
		    *((uint32_t *) state) = SWAP_INT(flavor);
		    state += sizeof(uint32_t);
		    count = *((unsigned int *) state);
		    *((unsigned int *) state) = SWAP_INT(count);
		    state += sizeof(uint32_t);
		    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 *cpu;

		    while(state < p){
			flavor = *((uint32_t *)state);
			*((uint32_t *)state) = SWAP_INT(flavor);
			state += sizeof(uint32_t);
			count = *((uint32_t *)state);
			*((uint32_t *)state) = SWAP_INT(count);
			state += sizeof(uint32_t);
			switch(flavor){
			case ARM_THREAD_STATE:
			    cpu = (arm_thread_state_t *)state;
			    swap_arm_thread_state_t(cpu, target_byte_sex);
			    state += sizeof(arm_thread_state_t);
			    break;
			}
		    }
		    break;
		}
		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;

	    case LC_CODE_SIGNATURE:
	    case LC_SEGMENT_SPLIT_INFO:
		ld = (struct linkedit_data_command *)lc;
		swap_linkedit_data_command(ld, target_byte_sex);
		break;

	    case LC_RPATH:
		rpath = (struct rpath_command *)lc;
		swap_rpath_command(rpath, target_byte_sex);
		break;

	    case LC_ENCRYPTION_INFO:
		ec = (struct encryption_info_command *)lc;
		swap_encryption_command(ec, target_byte_sex);
		break;
		
	    case LC_DYLD_INFO:
	    case LC_DYLD_INFO_ONLY:
		dc = (struct dyld_info_command *)lc;
		swap_dyld_info_command(dc, 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);
}