Exemple #1
0
IGL_INLINE igl::opengl::gliGenericImage *
igl::opengl::gliReadTGA(FILE *fp, char *name, int /*hflip*/, int vflip)
{
  igl::opengl::TgaHeader tgaHeader;
  igl::opengl::TgaFooter tgaFooter;
  char horzrev, vertrev;
  int width, height, bpp;
  int start, end, dir;
  int i, j, k;
  int pelbytes, wbytes;
  GLenum format;
  int components;
  RLEstate rleRec;
  RLEstate *rleInfo;
  int rle;
  int index, colors, length;
  GLubyte *cmap, *pixels, *data;
  int (*myfread)(RLEstate *rleInfo, unsigned char*, size_t, size_t, FILE*);
  igl::opengl::gliGenericImage *genericImage;

  /* Check the footer. */
  if (fseek(fp, 0L - sizeof(tgaFooter), SEEK_END)
      || fread(&tgaFooter, sizeof(tgaFooter), 1, fp) != 1) {
    sprintf(error, "TGA: Cannot read footer from \"%s\"", name);
    if (_verbose) printf("%s\n", error);
    return NULL;
  }  

  /* Check the signature. */
  if (memcmp(tgaFooter.signature, TGA_SIGNATURE,
             sizeof(tgaFooter.signature)) == 0) {
    if (_verbose) printf("TGA: found New TGA\n");
  } else {
    if (_verbose) printf("TGA: found Original TGA\n");
  }

  if (fseek(fp, 0, SEEK_SET) ||
      fread(&tgaHeader, sizeof(tgaHeader), 1, fp) != 1) {
    sprintf(error, "TGA: Cannot read header from \"%s\"", name);
    if (_verbose) printf("%s\n", error);
    return NULL;
  }

  if (_verbose && tgaHeader.idLength) {
    char *idString = (char*) malloc(tgaHeader.idLength);
    
    if (fread(idString, tgaHeader.idLength, 1, fp) != 1) {
      sprintf(error, "TGA: Cannot read ID field in \"%s\"", name);
      printf("%s\n", error);
    } else {
      printf("TGA: ID field: \"%*s\"\n", tgaHeader.idLength, idString);
    }
    free(idString);
  } else {
    /* Skip the image ID field. */
    if (tgaHeader.idLength && fseek(fp, tgaHeader.idLength, SEEK_CUR)) {
      sprintf(error, "TGA: Cannot skip ID field in \"%s\"", name);
      if (_verbose) printf("%s\n", error);
      return NULL;
    }
  }
  
  /* Reassemble the multi-byte values correctly, regardless of
     host endianness. */
  width = (tgaHeader.widthHi << 8) | tgaHeader.widthLo;
  height = (tgaHeader.heightHi << 8) | tgaHeader.heightLo;
  bpp = tgaHeader.bpp;
  if (_verbose) {
    printf("TGA: width=%d, height=%d, bpp=%d\n", width, height, bpp);
  }

  horzrev = tgaHeader.descriptor & TGA_DESC_HORIZONTAL;
  vertrev = tgaHeader.descriptor & TGA_DESC_VERTICAL;
  //vertrev=0;

//   // JASON - we can force this stuff if we want
//   if( hflip )
//       horzrev = 1;
  if( vflip )
      vertrev = 1;

  if (_verbose && horzrev) printf("TGA: horizontal reversed\n");
  if (_verbose && vertrev) printf("TGA: vertical reversed\n");

  rle = 0;
  switch (tgaHeader.imageType) {
  case TGA_TYPE_MAPPED_RLE:
    rle = 1;
    if (_verbose) printf("TGA: run-length encoded\n");
  case TGA_TYPE_MAPPED:
    /* Test for alpha channel. */
    format = GL_COLOR_INDEX;
    components = 1;
    if (_verbose) {
      printf("TGA: %d bit indexed image (%d bit palette)\n",
        tgaHeader.colorMapSize, bpp);
    }
    break;

  case TGA_TYPE_GRAY_RLE:
    rle = 1;
    if (_verbose) printf("TGA: run-length encoded\n");
  case TGA_TYPE_GRAY:
    format = GL_LUMINANCE;
    components = 1;
    if (_verbose) printf("TGA: %d bit grayscale image\n", bpp);
    break;

  case TGA_TYPE_COLOR_RLE:
    rle = 1;
    if (_verbose) printf("TGA: run-length encoded\n");
  case TGA_TYPE_COLOR:
    /* Test for alpha channel. */
    if (bpp == 32) {
      format = GL_BGRA_EXT;
      components = 4;
      if (_verbose) {
        printf("TGA: %d bit color image with alpha channel\n", bpp);
      }
    } else {
      format = GL_BGR_EXT;
      components = 3;
      if (_verbose) printf("TGA: %d bit color image\n", bpp);
    }
    break;

  default:
    sprintf(error,
      "TGA: unrecognized image type %d\n", tgaHeader.imageType);
    if (_verbose) printf("%s\n", error);
    return NULL;
  }

  if ((format == GL_BGRA_EXT && bpp != 32) ||
      (format == GL_BGR_EXT && bpp != 24) ||
      ((format == GL_LUMINANCE || format == GL_COLOR_INDEX) && bpp != 8)) {
    /* FIXME: We haven't implemented bit-packed fields yet. */
    fprintf(stderr, "bpp %d, format %x\n", bpp, (unsigned int)format); 
    sprintf(error, "TGA: channel sizes other than 8 bits are unimplemented");
    if (_verbose) printf("%s\n", error);
    return NULL;
  }

  /* Check that we have a color map only when we need it. */
  if (format == GL_COLOR_INDEX) {
    if (tgaHeader.colorMapType != 1) {
      sprintf(error, "TGA: indexed image has invalid color map type %d\n",
        tgaHeader.colorMapType);
      if (_verbose) printf("%s\n", error);
      return NULL;
    }
  } else if (tgaHeader.colorMapType != 0) {
    sprintf(error, "TGA: non-indexed image has invalid color map type %d\n",
      tgaHeader.colorMapType);
    if (_verbose) printf("%s\n", error);
    return NULL;
  }

  if (tgaHeader.colorMapType == 1) {
    /* We need to read in the colormap. */
    index = (tgaHeader.colorMapIndexHi << 8) | tgaHeader.colorMapIndexLo;
    length = (tgaHeader.colorMapLengthHi << 8) | tgaHeader.colorMapLengthLo;

    if (_verbose) {
      printf("TGA: reading color map (%d + %d) * (%d / 8)\n",
        index, length, tgaHeader.colorMapSize);
    }
    if (length == 0) {
      sprintf(error, "TGA: invalid color map length %d", length);
      if (_verbose) printf("%s\n", error);
      return NULL;
    }
    if (tgaHeader.colorMapSize != 24) {
      /* We haven't implemented bit-packed fields yet. */
      sprintf(error, "TGA: channel sizes other than 8 bits are unimplemented");
      if (_verbose) printf("%s\n", error);
      return NULL;
    }

    pelbytes = tgaHeader.colorMapSize / 8;
    colors = length + index;
    cmap = (GLubyte*)malloc (colors * pelbytes);

    /* Zero the entries up to the beginning of the map. */
    memset(cmap, 0, index * pelbytes);

    /* Read in the rest of the colormap. */
    if (fread(cmap, pelbytes, length, fp) != (size_t) length) {
      sprintf(error, "TGA: error reading colormap (ftell == %ld)\n",
        ftell (fp));
      if (_verbose) printf("%s\n", error);
      return NULL;
    }

    if (pelbytes >= 3) {
      /* Rearrange the colors from BGR to RGB. */
      int tmp;
      for (j = index; j < length * pelbytes; j += pelbytes) {
        tmp = cmap[j];
        cmap[j] = cmap[j + 2];
        cmap[j + 2] = tmp;
      }
    }
  } else {
    colors = 0;
    cmap = NULL;
  }

  /* Allocate the data. */
  pelbytes = bpp / 8;
  pixels = (unsigned char *) malloc (width * height * pelbytes);

  if (rle) {
    rleRec.statebuf = 0;
    rleRec.statelen = 0;
    rleRec.laststate = 0;
    rleInfo = &rleRec;
    myfread = rle_fread;
  } else {
    rleInfo = NULL;
    myfread = std_fread;
  }

  wbytes = width * pelbytes;

  if (vertrev) {
    start = 0;
    end = height;
    dir = 1;
  } else {
    /* We need to reverse loading order of rows. */
    start = height-1;
    end = -1;
    dir = -1;
  }

  for (i = start; i != end; i += dir) {
    data = pixels + i*wbytes;

    /* Suck in the data one row at a time. */
    if (myfread(rleInfo, data, pelbytes, width, fp) != width) {
      /* Probably premature end of file. */
      if (_verbose) {
        printf ("TGA: error reading (ftell == %ld, width=%d)\n",
          ftell(fp), width);
      }
      return NULL;
    }  

    if (horzrev) {
      /* We need to mirror row horizontally. */
      for (j = 0; j < width/2; j++) {
        GLubyte tmp;

        for (k = 0; k < pelbytes; k++) {
          tmp = data[j*pelbytes+k];
          data[j*pelbytes+k] = data[(width-j-1)*pelbytes+k];
          data[(width-j-1)*pelbytes+k] = tmp;
        }
      }
    }
  }

  if (rle) {
    free(rleInfo->statebuf);
  }

  if (fgetc (fp) != EOF) {
    if (_verbose) printf ("TGA: too much input data, ignoring extra...\n");
  }

  genericImage = (igl::opengl::gliGenericImage*) malloc(sizeof(igl::opengl::gliGenericImage));
  genericImage->width = width;
  genericImage->height = height;
  genericImage->format = format;
  genericImage->components = components;
  genericImage->cmapEntries = colors;
  genericImage->cmapFormat = GL_BGR_EXT;  // XXX fix me
  genericImage->cmap = cmap;
  genericImage->pixels = pixels;

  return genericImage;
}
Exemple #2
0
DWORD GetEnvironmentVariableEBA(LPCSTR envBlock, LPCSTR lpName, LPSTR lpBuffer, DWORD nSize)
{
	int length;
	char* env = NULL;
	const char * penvb = envBlock;
	char *foundEquals;

	while (*penvb && *(penvb+1))
	{
		length = strlen(penvb);
		foundEquals = strstr(penvb,"=");
		if (foundEquals == NULL) {
			continue;
		}
#ifdef _WIN32
		if (strnicmp(penvb,lpName,foundEquals - penvb) == 0) {
#else
		if (strncmp(penvb,lpName,foundEquals - penvb) == 0) {
#endif
			if (*(penvb + (foundEquals - penvb)) == '=') {
				// found variable ...
				if (foundEquals == NULL) {
					return 0;
				} else {
					env = foundEquals + 1;
					break;
				}
			}
		}
		penvb += (length +1);
	}


	if (!env)
		return 0;

	length = strlen(env);

	if ((length + 1 > nSize) || (!lpBuffer))
		return length + 1;

	CopyMemory(lpBuffer, env, length + 1);

	return length;
}



DWORD GetEnvironmentVariableW(LPCWSTR lpName, LPWSTR lpBuffer, DWORD nSize)
{
	return 0;
}

BOOL SetEnvironmentVariableA(LPCSTR lpName, LPCSTR lpValue)
{
	int length;
	char* envstr;

	if (!lpName)
		return FALSE;

	if (lpValue)
	{
		length = strlen(lpName) + strlen(lpValue) + 1;
		envstr = (char*) malloc(length + 1);
		sprintf_s(envstr, length + 1, "%s=%s", lpName, lpValue);
		envstr[length] = '\0';
		putenv(envstr);
	}
	else
	{
		unsetenv(lpName);
	}

	return TRUE;
}
Exemple #3
0
int main(int argc, const char* argv[]) {
  int log_tab_size = 12;
  int compress = 1;
  FSCCodingMethod method = CODING_METHOD_DEFAULT;
  int stats_only = 0;
  int ok = 0;
  int c;

  for (c = 1; c < argc; ++c) {
    if (!strcmp(argv[c], "-l") && c + 1 < argc) {
      log_tab_size = atoi(argv[++c]);
      if (log_tab_size > LOG_TAB_SIZE) log_tab_size = LOG_TAB_SIZE;
      else if (log_tab_size < 2) log_tab_size = 2;
    } else if (FSCParseCodingMethodOpt(argv[c], &method)) {
      continue;
    } else if (!strcmp(argv[c], "-m") && c + 1 < argc) {
      method = (FSCCodingMethod)atoi(argv[++c]);
    } else if (!strcmp(argv[c], "-s")) {
      stats_only = 1;
    } else if (!strcmp(argv[c], "-c")) {
      compress = 1;
    } else if (!strcmp(argv[c], "-d")) {
      compress = 0;
    } else if (!strcmp(argv[c], "-h")) {
      Help();
    }
  }

  uint8_t* out = NULL;
  size_t out_size = 0;
  uint8_t* in = NULL;
  size_t in_size = 0;

  // Read input
  fseek(stdin, 0L, SEEK_END);
  in_size = ftell(stdin);
  fseek(stdin, 0L, SEEK_SET);
  if (in_size == (size_t)-1) {
    fprintf(stderr, "Missing/erroneous input!\n");
    goto End;
  }
  in = (uint8_t*)malloc(in_size * sizeof(*in));
  if (in == NULL) {
    fprintf(stderr, "Malloc(%lu) failed!\n", in_size);
    exit(-1);
  }
  ok = (fread(in, in_size, 1, stdin) == 1);
  if (!ok) {
    fprintf(stderr, "Error reading from stdin!\n");
    goto End;
  }

  // Compress or decompress.
  MyClock start, tmp;
  if (compress) {   // encoding
    GetElapsed(&start, NULL);
    ok = FSCEncode(in, in_size, &out, &out_size, log_tab_size, method);
    if (!ok) {
      fprintf(stderr, "ERROR while encoding!\n");
      goto End;
    }

    if (stats_only) {
      const double elapsed = GetElapsed(&tmp, &start);
      const double entropy = GetEntropy(in, in_size);
      const double MS = 1.e-6 * in_size;
      const double reduction = 1. * out_size / in_size;
      printf("Enc time: %.3f sec [%.2lf MS/s] (%ld bytes out, %ld in).\n",
             elapsed, MS / elapsed, out_size, in_size);
      printf("Entropy: %.4lf vs expected %.4lf "
             "(off by %.5lf bit/symbol [%.3lf%%])\n",
             reduction, entropy, reduction - entropy,
             100. * (reduction - entropy) / entropy);
    }
  } else {         // decoding
    GetElapsed(&start, NULL);
    ok = FSCDecode(in, in_size, &out, &out_size);
    if (!ok) {
      fprintf(stderr, "ERROR while decoding!\n");
      goto End;
    }
    if (stats_only) {
      const double elapsed = GetElapsed(&tmp, &start);
      const double MS = 1.e-6 * out_size;
      printf("Dec time: %.3f sec [%.2lf MS/s].\n", elapsed, MS / elapsed);
    }
  }

  if (!stats_only) {
    ok = (fwrite(out, out_size, 1, stdout) == 1);
    if (!ok) {
      fprintf(stderr, "Error writing to stdout!\n");
      goto End;
    }
  }

 End:
  free(in);
  free(out);
  return !ok;
}
Exemple #4
0
/*
   InputParser_GetWordFloat..
   Same with InputParser_GetWord , if the result can be converted to a float number , it returns this number
   else 0.0 is returned
*/
float InputParser_GetWordFloat(struct InputParserC * ipc,unsigned int num)
{
   if ( CheckWordNumOk(ipc,num) == 0 ) { return 0.0; }
   if (ipc->tokenlist[num].length == 0 ) { return 0.0; }

   char remember = 0;
   char * string_segment = 0;
   char * last_char_of_string_segment = 0;
   unsigned char isLocallyAllocated = ipc->local_allocation;

   unsigned int tokenStart = ipc->tokenlist[num].token_start;
   unsigned int tokenLength = ipc->tokenlist[num].length;
   unsigned int stringLength = ipc->str_length;

   float return_value=0.0;
   //Our string is a "string_segment" , and its last character ( which will be temporary become null ) is last_char_of_string_segment


   if (!isLocallyAllocated)
    {
     string_segment = (char*) malloc( (tokenLength+1) * sizeof(char) );
     if (string_segment==0)
      {
        fprintf(stderr,"InputParser_GetWordFloat could not allocate memory to return float value , returning NaN \n");
        return NAN;
      }

     strncpy(string_segment,ipc->str+tokenStart,tokenLength);
     last_char_of_string_segment = string_segment + ipc->tokenlist[num].length;
    } else
    {
     string_segment = ipc->str+tokenStart;
     last_char_of_string_segment = string_segment + ipc->tokenlist[num].length;
    }

   if (tokenStart + tokenLength < stringLength)
   {
    remember = *last_char_of_string_segment;
    *last_char_of_string_segment = (char) 0; //Temporarily convert the string segment to a null terminated string
   }
   //else we are on the last part of the string so no reason to do the whole 0 remember thing..


   #if USE_SCANF
    //fprintf(stderr,"Using sscanf to parse %s \n",string_segment);
    #warning "scanf without field width limits can crash with huge input data on libc versions older than 2.13-25. Add a field width specifier to fix this problem"
    /*
      Sample program that can crash:
      #include <stdio.h>
      int main()
       { int a; scanf("%i", &a); return 0; }

      To make it crash:
      perl -e 'print "5"x2100000' | ./a.out|
    */
    sscanf(string_segment,"%f",&return_value);
   #else
    //fprintf(stderr,"Using atof to parse %s \n",string_segment);
    return_value=atof(string_segment);
   #endif // USE_SCANF


   if ( tokenStart + tokenLength < stringLength)
   {
    *last_char_of_string_segment = remember; //Restore string..
   }

  if (!isLocallyAllocated)
  {
   free(string_segment);
  }

  return return_value;
}
static bool is_option(struct dom_node_internal *node, void *ctx);

/**
 * Create a dom_html_select_element object
 *
 * \param doc  The document object
 * \param ele  The returned element object
 * \return DOM_NO_ERR on success, appropriate dom_exception on failure.
 */
dom_exception _dom_html_select_element_create(struct dom_html_document *doc,
		dom_string *namespace, dom_string *prefix,
		struct dom_html_select_element **ele)
{
	struct dom_node_internal *node;

	*ele = malloc(sizeof(dom_html_select_element));
	if (*ele == NULL)
		return DOM_NO_MEM_ERR;
	
	/* Set up vtables */
	node = (struct dom_node_internal *) *ele;
	node->base.vtable = &_dom_html_element_vtable;
	node->vtable = &_protect_vtable;

	return _dom_html_select_element_initialise(doc, namespace, prefix, *ele);
}

/**
 * Initialise a dom_html_select_element object
 *
 * \param doc  The document object
/*
 * Function: DHCPLeaseListCopyARPAddressInfo
 * Purpose:
 *   Returns a list of arp_address_info_t's corresponding to each
 *   discoverable lease.
 */
arp_address_info_t *
DHCPLeaseListCopyARPAddressInfo(DHCPLeaseListRef list_p,
				CFStringRef ssid,
				absolute_time_t * start_time_threshold_p,
				bool tentative_ok,
				int * ret_count)
{
    int				arp_info_count;
    arp_address_info_t *	arp_info_p;
    int				count;
    int				i;
    arp_address_info_t *	info_p;

    DHCPLeaseListRemoveStaleLeases(list_p);
    count = dynarray_count(list_p);
    if (count == 0) {
	*ret_count = 0;
	return (NULL);
    }
    arp_info_p = (arp_address_info_t *)malloc(sizeof(*arp_info_p) * count);
    arp_info_count = 0;
    info_p = arp_info_p;
    for (i = 0; i < count; i++) {
	DHCPLeaseRef	lease_p = dynarray_element(list_p, i);

	if (ssid != NULL) {
	    if (lease_p->ssid == NULL || !CFEqual(lease_p->ssid, ssid)) {
		if (G_IPConfiguration_verbose) {
		    my_log(LOG_DEBUG,
			   "ignoring lease with SSID %@",
			   lease_p->ssid);
		    continue;
		}
	    }
	    
	}
	if (lease_p->router_ip.s_addr == 0
	    || lease_p->router_hwaddr_length == 0) {
	    /* can't use this with ARP discovery */
	    if (G_IPConfiguration_verbose) {
		my_log(LOG_DEBUG, "ignoring lease for " IP_FORMAT,
		       IP_LIST(&lease_p->our_ip));
	    }
	    continue;
	}
	if (lease_p->tentative && tentative_ok == FALSE) {
	    /* ignore tentative lease */
	    continue;
	}
	if (start_time_threshold_p != NULL
	    && lease_p->lease_start < *start_time_threshold_p) {
	    if (G_IPConfiguration_verbose) {
		my_log(LOG_DEBUG, 
		       "start time on lease " IP_FORMAT " too old (%ld < %ld)",
		       IP_LIST(&lease_p->our_ip),
		       lease_p->lease_start, *start_time_threshold_p);
	    }
	    continue;
	}
	info_p->sender_ip = lease_p->our_ip;
	info_p->target_ip = lease_p->router_ip;
	bcopy(lease_p->router_hwaddr, info_p->target_hardware,
	      lease_p->router_hwaddr_length);
	arp_info_count++;
	info_p++;
    }
    if (arp_info_count == 0) {
	free(arp_info_p);
	arp_info_p = NULL;
    }
    *ret_count = arp_info_count;
    return (arp_info_p);
}
Exemple #7
0
int register_capture_poco(struct katcp_dispatch *d, char *name, int (*call)(struct katcp_dispatch *d, struct capture_poco *cp, int poke))
{
  struct state_poco *sp;
  struct capture_poco *cp, **tmp;

  sp = get_mode_katcp(d, POCO_POCO_MODE);
  if(sp == NULL){
    return -1;
  }

  tmp = realloc(sp->p_captures, sizeof(struct capture_poco *) * (sp->p_size + 1));
  if(tmp == NULL){
    return -1;
  }

  sp->p_captures = tmp;
  
  cp = malloc(sizeof(struct capture_poco));
  if(cp == NULL){
    return -1;
  }

  cp->c_magic = CAPTURE_MAGIC;

  cp->c_name = NULL;
  cp->c_fd = (-1);

  cp->c_port = htons(0);
  cp->c_ip = htonl(0);

  /* c_prep - unset */

  cp->c_start.tv_sec = 0;
  cp->c_start.tv_usec = 0;

  cp->c_stop.tv_sec = 0;
  cp->c_stop.tv_usec = 0;

#if 0
  cp->c_period.tv_sec = 0;
  cp->c_period.tv_usec = 0;
#endif

  cp->c_state = 0;
#if 0
  cp->c_ping = 0;
#endif

  cp->c_schedule = call;

  cp->c_ts_msw = 0;
  cp->c_ts_lsw = 0;
  cp->c_options = 0;

  cp->c_buffer = NULL;
  cp->c_size = 0;
  cp->c_sealed = 0;
  cp->c_limit = MTU_POCO - PACKET_OVERHEAD_POCO;
  cp->c_used = 8; /* always have a header */

  cp->c_failures = 0;

  cp->c_dump = NULL;
  cp->c_toggle = NULL;
  cp->c_destroy = NULL;

  cp->c_name = strdup(name);
  if(cp->c_name == NULL){
    destroy_capture_poco(d, cp);
    return -1;
  }

  cp->c_buffer = malloc(cp->c_limit);
  if(cp->c_buffer == NULL){
    destroy_capture_poco(d, cp);
    return -1;
  }
  cp->c_size = cp->c_limit;

  sp->p_captures[sp->p_size] = cp;
  sp->p_size++;

  return 0;
}
void writebits(UCHAR Mask)
{
	DWORD devIndex = 0;
	DWORD numDevs;

	UCHAR ucMask =0x0;
	ftStatus = FT_CreateDeviceInfoList(&numDevs);
	if (ftStatus == FT_OK)
	{ 
		// printf("Number of devices is %d\n",numDevs);
	}
	if (numDevs > 0)
	{
		// allocate storage for list based on numDevs
		devInfo = (FT_DEVICE_LIST_INFO_NODE*)malloc(sizeof(FT_DEVICE_LIST_INFO_NODE)*numDevs);  // get the device information list
		ftStatus = FT_GetDeviceInfoList(devInfo,&numDevs); 
		if (ftStatus == FT_OK)
		{
			/*
			for (i = 0; i < numDevs; i++)
			{ 
				printf("Dev %d:\n",i);
				printf(" Flags=0x%x\n",devInfo[i].Flags);
				printf(" Type=%s\n",devices[devInfo[i].Type]); 
				printf(" ID=0x%x\n",devInfo[i].ID);
				printf(" LocId=0x%x\n",devInfo[i].LocId);
				printf(" SerialNumber=%s\n",devInfo[i].SerialNumber);
				printf(" Description=%s\n",devInfo[i].Description);
				printf(" ftHandle=0x%x\n",devInfo[i].ftHandle);			

			}
			*/
		}
		else
		{
			
		}

		i=0;
		ftStatus = FT_Open(i,&ftHandle);

		if (ftStatus == FT_OK)
		{ 
			// printf("open OK\n");
		}
		else
		{
			printf("Open failed! \n");
		}
	
			ucMask = Mask;
		
	// Set CBUS pins states
		ftStatus = FT_SetBitMode(ftHandle,ucMask,0x20);

	// Check to see if write successful
		if (ftStatus == FT_OK) {
			printf("CBUS Write Succesful: 0x%02X\n",ucMask);
		}
		else
		{
			printf("CBUS write failed!\n");
		}
	// Close device handle
	ftStatus = FT_Close(ftHandle);
	}
}
void get_info(void)
{
	
	UCHAR Mask = 0xff;
	UCHAR Mode = 1;     // Set asynchronous bit-bang mode
	LONG lComPortNumber;
	DWORD numDevs;
	
	//UCHAR BitMode;
	

	char ManufacturerBuf[32];
	char ManufacturerIdBuf[16];
	char DescriptionBuf[64];
	char SerialNumberBuf[16];
	ftData.Signature1 = 0x00000000; 
	ftData.Signature2 = 0xffffffff; 
	ftData.Version = 0x00000002; 

	ftData.Manufacturer = ManufacturerBuf;
	ftData.ManufacturerId = ManufacturerIdBuf;
	ftData.Description = DescriptionBuf;
	ftData.SerialNumber = SerialNumberBuf;

	ftStatus = FT_CreateDeviceInfoList(&numDevs);
	if (ftStatus == FT_OK)
	{ 
		printf("Number of devices is %d\n",numDevs);
	}
	if (numDevs > 0)
	{
		// allocate storage for list based on numDevs
		devInfo = (FT_DEVICE_LIST_INFO_NODE*)malloc(sizeof(FT_DEVICE_LIST_INFO_NODE)*numDevs);  // get the device information list
		ftStatus = FT_GetDeviceInfoList(devInfo,&numDevs); 
		if (ftStatus == FT_OK)
		{
			for (i = 0; i < numDevs; i++)
			{ 
				printf("Dev %d:\n",i);
				printf(" Flags=0x%x\n",devInfo[i].Flags);
				printf(" Type=%s\n",devices[devInfo[i].Type]); 
				printf(" ID=0x%x\n",devInfo[i].ID);
				printf(" LocId=0x%x\n",devInfo[i].LocId);
				printf(" SerialNumber=%s\n",devInfo[i].SerialNumber);
				printf(" Description=%s\n",devInfo[i].Description);
				// printf(" ftHandle=0x%x\n",devInfo[i].ftHandle);			

			}
		}

		i=0;  //open first device
		ftStatus = FT_Open(i,&ftHandle);

		if (ftStatus != FT_OK)
		{
			printf("Can't open %s device! \n",devInfo[i].Description);
		}
		else
		{     
			printf("Successfully open  %s device! \n",devInfo[i].Description);	
			ftStatus = FT_GetComPortNumber(ftHandle,&lComPortNumber);
			if (ftStatus == FT_OK)
			{ 
				if (lComPortNumber == -1)
				{ 
					printf(" NO com port Assigned!\n");
				}
				else
				{ 
					// COM port assigned with number held in lComPortNumber
					printf(" Current assigned COM Port: %d \n",lComPortNumber);
				} 
			}
			else
			{
				printf(" Failed to get the COM Port!\n");
			}

			ftStatus = FT_EE_Read(ftHandle, &ftData);
			if (ftStatus == FT_OK)
			{ 
				// FT_EE_Read OK, data is available in ftData
				printf(" EEPROM READ OK\n");
				printf("Signature1 = 0x%04x\n", ftData.Signature1);
				printf("Signature2 = 0x%04x\n", ftData.Signature2);
				printf("Version = 0x%04x\n", ftData.Version);
				printf("VendorID = 0x%04x\n", ftData.VendorId);
				printf("ProductID = 0x%04x\n", ftData.ProductId);
				printf("Manufacturer = %s\n", ftData.Manufacturer);
				printf("ManufacturerID = %s\n", ftData.ManufacturerId);
				printf("Description = %s\n", ftData.Description);
				printf("SerialNumber = %s\n", ftData.SerialNumber);
				printf("MaxPower = %d\n", ftData.MaxPower);
				printf("PnP = %x\n", ftData.PnP);
				printf("SelfPowered = %x\n", ftData.SelfPowered);
				printf("RemoteWakeup = %x\n", ftData.RemoteWakeup);
				printf("Use Ext Osc = %x\n", ftData.UseExtOsc);
				printf("High Drives = %x\n", ftData.HighDriveIOs);
				printf("Endpoint Size = %x\n", ftData.EndpointSize);
				printf("Pull Down Enabled = %x\n", ftData.PullDownEnableR);
				printf("Serial Number Enabled = %x\n", ftData.SerNumEnableR);
				printf("Invert TXD = %x\n", ftData.InvertTXD);
				printf("Invert RXD = %x\n", ftData.InvertRXD);
				printf("Invert RTS = %x\n", ftData.InvertRTS);
				printf("Invert CTS = %x\n", ftData.InvertCTS);
				printf("Invert DTR = %x\n", ftData.InvertDTR);
				printf("Invert DSR = %x\n", ftData.InvertDSR);
				printf("Invert DCD = %x\n", ftData.InvertDCD);
				printf("Invert RI = %x\n", ftData.InvertRI);
				printf("CBUS0 =  0X%02X\n", ftData.Cbus0);
				printf("CBUS1 =  0X%02X\n", ftData.Cbus1);
				printf("CBUS2 =  0X%02X\n", ftData.Cbus2);
				printf("CBUS3 =  0X%02X\n", ftData.Cbus3);
				printf("CBUS4 =  0X%02X\n", ftData.Cbus4);



			} 
			else
			{ 
				// FT_EE_Read FAILED! 
				printf(" EEPROM READ FAILED\n");

			}
			FT_Close(ftHandle);	
		}      
	}
	else
	{
		printf("No FT232 Device found! \n");
	}
}
Exemple #10
0
HRESULT __stdcall VF_OpenFileFunc_Blen( 
	char *lpFileName, LPVF_FileHandle lpFileHandle )
{
	conndesc * rval;
	char * host;
	char * p;
	int port;
	SOCKET s_in;
	char buf[256];
	struct sockaddr_in      addr;
	FILE* fp;

	p = lpFileName;
	while (*p && *p != '.') p++;
	if (*p) p++;
	if (strcmp(p, "blu") != 0) {
		return VF_ERROR;
	}

	fp = fopen(lpFileName, "r");
	if (!fp) {
		return VF_ERROR;
	}
	fgets(buf, 256, fp);
	fclose(fp);

	host = buf;
	p = host;
	while (*p && *p != ':') p++;
	if (*p) p++;
	p[-1] = 0;
	port = atoi(p);
	if (!port) {
		port = 8080;
	}

	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = getipaddress(host);

	s_in = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (s_in < 0) {
		return VF_ERROR;
	}

	if (connect(s_in, (struct sockaddr*) &addr,
		    sizeof(addr)) < 0) {
		closesocket(s_in);
		return VF_ERROR;
	}

	rval = (conndesc*) malloc(sizeof(conndesc));

	rval->addr = addr;

	my_send(s_in, "GET /info.txt HTTP/1.0\n\n");

	for (;;) {
		char * key;
		char * val;

		if (my_gets(s_in, buf, 250) <= 0) {
			break;
		}

		key = buf;
		val = buf;
		while (*val && *val != ' ') val++;
		if (*val) {
			*val = 0;
			val++;
			
			if (strcmp(key, "width") == 0) {
				rval->width = atoi(val);
			} else if (strcmp(key, "height") == 0) {
				rval->height = atoi(val);
			} else if (strcmp(key, "start") == 0) {
				rval->start = atoi(val);
			} else if (strcmp(key, "end") == 0) {
				rval->end = atoi(val);
			} else if (strcmp(key, "rate") == 0) {
				rval->rate = atoi(val);
			} else if (strcmp(key, "ratescale") == 0) {
				rval->ratescale = atoi(val);
			}
		}
	}

	closesocket(s_in);

	*lpFileHandle = (VF_FileHandle) rval;

	return VF_OK;
}
Exemple #11
0
int parse_input( int * argc , char* input, char*** argv )
{
  dref(argc) = 0; //Count of arguments
  int count = 0; //Counter to store arguments
  int done = 0;
  int before = 0;
  int found = 0;
  int quotes = 0;
  int status = 0;
  
  char** args = NULL;
  char* argin = input;
  char* iptin = input;

  //Tokenize and count number of arguments in input
  while( !done )
  {
    before = found;
    switch( dref(iptin) )
    {
      case 0:
        done = 1;
        break;
        
      case '\"':
        quotes++;
        found = 0;
        break;
        
      case ' ':
        if( is_even(quotes) )
        {
          found = 0;
          break;
        }
        
      case '\t':
      default:
        found = 1;
        if( !before  )
          dref(argc)++;
    }
    if( !done && !found )
      dref(iptin) = 0;
    iptin++;
  }

  //Check if there are an odd number of ""
  if( is_odd(quotes) )
  {
    printf( "Parse error: Unable to match \"\" delimiters.\n" );
    return -1;
  }

  //Allocate Exactly Enough Memory
  if( dref(argc) > 0 )
    args = (char**) malloc( (dref(argc)+1)*sizeof(char*) );
  else
    return 0;

  //Store Arguments
  found = 0;
  argin = input;
  while( argin < iptin )
  {
    if( dref(argin) != 0 )
    {
      if( !found )
      {
        //printf( "Argument %d: %s\n" , count , argin );
        args[count++] = argin;
      }
      found = 1;
    }
    else
      found = 0;
    argin++;
  }
  args[dref(argc)] = NULL;

  //For testing purposes
  if( dref(argc) > 0 && argv != NULL )
  {
    dref(argv) = args;
  }
  else
    free(args);
  return 0;
}
Exemple #12
0
int
main(int argc, char *argv[])
{
    netsnmp_session session, *ss;
    netsnmp_pdu    *pdu, *response;
    netsnmp_variable_list *vars;
    int             arg;
    char           *gateway;

    int             count;
    struct varInfo *vip;
    u_int           value = 0;
    struct counter64 c64value;
    float           printvalue;
    time_t          last_time = 0;
    time_t          this_time;
    time_t          delta_time;
    int             sum;        /* what the heck is this for, its never used? */
    char            filename[128] = { 0 };
    struct timeval  tv;
    struct tm       tm;
    char            timestring[64] = { 0 }, valueStr[64] = {
    0}, maxStr[64] = {
    0};
    char            outstr[256] = { 0 }, peakStr[64] = {
    0};
    int             status;
    int             begin, end, last_end;
    int             print = 1;
    int             exit_code = 0;

    switch (arg = snmp_parse_args(argc, argv, &session, "C:", &optProc)) {
    case -2:
        exit(0);
    case -1:
        usage();
        exit(1);
    default:
        break;
    }

    gateway = session.peername;

    for (; optind < argc; optind++) {
	if (current_name >= MAX_ARGS) {
	    fprintf(stderr, "%s: Too many variables specified (max %d)\n",
	    	argv[optind], MAX_ARGS);
	    exit(1);
	}
        varinfo[current_name++].name = argv[optind];
    }

    if (current_name == 0) {
        usage();
        exit(1);
    }

    if (dosum) {
	if (current_name >= MAX_ARGS) {
	    fprintf(stderr, "Too many variables specified (max %d)\n",
	    	MAX_ARGS);
	    exit(1);
	}
        varinfo[current_name++].name = 0;
    }

    SOCK_STARTUP;

    /*
     * open an SNMP session 
     */
    ss = snmp_open(&session);
    if (ss == NULL) {
        /*
         * diagnose snmp_open errors with the input netsnmp_session pointer 
         */
        snmp_sess_perror("snmpdelta", &session);
        SOCK_CLEANUP;
        exit(1);
    }

    if (tableForm && timestamp) {
        printf("%s", gateway);
    }
    for (count = 0; count < current_name; count++) {
        vip = varinfo + count;
        if (vip->name) {
            vip->oidlen = MAX_OID_LEN;
            vip->info_oid = (oid *) malloc(sizeof(oid) * vip->oidlen);
            if (snmp_parse_oid(vip->name, vip->info_oid, &vip->oidlen) ==
                NULL) {
                snmp_perror(vip->name);
                SOCK_CLEANUP;
                exit(1);
            }
            sprint_descriptor(vip->descriptor, vip);
            if (tableForm)
                printf("\t%s", vip->descriptor);
        } else {
            vip->oidlen = 0;
            strcpy(vip->descriptor, SumFile);
        }
        vip->value = 0;
        zeroU64(&vip->c64value);
        vip->time = 0;
        vip->max = 0;
        if (peaks) {
            vip->peak_count = -1;
            vip->peak = 0;
            vip->peak_average = 0;
        }
    }

    wait_for_period(period);

    end = current_name;
    sum = 0;
    while (1) {
        pdu = snmp_pdu_create(SNMP_MSG_GET);

        if (deltat)
            snmp_add_null_var(pdu, sysUpTimeOid, sysUpTimeLen);

        if (end == current_name)
            count = 0;
        else
            count = end;
        begin = count;
        for (; count < current_name
             && count < begin + varbindsPerPacket - deltat; count++) {
            if (varinfo[count].oidlen)
                snmp_add_null_var(pdu, varinfo[count].info_oid,
                                  varinfo[count].oidlen);
        }
        last_end = end;
        end = count;

      retry:
        status = snmp_synch_response(ss, pdu, &response);
        if (status == STAT_SUCCESS) {
            if (response->errstat == SNMP_ERR_NOERROR) {
                if (timestamp) {
                    gettimeofday(&tv, (struct timezone *) 0);
                    memcpy(&tm, localtime((time_t *) & tv.tv_sec),
                           sizeof(tm));
                    if (((period % 60)
                         && (!peaks || ((period * peaks) % 60)))
                        || keepSeconds)
                        sprintf(timestring, " [%02d:%02d:%02d %d/%d]",
                                tm.tm_hour, tm.tm_min, tm.tm_sec,
                                tm.tm_mon + 1, tm.tm_mday);
                    else
                        sprintf(timestring, " [%02d:%02d %d/%d]",
                                tm.tm_hour, tm.tm_min,
                                tm.tm_mon + 1, tm.tm_mday);
                }

                vars = response->variables;
                if (deltat) {
                    if (!vars || !vars->val.integer) {
                        fprintf(stderr, "Missing variable in reply\n");
                        continue;
                    } else {
                        this_time = *(vars->val.integer);
                    }
                    vars = vars->next_variable;
                } else {
                    this_time = 1;
                }

                for (count = begin; count < end; count++) {
                    vip = varinfo + count;

                    if (vip->oidlen) {
                        if (!vars || !vars->val.integer) {
                            fprintf(stderr, "Missing variable in reply\n");
                            break;
                        }
                        vip->type = vars->type;
                        if (vars->type == ASN_COUNTER64) {
                            u64Subtract(vars->val.counter64,
                                        &vip->c64value, &c64value);
                            memcpy(&vip->c64value, vars->val.counter64,
                                   sizeof(struct counter64));
                        } else {
                            value = *(vars->val.integer) - vip->value;
                            vip->value = *(vars->val.integer);
                        }
                        vars = vars->next_variable;
                    } else {
                        value = sum;
                        sum = 0;
                    }
                    delta_time = this_time - vip->time;
                    if (delta_time <= 0)
                        delta_time = 100;
                    last_time = vip->time;
                    vip->time = this_time;
                    if (last_time == 0)
                        continue;

                    if (vip->oidlen && vip->type != ASN_COUNTER64) {
                        sum += value;
                    }

                    if (tableForm) {
                        if (count == begin) {
                            sprintf(outstr, "%s", timestring + 1);
                        } else {
                            outstr[0] = '\0';
                        }
                    } else {
                        sprintf(outstr, "%s %s", timestring,
                                vip->descriptor);
                    }

                    if (deltat || tableForm) {
                        if (vip->type == ASN_COUNTER64) {
                            fprintf(stderr,
                                    "time delta and table form not supported for counter64s\n");
                            exit(1);
                        } else {
                            printvalue =
                                ((float) value * 100) / delta_time;
                            if (tableForm)
                                sprintf(valueStr, "\t%.2f", printvalue);
                            else
                                sprintf(valueStr, " /sec: %.2f",
                                        printvalue);
                        }
                    } else {
                        printvalue = (float) value;
                        sprintf(valueStr, " /%d sec: ", period);
                        if (vip->type == ASN_COUNTER64)
                            printU64(valueStr + strlen(valueStr),
                                     &c64value);
                        else
                            sprintf(valueStr + strlen(valueStr), "%u",
                                    value);
                    }

                    if (!peaks) {
                        strcat(outstr, valueStr);
                    } else {
                        print = 0;
                        if (vip->peak_count == -1) {
                            if (wait_for_peak_start(period, peaks) == 0)
                                vip->peak_count = 0;
                        } else {
                            vip->peak_average += printvalue;
                            if (vip->peak < printvalue)
                                vip->peak = printvalue;
                            if (++vip->peak_count == peaks) {
                                if (deltat)
                                    sprintf(peakStr,
                                            " /sec: %.2f	(%d sec Peak: %.2f)",
                                            vip->peak_average /
                                            vip->peak_count, period,
                                            vip->peak);
                                else
                                    sprintf(peakStr,
                                            " /%d sec: %.0f	(%d sec Peak: %.0f)",
                                            period,
                                            vip->peak_average /
                                            vip->peak_count, period,
                                            vip->peak);
                                vip->peak_average = 0;
                                vip->peak = 0;
                                vip->peak_count = 0;
                                print = 1;
                                strcat(outstr, peakStr);
                            }
                        }
                    }

                    if (printmax) {
                        if (printvalue > vip->max) {
                            vip->max = printvalue;
                        }
                        if (deltat)
                            sprintf(maxStr, "	(Max: %.2f)", vip->max);
                        else
                            sprintf(maxStr, "	(Max: %.0f)", vip->max);
                        strcat(outstr, maxStr);
                    }

                    if (print) {
                        if (fileout) {
                            sprintf(filename, "%s-%s", gateway,
                                    vip->descriptor);
                            print_log(filename, outstr + 1);
                        } else {
                            if (tableForm)
                                printf("%s", outstr);
                            else
                                printf("%s\n", outstr + 1);
                            fflush(stdout);
                        }
                    }
                }
                if (end == last_end && tableForm)
                    printf("\n");
            } else {
                if (response->errstat == SNMP_ERR_TOOBIG) {
                    if (response->errindex <= varbindsPerPacket
                        && response->errindex > 0) {
                        varbindsPerPacket = response->errindex - 1;
                    } else {
                        if (varbindsPerPacket > 30)
                            varbindsPerPacket -= 5;
                        else
                            varbindsPerPacket--;
                    }
                    if (varbindsPerPacket <= 0) {
                        exit_code = 5;
                        break;
                    }
                    end = last_end;
                    continue;
                } else if (response->errindex != 0) {
                    fprintf(stderr, "Failed object: ");
                    for (count = 1, vars = response->variables;
                         vars && count != response->errindex;
                         vars = vars->next_variable, count++);
                    if (vars)
                        fprint_objid(stderr, vars->name,
                                     vars->name_length);
                    fprintf(stderr, "\n");
                    /*
                     * Don't exit when OIDs from file are not found on agent
                     * exit_code = 1;
                     * break;
                     */
                } else {
                    fprintf(stderr, "Error in packet: %s\n",
                            snmp_errstring(response->errstat));
                    exit_code = 1;
                    break;
                }

                /*
                 * retry if the errored variable was successfully removed 
                 */
                if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, 
					    NETSNMP_DS_APP_DONT_FIX_PDUS)) {
                    pdu = snmp_fix_pdu(response, SNMP_MSG_GET);
                    snmp_free_pdu(response);
                    response = NULL;
                    if (pdu != NULL)
                        goto retry;
                }
            }

        } else if (status == STAT_TIMEOUT) {
            fprintf(stderr, "Timeout: No Response from %s\n", gateway);
            response = 0;
            exit_code = 1;
            break;
        } else {                /* status == STAT_ERROR */
            snmp_sess_perror("snmpdelta", ss);
            response = 0;
            exit_code = 1;
            break;
        }

        if (response)
            snmp_free_pdu(response);
        if (end == current_name) {
            wait_for_period(period);
        }
    }
    snmp_close(ss);
    SOCK_CLEANUP;
    return (exit_code);
}
Exemple #13
0
/* We expect four arguments:
   - source directory name
   - object directory
   - common object directory
   - the program name with path
*/
int
main (int argc, char *argv[])
{
    const char *srcdir;
    const char *objdir;
    const char *common_objdir;
    const char *progpath;
    struct stat64 st1;
    struct stat64 st2;
    struct stat64 st3;
    DIR *dir1;
    DIR *dir2;
    int result = 0;
    struct dirent64 *d;
    struct dirent64 direntbuf;
    char *objdir_copy1;
    char *objdir_copy2;
    char *buf;
    int fd;

    mtrace ();

    if (argc < 5)
    {
        puts ("not enough parameters");
        exit (1);
    }

    /* Make parameters available with nicer names.  */
    srcdir = argv[1];
    objdir = argv[2];
    common_objdir = argv[3];
    progpath = argv[4];

    /* First test the current source dir.  We cannot really compare the
       result of `getpwd' with the srcdir string but we have other means.  */
    if (stat64 (".", &st1) < 0)
    {
        printf ("cannot stat starting directory: %m\n");
        exit (1);
    }

    if (chdir (srcdir) < 0)
    {
        printf ("cannot change to source directory: %m\n");
        exit (1);
    }
    if (stat64 (".", &st2) < 0)
    {
        printf ("cannot stat source directory: %m\n");
        exit (1);
    }

    /* The two last stat64 calls better were for the same directory.  */
    if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
    {
        printf ("stat of source directory failed: (%lld,%lld) vs (%lld,%lld)\n",
                (long long int) st1.st_dev, (long long int) st1.st_ino,
                (long long int) st2.st_dev, (long long int) st2.st_ino);
        exit (1);
    }

    /* Change to the object directory.  */
    if (chdir (objdir) < 0)
    {
        printf ("cannot change to object directory: %m\n");
        exit (1);
    }
    if (stat64 (".", &st1) < 0)
    {
        printf ("cannot stat object directory: %m\n");
        exit (1);
    }
    /* Is this the same we get as with the full path?  */
    if (stat64 (objdir, &st2) < 0)
    {
        printf ("cannot stat object directory with full path: %m\n");
        exit (1);
    }
    if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
    {
        printf ("stat of object directory failed: (%lld,%lld) vs (%lld,%lld)\n",
                (long long int) st1.st_dev, (long long int) st1.st_ino,
                (long long int) st2.st_dev, (long long int) st2.st_ino);
        exit (1);
    }

    objdir_copy1 = getcwd (NULL, 0);
    if (objdir_copy1 == NULL)
    {
        printf ("cannot get current directory name for object directory: %m\n");
        result = 1;
    }

    /* First test: this directory must include our program.  */
    if (stat64 (progpath, &st2) < 0)
    {
        printf ("cannot stat program: %m\n");
        exit (1);
    }

    dir1 = opendir (".");
    if (dir1 == NULL)
    {
        printf ("cannot open object directory: %m\n");
        exit (1);
    }

    while ((d = readdir64 (dir1)) != NULL)
    {
#ifdef _DIRENT_HAVE_D_TYPE
        if (d->d_type != DT_UNKNOWN && d->d_type != DT_REG)
            continue;
#endif

        if (d->d_ino == st2.st_ino)
        {
            /* Might be it.  Test the device.  We could use the st_dev
               element from st1 but what the heck, do more testing.  */
            if (stat64 (d->d_name, &st3) < 0)
            {
                printf ("cannot stat entry from readdir: %m\n");
                result = 1;
                d = NULL;
                break;
            }

            if (st3.st_dev == st2.st_dev)
                break;
        }
    }

    if (d == NULL)
    {
        puts ("haven't found program in object directory");
        result = 1;
    }

    /* We leave dir1 open.  */

    /* Stat using file descriptor.  */
    if (fstat64 (dirfd (dir1), &st2) < 0)
    {
        printf ("cannot fstat object directory: %m\n");
        result = 1;
    }
    if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
    {
        printf ("fstat of object directory failed: (%lld,%lld) vs (%lld,%lld)\n",
                (long long int) st1.st_dev, (long long int) st1.st_ino,
                (long long int) st2.st_dev, (long long int) st2.st_ino);
        exit (1);
    }

    if (chdir ("..") < 0)
    {
        printf ("cannot go to common object directory with \"..\": %m\n");
        exit (1);
    }

    if (stat64 (".", &st1) < 0)
    {
        printf ("cannot stat common object directory: %m\n");
        exit (1);
    }
    /* Is this the same we get as with the full path?  */
    if (stat64 (common_objdir, &st2) < 0)
    {
        printf ("cannot stat common object directory with full path: %m\n");
        exit (1);
    }
    if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
    {
        printf ("stat of object directory failed: (%lld,%lld) vs (%lld,%lld)\n",
                (long long int) st1.st_dev, (long long int) st1.st_ino,
                (long long int) st2.st_dev, (long long int) st2.st_ino);
        exit (1);
    }

    /* Stat using file descriptor.  */
    if (fstat64 (dirfd (dir1), &st2) < 0)
    {
        printf ("cannot fstat object directory: %m\n");
        result = 1;
    }

    dir2 = opendir (common_objdir);
    if (dir2 == NULL)
    {
        printf ("cannot open common object directory: %m\n");
        exit (1);
    }

    while ((d = readdir64 (dir2)) != NULL)
    {
#ifdef _DIRENT_HAVE_D_TYPE
        if (d->d_type != DT_UNKNOWN && d->d_type != DT_DIR)
            continue;
#endif

        if (d->d_ino == st2.st_ino)
        {
            /* Might be it.  Test the device.  We could use the st_dev
               element from st1 but what the heck, do more testing.  */
            if (stat64 (d->d_name, &st3) < 0)
            {
                printf ("cannot stat entry from readdir: %m\n");
                result = 1;
                d = NULL;
                break;
            }

            if (st3.st_dev == st2.st_dev)
                break;
        }
    }

    /* This better should be the object directory again.  */
    if (fchdir (dirfd (dir1)) < 0)
    {
        printf ("cannot fchdir to object directory: %m\n");
        exit (1);
    }

    objdir_copy2 = getcwd (NULL, 0);
    if (objdir_copy2 == NULL)
    {
        printf ("cannot get current directory name for object directory: %m\n");
        result = 1;
    }
    if (strcmp (objdir_copy1, objdir_copy2) != 0)
    {
        puts ("getcwd returned a different string the second time");
        result = 1;
    }

    /* This better should be the common object directory again.  */
    if (fchdir (dirfd (dir2)) < 0)
    {
        printf ("cannot fchdir to common object directory: %m\n");
        exit (1);
    }

    if (stat64 (".", &st2) < 0)
    {
        printf ("cannot stat common object directory: %m\n");
        exit (1);
    }
    if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
    {
        printf ("stat of object directory failed: (%lld,%lld) vs (%lld,%lld)\n",
                (long long int) st1.st_dev, (long long int) st1.st_ino,
                (long long int) st2.st_dev, (long long int) st2.st_ino);
        exit (1);
    }

    buf = (char *) malloc (strlen (objdir_copy1) + 1 + sizeof "tst-dir.XXXXXX");
    if (buf == NULL)
    {
        printf ("cannot allocate buffer: %m");
        exit (1);
    }

    stpcpy (stpcpy (stpcpy (buf, objdir_copy1), "/"), "tst-dir.XXXXXX");
    if (mkdtemp (buf) == NULL)
    {
        printf ("cannot create test directory in object directory: %m\n");
        exit (1);
    }
    if (stat64 (buf, &st1) < 0)
    {
        printf ("cannot stat new directory \"%s\": %m\n", buf);
        exit (1);
    }
    if (chmod (buf, 0700) < 0)
    {
        printf ("cannot change mode of new directory: %m\n");
        exit (1);
    }

    /* Try to find the new directory.  */
    rewinddir (dir1);
    while (readdir64_r (dir1, &direntbuf, &d) == 0 && d != NULL)
    {
#ifdef _DIRENT_HAVE_D_TYPE
        if (d->d_type != DT_UNKNOWN && d->d_type != DT_DIR)
            continue;
#endif

        if (d->d_ino == st1.st_ino)
        {
            /* Might be it.  Test the device.  We could use the st_dev
               element from st1 but what the heck, do more testing.  */
            size_t len = strlen (objdir) + 1 + _D_EXACT_NAMLEN (d) + 1;
            char tmpbuf[len];

            stpcpy (stpcpy (stpcpy (tmpbuf, objdir), "/"), d->d_name);

            if (stat64 (tmpbuf, &st3) < 0)
            {
                printf ("cannot stat entry from readdir: %m\n");
                result = 1;
                d = NULL;
                break;
            }

            if (st3.st_dev == st2.st_dev
                    && strcmp (d->d_name, buf + strlen (buf) - 14) == 0)
                break;
        }
    }

    if (d == NULL)
    {
        printf ("haven't found new directory \"%s\"\n", buf);
        exit (1);
    }

    if (closedir (dir2) < 0)
    {
        printf ("closing dir2 failed: %m\n");
        result = 1;
    }

    if (chdir (buf) < 0)
    {
        printf ("cannot change to new directory: %m\n");
        exit (1);
    }

    dir2 = opendir (buf);
    if (dir2 == NULL)
    {
        printf ("cannot open new directory: %m\n");
        exit (1);
    }

    if (fstat64 (dirfd (dir2), &st2) < 0)
    {
        printf ("cannot fstat new directory \"%s\": %m\n", buf);
        exit (1);
    }
    if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
    {
        printf ("stat of new directory failed: (%lld,%lld) vs (%lld,%lld)\n",
                (long long int) st1.st_dev, (long long int) st1.st_ino,
                (long long int) st2.st_dev, (long long int) st2.st_ino);
        exit (1);
    }

    if (mkdir ("another-dir", 0777) < 0)
    {
        printf ("cannot create \"another-dir\": %m\n");
        exit (1);
    }
    fd = open ("and-a-file", O_RDWR | O_CREAT | O_EXCL, 0666);
    if (fd == -1)
    {
        printf ("cannot create \"and-a-file\": %m\n");
        exit (1);
    }
    close (fd);

    /* Some tests about error reporting.  */
    errno = 0;
    if (chdir ("and-a-file") >= 0)
    {
        printf ("chdir to \"and-a-file\" succeeded\n");
        exit (1);
    }
    if (errno != ENOTDIR)
    {
        printf ("chdir to \"and-a-file\" didn't set correct error\n");
        result = 1;
    }

    errno = 0;
    if (chdir ("and-a-file/..") >= 0)
    {
        printf ("chdir to \"and-a-file/..\" succeeded\n");
        exit (1);
    }
    if (errno != ENOTDIR)
    {
        printf ("chdir to \"and-a-file/..\" didn't set correct error\n");
        result = 1;
    }

    errno = 0;
    if (chdir ("another-dir/../and-a-file") >= 0)
    {
        printf ("chdir to \"another-dir/../and-a-file\" succeeded\n");
        exit (1);
    }
    if (errno != ENOTDIR)
    {
        printf ("chdir to \"another-dir/../and-a-file\" didn't set correct error\n");
        result = 1;
    }

    /* We now should have a directory and a file in the new directory.  */
    rewinddir (dir2);
    while (readdir64_r (dir2, &direntbuf, &d) == 0 && d != NULL)
    {
        if (strcmp (d->d_name, ".") == 0
                || strcmp (d->d_name, "..") == 0
                || strcmp (d->d_name, "another-dir") == 0)
        {
#ifdef _DIRENT_HAVE_D_TYPE
            if (d->d_type != DT_UNKNOWN && d->d_type != DT_DIR)
            {
                printf ("d_type for \"%s\" is wrong\n", d->d_name);
                result = 1;
            }
#endif
            if (stat64 (d->d_name, &st3) < 0)
            {
                printf ("cannot stat \"%s\" is wrong\n", d->d_name);
                result = 1;
            }
            else if (! S_ISDIR (st3.st_mode))
            {
                printf ("\"%s\" is no directory\n", d->d_name);
                result = 1;
            }
        }
        else if (strcmp (d->d_name, "and-a-file") == 0)
        {
#ifdef _DIRENT_HAVE_D_TYPE
            if (d->d_type != DT_UNKNOWN && d->d_type != DT_REG)
            {
                printf ("d_type for \"%s\" is wrong\n", d->d_name);
                result = 1;
            }
#endif
            if (stat64 (d->d_name, &st3) < 0)
            {
                printf ("cannot stat \"%s\" is wrong\n", d->d_name);
                result = 1;
            }
            else if (! S_ISREG (st3.st_mode))
            {
                printf ("\"%s\" is no regular file\n", d->d_name);
                result = 1;
            }
        }
        else
        {
            printf ("unexpected directory entry \"%s\"\n", d->d_name);
            result = 1;
        }
    }

    if (stat64 ("does-not-exist", &st1) >= 0)
    {
        puts ("stat for unexisting file did not fail");
        result = 1;
    }

    /* Free all resources.  */

    if (closedir (dir1) < 0)
    {
        printf ("closing dir1 failed: %m\n");
        result = 1;
    }
    if (closedir (dir2) < 0)
    {
        printf ("second closing dir2 failed: %m\n");
        result = 1;
    }

    if (rmdir ("another-dir") < 0)
    {
        printf ("cannot remove \"another-dir\": %m\n");
        result = 1;
    }

    if (unlink ("and-a-file") < 0)
    {
        printf ("cannot remove \"and-a-file\": %m\n");
        result = 1;
    }

    /* One more test before we leave: mkdir() is supposed to fail with
       EEXIST if the named file is a symlink.  */
    if (symlink ("a-symlink", "a-symlink") != 0)
    {
        printf ("cannot create symlink \"a-symlink\": %m\n");
        result = 1;
    }
    else
    {
        if (mkdir ("a-symlink", 0666) == 0)
        {
            puts ("can make directory \"a-symlink\"");
            result = 1;
        }
        else if (errno != EEXIST)
        {
            puts ("mkdir(\"a-symlink\") does not fail with EEXIST\n");
            result = 1;
        }
        if (unlink ("a-symlink") < 0)
        {
            printf ("cannot unlink \"a-symlink\": %m\n");
            result = 1;
        }
    }

    if (chdir (srcdir) < 0)
    {
        printf ("cannot change back to source directory: %m\n");
        exit (1);
    }

    if (rmdir (buf) < 0)
    {
        printf ("cannot remove \"%s\": %m\n", buf);
        result = 1;
    }
    free (objdir_copy1);
    free (objdir_copy2);

    if (result == 0)
        puts ("all OK");

    return result;
}
Exemple #14
0
/* Decode a bufferful of file. */
IGL_INLINE static int
rle_fread(RLEstate *rleInfo, unsigned char *vbuf, size_t datasize, size_t nelems, FILE *fp)
{

  unsigned char *buf = vbuf;
  int j, k;
  int buflen, count, bytes, curbytes;
  unsigned char *p;

  /* Scale the buffer length. */
  buflen = nelems * datasize;

  j = 0;
  curbytes = totbytes;
  while (j < buflen) {
    if (rleInfo->laststate < rleInfo->statelen) {
      /* Copy bytes from our previously decoded buffer. */
      bytes = MIN(buflen - j, rleInfo->statelen - rleInfo->laststate);
      memcpy(buf + j, rleInfo->statebuf + rleInfo->laststate, bytes);
      j += bytes;
      rleInfo->laststate += bytes;

      /* If we used up all of our state bytes, then reset them. */
      if (rleInfo->laststate >= rleInfo->statelen) {
        rleInfo->laststate = 0;
        rleInfo->statelen = 0;
      }

      /* If we filled the buffer, then exit the loop. */
      if (j >= buflen) break;
    }

    /* Decode the next packet. */
    count = fgetc(fp);
    if (count == EOF) {
      if (_verbose) printf("TGA: hit EOF while looking for count\n");
      return j / datasize;
    }

    /* Scale the byte length to the size of the data. */
    bytes = ((count & ~RLE_PACKETSIZE) + 1) * datasize;

    if (j + bytes <= buflen) {
      /* We can copy directly into the image buffer. */
      p = buf + j;
    } else {
#ifdef PROFILE
      printf("TGA: needed to use statebuf for %d bytes\n", buflen - j);
#endif
      /* Allocate the state buffer if we haven't already. */
      if (!rleInfo->statebuf) {
        rleInfo->statebuf = (unsigned char *) malloc(RLE_PACKETSIZE * datasize);
      }
      p = rleInfo->statebuf;
    }

    if (count & RLE_PACKETSIZE) {
      /* Fill the buffer with the next value. */
      if (fread(p, datasize, 1, fp) != 1) {
        if (_verbose) {
          printf("TGA: EOF while reading %d/%d element RLE packet\n",
            bytes, (int)datasize);
        }
        return j / datasize;
      }

      /* Optimized case for single-byte encoded data. */
      if (datasize == 1) {
        memset(p + 1, *p, bytes - 1);
      } else {
        for (k = datasize; k < bytes; k += datasize) {
          memcpy(p + k, p, datasize);
        }
      }
    } else {
      /* Read in the buffer. */
      if (fread(p, bytes, 1, fp) != 1) {
        if (_verbose) {
          printf("TGA: EOF while reading %d/%d element raw packet\n",
            bytes, (int)datasize);
        }
        return j / datasize;
      }
    }

    if (_verbose > 1) {
      totbytes += bytes;
      if (_verbose > 2) {
        printf("TGA: %s packet %d/%d\n",
          (count & RLE_PACKETSIZE) ? "RLE" : "raw",
          bytes, totbytes);
      }
    }

    /* We may need to copy bytes from the state buffer. */
    if (p == rleInfo->statebuf) {
      rleInfo->statelen = bytes;
    } else {
      j += bytes;
    }
  }

  if (_verbose > 1) {
    printf("TGA: rle_fread %d/%d (total %d)\n",
    (int) ( nelems * datasize), totbytes - curbytes, totbytes);
  }
  return nelems;
}
Exemple #15
0
static int open_sgi(audio_output_t *ao)
{
	int dev = AL_DEFAULT_OUTPUT;
	ALconfig config = alNewConfig();
	ALport port = NULL;
	
	/* Test for correct completion */
	if (config == 0) {
		error1("open_sgi: %s",alGetErrorString(oserror()));
		return -1;
	}
	
	/* Set port parameters */
	if(ao->channels == 2)
		alSetChannels(config, AL_STEREO);
	else
		alSetChannels(config, AL_MONO);
	
	alSetWidth(config, AL_SAMPLE_16);
	alSetSampFmt(config,AL_SAMPFMT_TWOSCOMP);
	alSetQueueSize(config, 131069);
	
	/* Setup output device to specified module. If there is no module
	specified in ao structure, use the default four output */
	if ((ao->device) != NULL) {
		char *dev_name;
		
		dev_name=malloc((strlen(ao->device) + strlen(analog_output_res_name) + 1) *
		  sizeof(char));
		
		strcpy(dev_name,ao->device);
		strcat(dev_name,analog_output_res_name);
		
		/* Find the asked device resource */
		dev=alGetResourceByName(AL_SYSTEM,dev_name,AL_DEVICE_TYPE);
		
		/* Free allocated space */
		free(dev_name);
		
		if (!dev) {
			error2("Invalid audio resource: %s (%s)",dev_name, alGetErrorString(oserror()));
			return -1;
		}
	}
	
	/* Set the device */
	if (alSetDevice(config,dev) < 0)
	{
		error1("open_sgi: %s",alGetErrorString(oserror()));
		return -1;
	}
	
	/* Open the audio port */
	port = alOpenPort("mpg123-VSC", "w", config);
	if(port == NULL) {
		error1("Unable to open audio channel: %s", alGetErrorString(oserror()));
		return -1;
	}
	
	ao->handle = (void*)port;
	
	
	set_format(ao, config);
	set_channels(ao, config);
	set_rate(ao, config);
	
	
	alFreeConfig(config);
	
	return 1;
}
Exemple #16
0
void uhc_summarize_results(
    int num_genes,
    int num_chromosomes,
    int num_genomes,
    int circular,
    struct genome_struct *genome_list_in,
    int nsegs,
    int *seg_list,

    /* output */
    struct uhc_mem *uhcmem,
    struct genome_struct *out_genome
)
{
    int d;

    int count;
    int s1, s2;
    int bestd, num_best;
    int k;

    int *curseg;
    int cur_len;
    int cur_genome_num;
    struct genome_struct *cur_genome = (struct genome_struct *) 0;

    int *sign_groups;

    int i1,i2,max_entry;
    int *dmat = uhcmem->dmat;

    /**********************************************************************
     * Calc sign groups
     **********************************************************************/
    //printf("uhc_summarize_results\n");
    sign_groups = (int *) e_malloc(nsegs * sizeof(int),
                                   "uhc_summarize_results: sign_groups");
    calc_sign_groups(sign_groups,
                     uhcmem);



    //printf("STOP_1\n");
    /**********************************************************************
     * # runs at each distance
     **********************************************************************/

    //f//printf(outfile, "\n# trials giving each score:\n");
    /*f//printf(outfile, "%*s  # times\n",
    uhcmem->width_score2, "score");*/
    for (d=0; d < uhcmem->max_dist_possible; d++) {
    if (uhcmem->dist_counts[d] > 0) {
            /*f//printf(outfile, "%*d  %d\n",
            uhcmem->width_score2, d,
                   uhcmem->dist_counts[d]);*/
        }
    }
    if (uhcmem->dist_counts[uhcmem->max_dist_possible] != 0) {
        /* TODO: improve handling of this for arbitrary weight matrices */
        /*f//printf(outfile, "%*s  %d\n",
        uhcmem->width_score2, "other",
        uhcmem->dist_counts[uhcmem->max_dist_possible]);*/
    }

    //printf("STOP_2\n");
    /**********************************************************************
     * at best dist: sign pattern
     **********************************************************************/

    bestd = uhcmem->best_dist;
    num_best = uhcmem->dist_counts[bestd];

    //f//printf(outfile, "\n");
    //printf("STOP_3\n");
    /**********************************************************************
     * at best dist: perfect correlation groups
     **********************************************************************/

    //f//printf(outfile, "\n");
    //printf("STOP_4\n");
    /**********************************************************************
     * at best dist: sign counts
     **********************************************************************/

    //f//printf(outfile,"\nSign counts and perfect correlations:\n");
    cur_genome_num = -1;
    for (s1 = 0; s1 < nsegs; s1++) {
    curseg = USEG(seg_list, s1);

        /* print genome name if switched genomes */
        if (curseg[0] != cur_genome_num) {
            cur_genome_num = curseg[0];
            cur_genome = &genome_list_in[cur_genome_num];
            if (cur_genome->gnamePtr != (char *) 0) {
                //f//printf(outfile, ">%s\n", cur_genome->gnamePtr);
            } else {
                //f//printf(outfile, ">genome%d\n", cur_genome_num + 1);
            }
        }

        cur_len = curseg[2];

        //f//printf(outfile, "S%-*d  [", uhcmem->width_segnum, s1);
        for (k=0; k<cur_len; k++) {
            //f//printf(outfile, " %d", cur_genome->genes[cur_start+k]);
        }
        //f//printf(outfile," ]   ");

        count = uhcmem->dist_corr[s1*nsegs+s1];
        /*f//printf(outfile,
        "%d+  %d-  "
        ,
        count, num_best-count);*/

        count = sign_groups[s1];
        if (count == -1-nsegs) {
        //f//printf(outfile, "sign -");
    } else if (count == nsegs) {
        //f//printf(outfile, "sign +");
    } else if (count == s1) {
    } else if (count >= 0) {
        //f//printf(outfile, "sign same as S%d", count);
    } else if (count < 0) {
        //f//printf(outfile, "sign same as -S%d", -1-count);
    }

    //f//printf(outfile, "\n");
}
//printf("STOP_5\n");
/**********************************************************************
 * at best dist: detailed correlations
 **********************************************************************/

//f//printf(outfile,"\nCorrelations: Number of times segments have same sign:\n");
for (s1=0; s1<nsegs; s1++) {
    //f//printf(outfile, "S%-*d  ", uhcmem->width_segnum, s1);
    for (s2=0; s2<nsegs; s2++) {
            if (s1 == s2) {
                count = num_best;
            } else if (s2<s1) {
                count = uhcmem->dist_corr[s2*nsegs+s1];
            } else {
                count = uhcmem->dist_corr[s1*nsegs+s2];
            }
            //f//printf(outfile, " %*d", uhcmem->width_run, count);
        }
        //f//printf(outfile, "\n");
    }
//printf("STOP_6\n");
    /**********************************************************************
     * at best dist: one particular signage
     **********************************************************************/

    //f//printf(outfile,"\nA best scoring solution:\n");

    uhc_setsigns(num_genes, num_chromosomes, num_genomes,
                 genome_list_in,
                 nsegs, seg_list, uhcmem->bestsigns,
                 uhcmem);

    /* Set the output genome */
    ////printf ("Genome list %u ", uhcmem);
    ////printf ("Genome list %d ", uhcmem->genome_list + 1);
    memcpy(out_genome, uhcmem->genome_list + 1, sizeof(struct genome_struct));
    out_genome->genes = malloc(sizeof(int) * num_genes);
    copy_genes((uhcmem->genome_list + 1)->genes, out_genome->genes, num_genes);

//printf("STOP_7\n");
    /**********************************************************************
     * and the pairwise matrix for that signage
     **********************************************************************/

    max_entry = 0;
    for (i1=0; i1<num_genomes; i1++) {
    dmat[num_genomes*i1 + i1] = 0;
        for (i2=0; i2<i1; i2++) {
            d =
                dmat[num_genomes*i1 + i2] =
                    dmat[num_genomes*i2 + i1] =
                        uhc_dist(uhcmem, i1, i2,
                                 num_genes, num_chromosomes, circular);
            if (d > max_entry) {
                max_entry = d;
            }
        }
    }
//printf("STOP_8\n");
    /* TODO: should integrate this with the other matrix printing routines */

    //DEBUG: deleted code here
}
Exemple #17
0
int main (int argc, char **argv)
{
  unsigned int L1_CacheSize; /* L1 data cache size in bytes */
  unsigned int L2_CacheSize; /* L2 data cache size in bytes */
  float Target_IPC = 0.5;
  float Target_MEM = 0.01;
  int IPC_weight = 5, Dcache_weight = 5;

  /* dcache vars */
  unsigned int * data;
  int i;         /* loop counter */
  unsigned int dataSize;  /* Size of the data array */
  unsigned int nextInd, prevInd; /* array indicies */
  register int bench_index;
  register unsigned int array_index;
  int dumb = 1;
  
  /* vary IPC vars */
  int a[100]; int pos = 0;
  int int1=1,int2=2,int3=3;
  double fp1=1.0, fp2=2.0, fp3=3.0;
  int d_low; int loopcount_hiIPC, loopcount_loIPC;
  
  
  /* 1) READ RATES */
  /*********************************************************************/
  if (argc != 7)
  {
    fprintf(stderr, "\nUsage: %s -I <IPC [0.0-2.0] > -M <Mem/Uop rate [0.0-0.060]> -W <Proportion of IPC loop [0-10]int> \n", argv[0]);
    fprintf(stderr, "i.e. %s -I 0.5 -M 0.020 -W 5\n\n", argv[0]);
    fprintf(stderr, "   Proportion of IPC loop: How much of the constructed bench mixture should be IPC varying bench.\n");  
    fprintf(stderr, "   For example,  5 means,  50%% varyIPC &  50%% Dcache.\n");  
    fprintf(stderr, "                 0 means,   0%% varyIPC & 100%% Dcache --> pure dcache bench.\n");  
    fprintf(stderr, "   For example, 10 means, 100%% varyIPC &   0%% Dcache --> pure vary IPC bench.\n");  
    exit(1);
  }
  
  if (strcmp(argv[1], "-I") == 0)
  {
    Target_IPC = atof(argv[2]);
    //printf("%.20f", Target_IPC);
  }
  else
  {
    fprintf(stderr,"\n\n\tDON't UNDERSTAND OPTION %s %s..\n", argv[1], argv[2]);
    fprintf(stderr,"\n\n\tShould be: -I <IPC> \n");
    exit(2);
  }

  if (strcmp(argv[3], "-M") == 0)
  {
    Target_MEM = atof(argv[4]);
    //printf("%.20f", Target_MEM);
  }
  else
  {
    fprintf(stderr,"\n\n\tDON't UNDERSTAND OPTION %s %s..\n", argv[3], argv[4]);
    fprintf(stderr,"\n\n\tShould be: -M <Mem Rate> \n");
    exit(2);
  }

  if (strcmp(argv[5], "-W") == 0)
  {
    IPC_weight = atoi(argv[6]);
    if ( (IPC_weight >= 0) && (IPC_weight <= 10) )
    {
      Dcache_weight = 10 - IPC_weight;
    }
    else {
      fprintf(stderr,"\n\n IPC loop proportion should be between [0,10]; NOT %d\n", IPC_weight);
    }
  }
  else
  {
    fprintf(stderr,"\n\n\tDON't UNDERSTAND OPTION %s %s..\n", argv[5], argv[6]);
    fprintf(stderr,"\n\n\tShould be: -W <Proportion of IPC loop> \n");
    exit(2);
  }
  /*********************************************************************/

  fprintf (stderr,"L1 Data Cache Size in bytes: (32K)\n");
  L1_CacheSize = 32*1024;
  /*scanf ("%d", &L1_CacheSize);*/
  fprintf (stderr,"L2 Data Cache Size in bytes: (1024K)\n");
  L2_CacheSize = 1024*1024;
  

  /*******************************************************************/
  /* Initialize hi & lo IPC loop weights, a array */
  /*******************************************************************/
  if ( (Target_IPC > 2.1) || (Target_IPC < 0.0) )
  {
    fprintf(stderr, "Target IPC (%f) Out of [0.0-2.0] range man chill out!\n", Target_IPC);
    exit(-1);
  }
  loopcount_hiIPC = MIN ( (int) ((Target_IPC/2.0)*1000.0), 1000);
  loopcount_loIPC = 1000 - loopcount_hiIPC;
  
  a[pos] = 4396; a[pos+1] = 155;
  /*######################################################################**/

  /*******************************************************************/
  /* Initialize THe Array Data */
  /*******************************************************************/
  if (Target_MEM < 0.0001)
  {
    dataSize = (unsigned int) (L1_CacheSize / 32); /*800% L1 hit rate*/
  }
  else if (Target_MEM < 0.045) 
  {
    dataSize = (unsigned int) ( 16379854.1665904*Target_MEM + 87223.0988672634 ); /* from piecewise curve fit */
  }
  else if (Target_MEM < 0.061) 
  {
    dataSize = (unsigned int) ( 287285513.968285*Target_MEM - 12408337.3961814 );/* from piecewise curve fit */
  }
  else 
  {
    fprintf(stderr, "TOO HIGH MEM RATE! Get Your act together!\n");
    exit(1);
  }

  data = (unsigned int *) malloc (sizeof (unsigned int) * dataSize); /*our huge array*/
  /* initially all -1*/
  for (i=0; i<dataSize; i++)
    data [i] = -1;
  /* assign the linked list type of values */
  prevInd = 0;
  for (i=0; i<dataSize-1; i++)
  /* each loop assignes 1 element do the whole thing assignes dataSize -1 elements */
  {
    /* find the 1st unassigned element (still -1) */
    do
    {
      nextInd = ((rand () << 15) | rand ()) % dataSize;
    } while (data[nextInd] != -1);
    data[prevInd] = nextInd; /* old element's value is new index */
    prevInd = nextInd;
  }
  data[prevInd] = 0; /* last element goes back to first */

  fprintf (stderr,"Done Initializing the Array!\n");
  /*######################################################################**/

  /*--------------------------------------------------------------*/
  /* Main Benchmark Loop */
  /*--------------------------------------------------------------*/
  array_index = 0; /* move Dcache array index out of main looop */
  
  for (bench_index=0; bench_index<3000; bench_index++)
  {

  /* Hi IPC loop */
    //fprintf(stderr, "\tIPC: 1.9 \n");
    i = 0;
    while (i<loopcount_hiIPC*IPC_weight*8) /* x8 to balance loop weights */
    {
       //fprintf(stdout, "pos: %d, a[pos]: %d, a[pos+1]: %d\n",pos, a[pos], a[pos+1]);getchar();	
       int1 = int1 + 1;
       int2 = a[pos] + a[pos+1];
       int3 = int1 + int2;
       int1 = int1 + 1;
       int2 = a[pos] + a[pos+1];
       int3 = int1 + int2;
       int1 = int1 + 1;
       int2 = a[pos] + a[pos+1];
       int3 = int1 + int2;
       a[pos] = int3;
       i ++;
       //fprintf(stdout, "pos: %d, a[pos]: %d, a[pos+1]: %d\n",pos, a[pos], a[pos+1]);getchar();	
    }

    /* Lo IPC loop */
    //fprintf(stderr, "\tIPC:0.1 \n");
    d_low = 0;
    while(d_low < loopcount_loIPC*IPC_weight)
    {
      // fprintf(stderr, "%.20f %.20f %.20f\n", fp1, fp2, fp3); getchar();
      fp1 = fp2 / fp3;
      fp2 = fp3 / fp1;
      fp3 = fp1 / fp2;
      fp1 = fp3 / fp2;
      fp2 = fp1 / fp3;
      fp3 = fp2 / fp1;
      fp1 = fp1 / 0.03292181069958847323;
      fp2 = fp2 / 0.22222222222222220989 / 0.5;
      fp3 = fp3 / 6.75000000000000088818 / 0.33333333333333333333;

      d_low = d_low+1;
    }

    /*  Dcache loop */
    for (i=0; i<10000*Dcache_weight; i++)
    {
      array_index = data[array_index];
      dumb = dumb + 1;
    }	
  } 
  /* EO MAIN BENCHMARK LOOP */
  fprintf(stdout, "dcache_iter/big_bench_loop_iter = %d/%d\n", dumb, bench_index);

  return 0;
}
Exemple #18
0
/*
 * Read a HTTP response from a socket.
 * Process Content-Length and Transfer-encoding headers.
 * return a pointer to the content buffer, which length is saved
 * to the length parameter.
 */
void *
getHTTPResponse(int s, int * size)
{
	char buf[2048];
	int n;
	int endofheaders = 0;
	int chunked = 0;
	int content_length = -1;
	unsigned int chunksize = 0;
	unsigned int bytestocopy = 0;
	/* buffers : */
	char * header_buf;
	int header_buf_len = 2048;
	int header_buf_used = 0;
	char * content_buf;
	int content_buf_len = 2048;
	int content_buf_used = 0;
	char chunksize_buf[32];
	int chunksize_buf_index;

	header_buf = malloc(header_buf_len);
	content_buf = malloc(content_buf_len);
	chunksize_buf[0] = '\0';
	chunksize_buf_index = 0;

	while((n = receivedata(s, buf, 2048, 5000)) > 0)
	{
		if(endofheaders == 0)
		{
			int i;
			int linestart=0;
			int colon=0;
			int valuestart=0;
			if(header_buf_used + n > header_buf_len) {
				header_buf = realloc(header_buf, header_buf_used + n);
				header_buf_len = header_buf_used + n;
			}
			memcpy(header_buf + header_buf_used, buf, n);
			header_buf_used += n;
			/* search for CR LF CR LF (end of headers)
			 * recognize also LF LF */
			i = 0;
			while(i < (header_buf_used-1) && (endofheaders == 0)) {
				if(header_buf[i] == '\r') {
					i++;
					if(header_buf[i] == '\n') {
						i++;
						if(i < header_buf_used && header_buf[i] == '\r') {
							i++;
							if(i < header_buf_used && header_buf[i] == '\n') {
								endofheaders = i+1;
							}
						}
					}
				} else if(header_buf[i] == '\n') {
					i++;
					if(header_buf[i] == '\n') {
						endofheaders = i+1;
					}
				}
				i++;
			}
			if(endofheaders == 0)
				continue;
			/* parse header lines */
			for(i = 0; i < endofheaders - 1; i++) {
				if(colon <= linestart && header_buf[i]==':')
				{
					colon = i;
					while(i < (endofheaders-1)
					      && (header_buf[i+1] == ' ' || header_buf[i+1] == '\t'))
						i++;
					valuestart = i + 1;
				}
				/* detecting end of line */
				else if(header_buf[i]=='\r' || header_buf[i]=='\n')
				{
					if(colon > linestart && valuestart > colon)
					{
#ifdef DEBUG
						printf("header='%.*s', value='%.*s'\n",
						       colon-linestart, header_buf+linestart,
						       i-valuestart, header_buf+valuestart);
#endif
						if(0==strncasecmp(header_buf+linestart, "content-length", colon-linestart))
						{
							content_length = atoi(header_buf+valuestart);
#ifdef DEBUG
							printf("Content-Length: %d\n", content_length);
#endif
						}
						else if(0==strncasecmp(header_buf+linestart, "transfer-encoding", colon-linestart)
						   && 0==strncasecmp(header_buf+valuestart, "chunked", 7))
						{
#ifdef DEBUG
							printf("chunked transfer-encoding!\n");
#endif
							chunked = 1;
						}
					}
					while(header_buf[i]=='\r' || header_buf[i] == '\n')
						i++;
					linestart = i;
					colon = linestart;
					valuestart = 0;
				} 
			}
			/* copy the remaining of the received data back to buf */
			n = header_buf_used - endofheaders;
			memcpy(buf, header_buf + endofheaders, n);
			/* if(headers) */
		}
		if(endofheaders)
		{
			/* content */
			if(chunked)
			{
				int i = 0;
				while(i < n)
				{
					if(chunksize == 0)
					{
						/* reading chunk size */
						if(chunksize_buf_index == 0) {
							/* skipping any leading CR LF */
							if(i<n && buf[i] == '\r') i++;
							if(i<n && buf[i] == '\n') i++;
						}
						while(i<n && isxdigit(buf[i])
						     && chunksize_buf_index < (sizeof(chunksize_buf)-1))
						{
							chunksize_buf[chunksize_buf_index++] = buf[i];
							chunksize_buf[chunksize_buf_index] = '\0';
							i++;
						}
						while(i<n && buf[i] != '\r' && buf[i] != '\n')
							i++; /* discarding chunk-extension */
						if(i<n && buf[i] == '\r') i++;
						if(i<n && buf[i] == '\n') {
							int j;
							for(j = 0; j < chunksize_buf_index; j++) {
							if(chunksize_buf[j] >= '0'
							   && chunksize_buf[j] <= '9')
								chunksize = (chunksize << 4) + (chunksize_buf[j] - '0');
							else
								chunksize = (chunksize << 4) + ((chunksize_buf[j] | 32) - 'a' + 10);
							}
							chunksize_buf[0] = '\0';
							chunksize_buf_index = 0;
							i++;
						} else {
							/* not finished to get chunksize */
							continue;
						}
#ifdef DEBUG
						printf("chunksize = %u (%x)\n", chunksize, chunksize);
#endif
						if(chunksize == 0)
						{
#ifdef DEBUG
							printf("end of HTTP content - %d %d\n", i, n);
							/*printf("'%.*s'\n", n-i, buf+i);*/
#endif
							goto end_of_stream;
						}
					}
					bytestocopy = ((int)chunksize < n - i)?chunksize:(n - i);
					if((int)(content_buf_used + bytestocopy) > content_buf_len)
					{
						if(content_length >= content_buf_used + (int)bytestocopy) {
							content_buf_len = content_length;
						} else {
							content_buf_len = content_buf_used + (int)bytestocopy;
						}
						content_buf = (char *)realloc((void *)content_buf, 
						                              content_buf_len);
					}
					memcpy(content_buf + content_buf_used, buf + i, bytestocopy);
					content_buf_used += bytestocopy;
					i += bytestocopy;
					chunksize -= bytestocopy;
				}
			}
			else
			{
				/* not chunked */
				if(content_length > 0
				   && (content_buf_used + n) > content_length) {
					/* skipping additional bytes */
					n = content_length - content_buf_used;
				}
				if(content_buf_used + n > content_buf_len)
				{
					if(content_length >= content_buf_used + n) {
						content_buf_len = content_length;
					} else {
						content_buf_len = content_buf_used + n;
					}
					content_buf = (char *)realloc((void *)content_buf, 
					                              content_buf_len);
				}
				memcpy(content_buf + content_buf_used, buf, n);
				content_buf_used += n;
			}
		}
		/* use the Content-Length header value if available */
		if(content_length > 0 && content_buf_used >= content_length)
		{
#ifdef DEBUG
			printf("End of HTTP content\n");
#endif
			break;
		}
	}
end_of_stream:
	free(header_buf); header_buf = NULL;
	*size = content_buf_used;
	if(content_buf_used == 0)
	{
		free(content_buf);
		content_buf = NULL;
	}
	return content_buf;
}
/*
 * Function: DHCPLeaseCreateWithDictionary
 * Purpose:
 *   Instantiate a new DHCPLease structure corresponding to the given
 *   dictionary.  Validates that required properties are present,
 *   returns NULL if those checks fail.
 */
static DHCPLeaseRef
DHCPLeaseCreateWithDictionary(CFDictionaryRef dict, bool is_wifi)
{
    CFDataRef			hwaddr_data;
    dhcp_lease_time_t		lease_time;
    DHCPLeaseRef		lease_p;
    CFDataRef			pkt_data;
    CFRange			pkt_data_range;
    struct in_addr *		router_p;
    CFStringRef			ssid = NULL;
    CFDateRef			start_date;
    dhcp_lease_time_t		t1_time;
    dhcp_lease_time_t		t2_time;

    /* get the lease start time */
    start_date = CFDictionaryGetValue(dict, kLeaseStartDate);
    if (isA_CFDate(start_date) == NULL) {
	goto failed;
    }
    /* get the packet data */
    pkt_data = CFDictionaryGetValue(dict, kPacketData);
    if (isA_CFData(pkt_data) == NULL) {
	goto failed;
    }
    /* if Wi-Fi, get the SSID */
    if (is_wifi) {
	ssid = CFDictionaryGetValue(dict, kSSID);
	if (isA_CFString(ssid) == NULL) {
	    goto failed;
	}
    }

    pkt_data_range.location = 0;
    pkt_data_range.length = CFDataGetLength(pkt_data);
    if (pkt_data_range.length < sizeof(struct dhcp)) {
	goto failed;
    }
    lease_p = (DHCPLeaseRef)
	malloc(offsetof(DHCPLease, pkt) + pkt_data_range.length);
    bzero(lease_p, offsetof(DHCPLease, pkt));

    /* copy the packet data */
    CFDataGetBytes(pkt_data, pkt_data_range, lease_p->pkt);
    lease_p->pkt_length = pkt_data_range.length;

    /* get the lease information and router IP address */
    lease_p->lease_start = (absolute_time_t)CFDateGetAbsoluteTime(start_date);
    { /* parse/retrieve options */
	dhcpol_t			options;
	
	(void)dhcpol_parse_packet(&options, (void *)lease_p->pkt,
				  pkt_data_range.length, NULL);
	dhcp_get_lease_from_options(&options, &lease_time, &t1_time, &t2_time);
	router_p = dhcp_get_router_from_options(&options, lease_p->our_ip);
	dhcpol_free(&options);
    }
    lease_p->lease_length = lease_time;

    /* get the IP address */
    /* ALIGN: lease_p->pkt is aligned, cast ok. */
    lease_p->our_ip = ((struct dhcp *)(void *)lease_p->pkt)->dp_yiaddr;

    /* get the router information */
    if (router_p != NULL) {
	CFRange		hwaddr_range;

	lease_p->router_ip = *router_p;
	/* get the router hardware address */
	hwaddr_data = CFDictionaryGetValue(dict, kRouterHardwareAddress);
	hwaddr_range.length = 0;
	if (isA_CFData(hwaddr_data) != NULL) {
	    hwaddr_range.length = CFDataGetLength(hwaddr_data);
	}
	if (hwaddr_range.length > 0) {
	    hwaddr_range.location = 0;
	    if (hwaddr_range.length > sizeof(lease_p->router_hwaddr)) {
		hwaddr_range.length = sizeof(lease_p->router_hwaddr);
	    }
	    lease_p->router_hwaddr_length = hwaddr_range.length;
	    CFDataGetBytes(hwaddr_data, hwaddr_range, lease_p->router_hwaddr);
	}
    }
    if (ssid != NULL) {
	CFRetain(ssid);
	lease_p->ssid = ssid;
    }
    return (lease_p);

 failed:
    return (NULL);
}
Exemple #20
0
static int Init( vout_thread_t *p_vout )
{
    vout_sys_t *p_sys = p_vout->p_sys;
    IDirectFBSurface *p_primary = (IDirectFBSurface *) p_vout->p_sys->p_primary;
    byte_t* p_pixels = NULL;
    picture_t *p_pic = NULL;
    int i_rlength, i_glength, i_blength;
    int i_roffset, i_goffset, i_boffset;
    int i_line_pitch;
    int i_size;
    int i_index;

    I_OUTPUTPICTURES = 0;

    switch( p_sys->p_pixel_format )
    {
        case DSPF_RGB332: 
            /* 8 bit RGB (1 byte, red 3@5, green 3@2, blue 2@0) */
            /* i_pixel_pitch = 1; */
            i_rlength = 3;
            i_roffset = 5;
            i_glength = 3;
            i_goffset = 2;
            i_blength = 2;
            i_boffset = 0;
            p_vout->output.i_chroma = VLC_FOURCC('R','G','B','2');
            break;

        case DSPF_RGB16:
            /* 16 bit RGB (2 byte, red 5@11, green 6@5, blue 5@0) */
            /* i_pixel_pitch = 2; */
            i_rlength = 5;
            i_roffset = 11;
            i_glength = 6;
            i_goffset = 5;
            i_blength = 5;
            i_boffset = 0;
            p_vout->output.i_chroma = VLC_FOURCC('R','V','1','6');
            break;

        case DSPF_RGB24:
            /* 24 bit RGB (3 byte, red 8@16, green 8@8, blue 8@0) */
            /* i_pixel_pitch = 3; */
            i_rlength = 8;
            i_roffset = 16;
            i_glength = 8;
            i_goffset = 8;
            i_blength = 8;
            i_boffset = 0;
            p_vout->output.i_chroma = VLC_FOURCC('R','V','2','4');
            break;

        case DSPF_RGB32:
            /* 24 bit RGB (4 byte, nothing@24, red 8@16, green 8@8, blue 8@0) */
            /* i_pixel_pitch = 4; */
            i_rlength = 8;
            i_roffset = 16;
            i_glength = 8;
            i_goffset = 8;
            i_blength = 8;
            i_boffset = 0;
            p_vout->output.i_chroma = VLC_FOURCC('R','V','3','2');
            break;

        default:
            msg_Err( p_vout, "unknown screen depth %i",
                     p_sys->p_pixel_format );
            return VLC_EGENERIC;
    }
    /* Set the RGB masks */
    p_vout->output.i_rmask = ( (1 << i_rlength) - 1 ) << i_roffset;
    p_vout->output.i_gmask = ( (1 << i_glength) - 1 ) << i_goffset;
    p_vout->output.i_bmask = ( (1 << i_blength) - 1 ) << i_boffset;

    /* Width and height */
    p_vout->output.i_width  = p_sys->i_width;
    p_vout->output.i_height = p_sys->i_height;

    /* The aspect */
    p_vout->output.i_aspect = (p_sys->i_width * VOUT_ASPECT_FACTOR) /
                               p_sys->i_height;

    /* Try to initialize 1 buffer */
    /* Find an empty picture slot */
    for( i_index = 0 ; i_index < VOUT_MAX_PICTURES ; i_index++ )
    {
        if( p_vout->p_picture[ i_index ].i_status == FREE_PICTURE )
        {
            p_pic = p_vout->p_picture + i_index;
            break;
        }
    }

    /* Allocate the picture */
    if( !p_pic )
        return VLC_EGENERIC;

    /* get the pixels */
    if( p_primary->Lock( p_primary, DSLF_READ, (void **) &p_pixels,
                         &i_line_pitch) != DFB_OK )
        return VLC_EGENERIC;

    /* allocate p_pixels */
    i_size = i_line_pitch * p_sys->i_height;
    p_sys->p_pixels = malloc( sizeof(byte_t) * i_size );
    if( p_sys->p_pixels == NULL )
    {
        p_primary->Unlock(p_primary);
        return VLC_ENOMEM;
    }

    /* copy pixels */
    memcpy( p_sys->p_pixels,  p_pixels, i_size );
    if( p_primary->Unlock(p_primary) != DFB_OK )
    {
        return VLC_EGENERIC;
    }

    p_pic->p->p_pixels = p_sys->p_pixels;
    p_pic->p->i_pixel_pitch = i_line_pitch / p_sys->i_width;
    p_pic->p->i_lines = p_sys->i_height;
    p_pic->p->i_visible_lines = p_sys->i_height;
    p_pic->p->i_pitch = i_line_pitch;
    p_pic->p->i_visible_pitch = i_line_pitch;
    p_pic->i_planes = 1;
    p_pic->i_status = DESTROYED_PICTURE;
    p_pic->i_type   = DIRECT_PICTURE;

    PP_OUTPUTPICTURE[ I_OUTPUTPICTURES ] = p_pic;

    I_OUTPUTPICTURES++;

    return VLC_SUCCESS;
}
int main(int argc, char const *argv[])
{
        /* Get platform */
        cl_platform_id platform;
        cl_uint num_platforms;
        cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clGetPlatformIDs' failed\n");
                exit(1);
        }
        
        printf("Number of platforms: %d\n", num_platforms);
        printf("platform=%p\n", platform);
        
        /* Get platform name */
        char platform_name[100];
        ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clGetPlatformInfo' failed\n");
                exit(1);
        }
        
        printf("platform.name='%s'\n\n", platform_name);
        
        /* Get device */
        cl_device_id device;
        cl_uint num_devices;
        ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clGetDeviceIDs' failed\n");
                exit(1);
        }
        
        printf("Number of devices: %d\n", num_devices);
        printf("device=%p\n", device);
        
        /* Get device name */
        char device_name[100];
        ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name),
        device_name, NULL);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clGetDeviceInfo' failed\n");
                exit(1);
        }
        
        printf("device.name='%s'\n", device_name);
        printf("\n");
        
        /* Create a Context Object */
        cl_context context;
        context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clCreateContext' failed\n");
                exit(1);
        }
        
        printf("context=%p\n", context);
        
        /* Create a Command Queue Object*/
        cl_command_queue command_queue;
        command_queue = clCreateCommandQueue(context, device, 0, &ret);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clCreateCommandQueue' failed\n");
                exit(1);
        }
        
        printf("command_queue=%p\n", command_queue);
        printf("\n");

        /* Program binary */
        unsigned char *bin;
        size_t bin_len;
        cl_int bin_ret;
        
        /* Read program binary */
        if (argc == 2)
                bin = read_buffer((char *)argv[1], &bin_len);
        else
        {
                printf("error: No binary specified\n");
                exit(1);
        }
        
        /* Create a program */
        cl_program program;
        program = clCreateProgramWithBinary(context, 1, &device, &bin_len, (const unsigned char **)&bin, &bin_ret, &ret);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clCreateProgramWithBinary' failed\n");
                exit(1);
        }
        if (bin_ret != CL_SUCCESS)
        {
                printf("error: Invalid binary for device\n");
                exit(1);
        }
        printf("program=%p\n", program);
        
        /* Free binary */
        free(bin);
        
        printf("program binary loaded\n");
        printf("\n");

        ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
        if (ret != CL_SUCCESS )
        {
                size_t size;
                char *log;

                /* Get log size */
                clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size);

                /* Allocate log and print */
                log = malloc(size);
                clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL);
                printf("error: call to 'clBuildProgram' failed:\n%s\n", log);
                
                /* Free log and exit */
                free(log);
                exit(1);
        }

        printf("program built\n");
        printf("\n");
        
        /* Create a Kernel Object*/
        cl_kernel kernel;
        kernel = clCreateKernel(program, "pre_decrement_ushort4", &ret);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clCreateKernel' failed\n");
                exit(1);
        }
        
        /* Create and allocate host buffers */
        size_t num_elem = 10;
        
        /* Create and init host side src buffer 0 */
        cl_ushort4 *src_0_host_buffer;
        src_0_host_buffer = malloc(num_elem * sizeof(cl_ushort4));
        for (int i = 0; i < num_elem; i++)
                src_0_host_buffer[i] = (cl_ushort4){{2, 2, 2, 2}};
        
        /* Create and init device side src buffer 0 */
        cl_mem src_0_device_buffer;
        src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_ushort4), NULL, &ret);
        if (ret != CL_SUCCESS)
        {
                printf("error: could not create source buffer\n");
                exit(1);
        }        
        ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_ushort4), src_0_host_buffer, 0, NULL, NULL);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clEnqueueWriteBuffer' failed\n");
                exit(1);
        }

        /* Create host dst buffer */
        cl_ushort4 *dst_host_buffer;
        dst_host_buffer = malloc(num_elem * sizeof(cl_ushort4));
        memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_ushort4));

        /* Create device dst buffer */
        cl_mem dst_device_buffer;
        dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_ushort4), NULL, &ret);
        if (ret != CL_SUCCESS)
        {
                printf("error: could not create dst buffer\n");
                exit(1);
        }
        
        /* Set kernel arguments */
        ret = CL_SUCCESS;
        ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer);
        ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &dst_device_buffer);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clSetKernelArg' failed\n");
                exit(1);
        }

        /* Launch the kernel */
        size_t global_work_size = num_elem;
        size_t local_work_size = num_elem;
        ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clEnqueueNDRangeKernel' failed\n");
                exit(1);
        }

        /* Wait for it to finish */
        clFinish(command_queue);

        /* Read results from GPU */
        ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_ushort4), dst_host_buffer, 0, NULL, NULL);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clEnqueueReadBuffer' failed\n");
                exit(1);
        }

        /* Dump dst buffer to file */
        char dump_file[100];
        sprintf((char *)&dump_file, "%s.result", argv[0]);
        write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_ushort4));
        printf("Result dumped to %s\n", dump_file);
        /* Free host dst buffer */
        free(dst_host_buffer);

        /* Free device dst buffer */
        ret = clReleaseMemObject(dst_device_buffer);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clReleaseMemObject' failed\n");
                exit(1);
        }
        
        /* Free host side src buffer 0 */
        free(src_0_host_buffer);

        /* Free device side src buffer 0 */
        ret = clReleaseMemObject(src_0_device_buffer);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clReleaseMemObject' failed\n");
                exit(1);
        }

        /* Release kernel */
        ret = clReleaseKernel(kernel);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clReleaseKernel' failed\n");
                exit(1);
        }

        /* Release program */
        ret = clReleaseProgram(program);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clReleaseProgram' failed\n");
                exit(1);
        }
        
        /* Release command queue */
        ret = clReleaseCommandQueue(command_queue);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clReleaseCommandQueue' failed\n");
                exit(1);
        }
        
        /* Release context */
        ret = clReleaseContext(context);
        if (ret != CL_SUCCESS)
        {
                printf("error: call to 'clReleaseContext' failed\n");
                exit(1);
        }
                
        return 0;
}
char * efcfDecipher(const char * cipher_text, int sequence_mode, char * key, int length){
  char * plainText = (char *)malloc(sizeof(char) * length);
  //Structure to store value for the current number generated.
  union Data {
    unsigned int s;
    char  tempNumber[4];
  } data;

  union Deciph {
    unsigned char decipher;
    int position;
  } deciph;

  deciph.position = 0;
  // Set all the positions to 0
  reinicializaTable();
  // Avoid getting trash
  int i;
  for(i = 0; i< length; i++){
    plainText[i] = '0';
  }
  // Breaks the line at the end
  //cipherText[(length*2)-1] = '\0';
  // Initialize the generator selected by the user
  initializeGenerators(sequence_mode, key);
  // Control variables: plain text, cipher text and number structure
  int iText = 0;
  int iPlainText = 0;
  int iNumber = 1;
  //Know when the table is over
  int count_table = 0 ;
  //Getting the first number.
  data.s = linearCongruentialGenerator(initial);
 // hexdump(data.tempNumber, 4);
  // First signal of the algorithm
  unsigned char signal = data.tempNumber[0];
  //Making the signal position occupied
  table[signal] = '1';
  // Loop to read the plain text
    do{
        if(count_table == 254) {
            iNumber = 0;
            count_table = 0;
            data.s = linearCongruentialGenerator(data.s);
            reinicializaTable();
            signal = data.tempNumber[iNumber];
            iNumber++;
            table[signal] = '1';
          }

      // Only leaves this while when the plain text is ciphered
      do {
        //Checks if a new number is needed
        if(iNumber % 4 == 0){
          data.s = linearCongruentialGenerator(data.s);
         // hexdump(data.tempNumber, 4);
        }
        deciph.decipher = cipher_text[iText] ^ data.tempNumber[iNumber % 4];
        if((unsigned char)cipher_text[iText] == signal) {
          // Conflict
            iNumber = 0;
            data.s = linearCongruentialGenerator(data.s);
            iText++;
            int jump = cipher_text[iText] ^ data.tempNumber[iNumber % 4];
            int i = 1;
            for (; i < jump; i++){
             iNumber++;
              if(iNumber % 4 == 0){
                data.s = linearCongruentialGenerator(data.s);
              }
            }
            //Get the deciphered text
            iText++;
            plainText[iPlainText] = cipher_text[iText] ^ data.tempNumber[iNumber % 4];
            iPlainText++;
            count_table++;
            iNumber++;
            iText++;
            break;
        }else {
          plainText[iPlainText] = cipher_text[iText] ^ data.tempNumber[iNumber % 4];
          iPlainText++;
          count_table++;
          iNumber++;
          iText++;
          break;
        }
        
      }while(true);
    }while(iText <= length);

 // hexdump(plainText, length*2);

  return plainText;
}
Exemple #23
0
/*
   InputParser_SeperateWords..
   Seperates words in c string (inpt) to tokens using delimiters set-up at structure ipc and keeps result at structure ipc
   if the c string will be erased before getting back the tokens you can set the keepcopy byte to 1 , this will allocate memory to
   keep a copy of the string..!
   the number returned is the total of tokens extracted!
*/
int InputParser_SeperateWords(struct InputParserC * ipc,char * inpt,char keepcopy)
{

   if (keepcopy==0)
    {
      #if WARN_ABOUT_INCORRECTLY_ALLOCATED_STACK_STRINGS
       if (warningsAboutIncorrectlyAllocatedStackIssued==0)
        {
         fprintf(stderr,"Please note that feeding input parser with strings allocated on the stack it is generally a good idea to enable keepcopy\n");
         fprintf(stderr,"For example passing here a string allocated as  char* hello = \"hello!\"; might lead to a segFault ( i.e. when calling InputParser_GetWordFloat ) \n");
         fprintf(stderr,"The correct way for allocating a string with in place processing is char hello[] = \"hello!\"; \n");
         fprintf(stderr,"Valgrind classifies these errors as \"Bad permissions for mapped region at address\" \n");
         ++warningsAboutIncorrectlyAllocatedStackIssued ;
        }
       #endif


    }





  if (CheckIPCOk(ipc)==0) { return 0; }
  if  ( inpt == 0 ) return 0; /* NULL INPUT -> NULL OUTPUT*/

  unsigned int   STRING_END = strlen(inpt) ;
  int WORDS_SEPERATED = 0 , NEXT_SHOULD_NOT_BE_A_DELIMITER=1 , FOUND_DELIMETER ; /* Ignores starting ,,,,,string,etc*/

  if ( STRING_END == 0 ) { return 0; } /* NULL INPUT -> NULL OUTPUT pt 2*/

  /* >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
   COPY STRING ( OR POINTER ) TO IPC STRUCTURE*/
  if ( keepcopy == 1 ) {  /* IF WE HAVE ALREADY ALLOCATED A STRING TO ipc->str , we should free it to prevent memory leaks!*/
                          if (ipc->local_allocation == 1)
                          {
                            if (ipc->str!=0)
                            { /* ipc->str contains a previous value!*/
                              free(ipc->str);
                              ipc->local_allocation = 0;
                            }
                          }
                          ipc->str = (char * ) malloc( sizeof(char) * (STRING_END+1) );
                          ipc->local_allocation = 1;
                          strncpy( ipc->str , inpt , STRING_END ) ;
                       } else
                       { ipc->str = inpt; }

  ipc->str_length = STRING_END;
  /* COPY STRING ( OR POINTER ) TO IPC STRUCTURE
   >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/


  register unsigned int i,z;
  ipc->tokens_count = 0 , ipc->tokenlist[0].token_start=0;
  for (i=0; i<STRING_END; i++)
  {
    FOUND_DELIMETER = 0;
    for (z=0; z<ipc->cur_delimeter_count; z++)
    {

    if ( inpt[i] == ipc->delimeters[z] )
      {
        FOUND_DELIMETER = 1;
        if (NEXT_SHOULD_NOT_BE_A_DELIMITER==0)
        {
         ipc->tokenlist[ipc->tokens_count].length = i - ipc->tokenlist[ipc->tokens_count].token_start;
         ipc->tokens_count+=1;
         ipc->tokenlist[ipc->tokens_count].token_start = i+1;
         WORDS_SEPERATED+=1;
         break;
        } else
        {
          ipc->tokenlist[ipc->tokens_count].token_start=i+1;
        }
      }
    }

    if (FOUND_DELIMETER == 0 ) NEXT_SHOULD_NOT_BE_A_DELIMITER=0; else
    if (FOUND_DELIMETER == 1 ) NEXT_SHOULD_NOT_BE_A_DELIMITER=1;

  }

   if (NEXT_SHOULD_NOT_BE_A_DELIMITER==0)
        {
         ipc->tokenlist[ipc->tokens_count].length = i - ipc->tokenlist[ipc->tokens_count].token_start;
         ipc->tokens_count+=1;
         ipc->tokenlist[ipc->tokens_count].token_start = i+1;
         WORDS_SEPERATED+=1;

        } else
  ipc->tokenlist[ipc->tokens_count].length = i - ipc->tokenlist[ipc->tokens_count].token_start;

  return WORDS_SEPERATED;
}
char * efcfCipher(const char * plain_text, int sequence_mode, char * key, size_t length){
  //Structure to store value for the current number generated.
  union Data {
    unsigned int s;
    char  tempNumber[4];
  } data;

  union Ciph {
    unsigned char cipher;
    int position;
  } ciph;

  ciph.position = 0;
  // Set all the positions to 0
  reinicializaTable();
  //Cipher text that will be produced
  char * cipherText = (char *)malloc(sizeof(char)* 50000);
  // Avoid getting trash
  int i;
  for(i = 0; i< 50000; i++){
    cipherText[i] = '0';
  }
  // Breaks the line at the end
  //cipherText[(length*2)-1] = '\0';
  // Initialize the generator selected by the user
  initializeGenerators(sequence_mode, key);
  // Control variables: plain text, cipher text and number structure
  int iText;
  int iCipherText = 0;
  int iNumber = 1;
  //Know when the table is over
  int count_table = 0 ;
  //Getting the first number.
  data.s = linearCongruentialGenerator(initial);
  //hexdump(data.tempNumber, 4);
  // First signal of the algorithm
  unsigned char signal = data.tempNumber[0];
  //Making the signal position occupied
  hexdump(data.tempNumber, 1);
  table[signal] = '1';
  hexdump(table, 256);
  // Loop to read the plain text
    do{
      if(count_table == 254) {
          count_table = 0;
          data.s = linearCongruentialGenerator(data.s);
          reinicializaTable();
          iNumber++;
          signal = data.tempNumber[iNumber % 4];
          table[signal] = '1';
        }
      // Only leaves this while when the plain text is ciphered
      do {
        //Checks if a new number is needed
        if(iNumber % 4 == 0){
          data.s = linearCongruentialGenerator(data.s);
          //hexdump(data.tempNumber, 4);
        }
        if(j == 255){
          
        }
        ciph.cipher = plain_text[iText] ^ data.tempNumber[iNumber % 4];
        if(table[ciph.position] == '0') {
          // Its a new position
            if(j == 0) {
              //Without a conflict
              cipherText[iCipherText] = ciph.cipher;
            }else {
              //With conflict
              cipherText[iCipherText] = s_old ^ j;
              iCipherText++;
              cipherText[iCipherText] = data.tempNumber[iNumber % 4] ^ plain_text[iText];
              j = 0;
            }
            table[ciph.position] = '1';
            count_table++;
            iCipherText++;
            iNumber++;
            iText++;
            break;
        }else if(table[ciph.position] == '1'){
          //Its not a new position
          if(j == 0) {
            // Its the first conflict
            cipherText[iCipherText] = signal;
            iNumber = 0;
            data.s = linearCongruentialGenerator(data.s);
            s_old = data.tempNumber[(iNumber % 4)];
            j = j + 2;
            iCipherText++;
            iNumber++;
          }else{
            j = j + 1;
            iNumber++;
          }
        }
        

      }while(true);
    }while(iText <= length);

  size_final = iCipherText;
  hexdump(cipherText, length*2);
  return cipherText;
}
void * malloc_new(size_t size)
{
    return malloc(size);
}
struct gameState* newGame() {
  struct gameState* g = malloc(sizeof(struct gameState));
  return g;
}
Exemple #27
0
LPCH MergeEnvironmentStrings(PCSTR original, PCSTR merge)
{

	const char * cp;
	char* p;
	int offset;
	int length;
	const char* envp;
	DWORD cchEnvironmentBlock;
	LPCH lpszEnvironmentBlock;
	const char **mergeStrings;
	int mergeStringLenth;
	int mergeArraySize = 128;
	int run;
	int mergeLength;
	int foundMerge;
	char * foundEquals;
	// first build an char ** of the merge env strings

	mergeStrings = (LPCSTR*) malloc(mergeArraySize * sizeof(char *));
	mergeStringLenth = 0;

	cp = merge;
	while( *cp && *(cp+1)) {
		length = strlen(cp);
		if (mergeStringLenth == mergeArraySize ) {
			mergeArraySize += 128;
			mergeStrings = (LPCSTR*) realloc(mergeStrings, mergeArraySize * sizeof(char *));

		}
		mergeStrings[mergeStringLenth] = cp;
		cp += length + 1;
		mergeStringLenth++;
	}

	offset = 0;

	cchEnvironmentBlock = 128;
	lpszEnvironmentBlock = (LPCH) malloc(cchEnvironmentBlock * sizeof(CHAR));

	envp  = original;

	while ((original != NULL) && (*envp && *(envp+1)))
	{
		length = strlen(envp);

		while ((offset + length + 8) > cchEnvironmentBlock)
		{
			cchEnvironmentBlock *= 2;
			lpszEnvironmentBlock = (LPCH) realloc(lpszEnvironmentBlock, cchEnvironmentBlock * sizeof(CHAR));
		}

		p = &(lpszEnvironmentBlock[offset]);

		// check if this value is in the mergeStrings
		foundMerge = 0;
		for (run = 0; run < mergeStringLenth; run ++) {
			if (mergeStrings[run] == NULL) {
				continue;
			}
			mergeLength =strlen(mergeStrings[run]);
			foundEquals = strstr(mergeStrings[run],"=");
			if (foundEquals == NULL) {
				continue;
			}
#ifdef _WIN32
			if (strnicmp(envp,mergeStrings[run],foundEquals - mergeStrings[run] + 1) == 0) {
#else
			if (strncmp(envp,mergeStrings[run],foundEquals - mergeStrings[run] + 1) == 0) {
#endif
				// found variable in merge list ... use this ....
				if (*(foundEquals + 1) == '\0') {
					// check if the argument is set ... if not remove variable ...
					foundMerge = 1;
				} else {

					while ((offset + mergeLength + 8) > cchEnvironmentBlock)
					{
						cchEnvironmentBlock *= 2;
						lpszEnvironmentBlock = (LPCH) realloc(lpszEnvironmentBlock, cchEnvironmentBlock * sizeof(CHAR));
					}
					foundMerge = 1;
					CopyMemory(p, mergeStrings[run], mergeLength);
					mergeStrings[run] = NULL;
					p[mergeLength] = '\0';
					offset += (mergeLength + 1);
				}
			}
		}


		if (foundMerge == 0) {
			CopyMemory(p, envp, length * sizeof(CHAR));
			p[length] = '\0';
			offset += (length + 1);
		}
		envp += (length +1);
	}

	// now merge the not already merged env
	for (run = 0; run < mergeStringLenth; run ++) {
		if (mergeStrings[run] == NULL) {
			continue;
		}

		mergeLength =strlen(mergeStrings[run]);

		while ((offset + mergeLength + 8) > cchEnvironmentBlock)
		{
			cchEnvironmentBlock *= 2;
			lpszEnvironmentBlock = (LPCH) realloc(lpszEnvironmentBlock, cchEnvironmentBlock * sizeof(CHAR));
		}

		p = &(lpszEnvironmentBlock[offset]);

		CopyMemory(p, mergeStrings[run], mergeLength);
		mergeStrings[run] = NULL;
		p[mergeLength] = '\0';
		offset += (mergeLength + 1);
	}


	lpszEnvironmentBlock[offset] = '\0';

	free(mergeStrings);

	return lpszEnvironmentBlock;
}


LPWCH GetEnvironmentStringsW(VOID)
{
	return NULL;
}

BOOL SetEnvironmentStringsA(LPCH NewEnvironment)
{
	return TRUE;
}

BOOL SetEnvironmentStringsW(LPWCH NewEnvironment)
{
	return TRUE;
}

DWORD ExpandEnvironmentStringsA(LPCSTR lpSrc, LPSTR lpDst, DWORD nSize)
{
	return 0;
}

DWORD ExpandEnvironmentStringsW(LPCWSTR lpSrc, LPWSTR lpDst, DWORD nSize)
{
	return 0;
}

BOOL FreeEnvironmentStringsA(LPCH lpszEnvironmentBlock)
{
	if (lpszEnvironmentBlock)
		free(lpszEnvironmentBlock);

	return TRUE;
}

BOOL FreeEnvironmentStringsW(LPWCH lpszEnvironmentBlock)
{
	return TRUE;
}
Exemple #28
0
void * operator new(size_t size)
{
    return malloc(size);
}
Exemple #29
0
void io_init(bool term_ctrl)
{
	static readonly unsigned char open_params_list[2] =
	{
		(unsigned char)iop_newversion,
		(unsigned char)iop_eol
	};
	static readonly unsigned char null_params_list[2] =
	{
		(unsigned char)iop_nl,
		(unsigned char)iop_eol
	};
	static readonly unsigned char	no_params = (unsigned char)iop_eol;
	static readonly unsigned char	shr_params[3] =
	{
		(unsigned char)iop_shared,
		(unsigned char)iop_readonly,
		(unsigned char)iop_eol
	};

	int4		status;
        mval    	val;
	mstr		tn;
 	MSTR_CONST	(gtm_netout, "GTM_NETOUT");
 	MSTR_CONST	(sys_net, "SYS$NET");
	char		buf1[MAX_TRANS_NAME_LEN]; /* buffer to hold translated name */
	mval		pars;
	io_log_name	*inp, *outp;
	io_log_name	*ln;

	error_def(ERR_LOGTOOLONG);

	io_init_name();
	/* default logical names */
	io_root_log_name = (io_log_name *)malloc(SIZEOF(*io_root_log_name));
	memset(io_root_log_name, 0, SIZEOF(*io_root_log_name));
	val.mvtype = MV_STR;
	val.str.addr = "0";
	val.str.len = 1;
	ln = get_log_name(&val.str, INSERT);
	assert(ln != 0);
	val.str = gtm_principal;
	status = TRANS_LOG_NAME(&val.str, &tn, buf1, SIZEOF(buf1), dont_sendmsg_on_log2long);
	if (SS_NOLOGNAM == status)
		dollar_principal = 0;
	else if (SS_NORMAL == status)
		dollar_principal = get_log_name(&tn, INSERT);
#	ifdef UNIX
	else if (SS_LOG2LONG == status)
		rts_error(VARLSTCNT(5) ERR_LOGTOOLONG, 3, val.str.len, val.str.addr, SIZEOF(buf1) - 1);
#	endif
	else
		rts_error(VARLSTCNT(1) status);

	/* open devices */
	val.str = sys_input;
	inp = get_log_name(&val.str, INSERT);
	pars.mvtype = MV_STR;
	status = TRANS_LOG_NAME(&val.str, &tn, buf1, SIZEOF(buf1), dont_sendmsg_on_log2long);
	if (SS_NOLOGNAM == status)
	{
		pars.str.len = SIZEOF(null_params_list);
		pars.str.addr = (char *)null_params_list;
	} else if (SS_NORMAL == status)
	{
		if (!io_is_rm(&val.str))
		{
			pars.str.len = SIZEOF(no_params);
			pars.str.addr = (char *)&no_params;
		} else  if (io_is_sn(&val.str))
		{
			pars.str.len = SIZEOF(open_params_list);
			pars.str.addr = (char *)open_params_list;
		} else
		{
			pars.str.len = SIZEOF(shr_params);
			pars.str.addr = (char *)shr_params;
		}
	}
#	ifdef UNIX
	else if (SS_LOG2LONG == status)
		rts_error(VARLSTCNT(5) ERR_LOGTOOLONG, 3, val.str.len, val.str.addr, SIZEOF(buf1) - 1);
#	endif
	else
		rts_error(VARLSTCNT(1) status);
	ESTABLISH(io_init_ch);
	(*op_open_ptr)(&val, &pars, 0, 0);
	io_curr_device.in  = io_std_device.in  = inp->iod;
	val.str = sys_output;
	if ((SS_NORMAL == TRANS_LOG_NAME(&gtm_netout, &tn, buf1, SIZEOF(buf1), do_sendmsg_on_log2long))
			&& (SS_NORMAL == TRANS_LOG_NAME(&sys_net, &tn, buf1, SIZEOF(buf1), do_sendmsg_on_log2long))
			&& io_is_sn(&sys_net))
		val.str = sys_net;
	outp = get_log_name(&val.str, INSERT);
	status = TRANS_LOG_NAME(&val.str, &tn, buf1, SIZEOF(buf1), dont_sendmsg_on_log2long);
	if ((SS_NORMAL != status) && (SS_NOLOGNAM != status))
	{
#		ifdef UNIX
		if (SS_LOG2LONG == status)
			rts_error(VARLSTCNT(5) ERR_LOGTOOLONG, 3, val.str.len, val.str.addr, SIZEOF(buf1) - 1);
		else
#		endif
			rts_error(VARLSTCNT(1) status);
	}
	if ((val.str.addr == sys_net.addr) && (pars.str.addr == (char *)open_params_list))
		/* sys$net is the only input thing that uses open_params_list */
		outp->iod = io_curr_device.in;
	/* For terminals and mailboxes and sockets, SYS$INPUT and SYS$OUTPUT may point to
		the same device.  If input is one of those, then check translated
		name for output against translated name for input;
		in that case they should be joined by their logical names */
	if (((tt == io_curr_device.in->type) || (mb == io_curr_device.in->type) ||
		(gtmsocket == io_curr_device.in->type))
		&& same_device_check(tn, buf1))
		outp->iod = io_curr_device.in;
	if (!outp->iod)
	{
		if (status == SS_NOLOGNAM)
		{
			pars.str.len = SIZEOF(null_params_list);
			pars.str.addr = (char *)null_params_list;
		} else  if (status == SS_NORMAL)
		{
			pars.str.len = SIZEOF(open_params_list);
			pars.str.addr = (char *)open_params_list;
		}
		(*op_open_ptr)(&val, &pars, 0, 0);
	}
	io_curr_device.out = io_std_device.out = outp->iod;
	term_setup(term_ctrl);
	io_std_device.out->pair = io_std_device;
	io_std_device.in->pair = io_std_device;
	io_std_device.out->perm = io_std_device.in->perm = TRUE;
	for (ln = io_root_log_name;  ln;  ln = ln->next)
		ln->iod = io_std_device.in;

	if (dollar_principal)
		dollar_principal->iod = io_std_device.in;
	pars.str.len = SIZEOF(no_params);
	pars.str.addr = (char *)&no_params;
	val.str.len = io_curr_device.in->trans_name->len;
	val.str.addr = io_std_device.in->trans_name->dollar_io;
	op_use(&val, &pars);
	REVERT;
	return;
}
int getAllInterfacesAndAddresses (JNIEnv *env, netif **netifPP)
{
    DWORD ret;
    IP_ADAPTER_ADDRESSES *ptr, *adapters=0;
    ULONG len=ipinflen, count=0;
    netif *nif=0, *dup_nif, *last=0, *loopif=0, *curr;
    int tun=0, net=0;

    *netifPP = 0;

   /*
    * Get the IPv4 interfaces. This information is the same
    * as what previous JDK versions would return.
    */

    ret = enumInterfaces(env, netifPP);
    if (ret == -1) {
        return -1;
    } else {
        count = ret;
    }

    /* locate the loopback (and the last) interface */
    for (nif=*netifPP, last=nif; nif!=0; nif=nif->next) {
        if (nif->ifType == MIB_IF_TYPE_LOOPBACK) {
            loopif = nif;
        }
        last = nif;
    }

    // Retrieve IPv4 addresses with the IP Helper API
    curr = *netifPP;
    while (curr != NULL) {
        netaddr *netaddrP;
        ret = enumAddresses_win(env, curr, &netaddrP);
        if (ret == -1) {
            return -1;
        }
        curr->addrs = netaddrP;
        curr->naddrs += ret;
        curr = curr->next;
    }

    ret = getAdapters (env, &adapters);
    if (ret != ERROR_SUCCESS) {
        goto err;
    }

    /* Now get the IPv6 information. This includes:
     *  (a)  IPv6 information associated with interfaces already found
     *  (b)  IPv6 information for IPv6 only interfaces (probably tunnels)
     *
     * For compatibility with previous releases we use the naming
     * information gotten from enumInterfaces() for (a) entries
     * However, the index numbers are taken from the new API.
     *
     * The procedure is to go through the list of adapters returned
     * by the new API looking for entries that correspond to IPv4 interfaces
     * already found.
     */

    ptr = adapters;
    while (ptr != NULL) {
        int c;
        netif *nif0;
        if (ptr->IfType == IF_TYPE_SOFTWARE_LOOPBACK && (loopif != NULL)) {
            c = getAddrsFromAdapter(ptr, &loopif->addrs);
            if (c == -1) {
                goto err;
            }
            loopif->naddrs += c;
        } else {
            int index = ptr->IfIndex;
            if (index != 0) {
                /* This entry is associated with an IPv4 interface */
                for (nif=*netifPP; nif!=0; nif=nif->next) {
                    if (nif->index == index) {
                        /* found the interface entry
                         * set the index to the IPv6 index and add the
                         * IPv6 addresses
                         */
                        nif->ipv6Index = ptr->Ipv6IfIndex;
                        c = getAddrsFromAdapter(ptr, &nif->addrs);
                        nif->naddrs += c;
                        break;
                    }
                }
            } else {
                /* This entry is IPv6 only */
                char newname [128];
                int c;

                /* Windows allocates duplicate adapter entries
                 * for tunnel interfaces when there are multiple
                 * physical adapters. Need to check
                 * if this is a duplicate (ipv6Index is the same)
                 */
                dup_nif = 0;
                for (nif0=*netifPP; nif0!=0; nif0=nif0->next) {
                    if (nif0->hasIpv6Address &&
                                ptr->Ipv6IfIndex == nif0->ipv6Index) {
                        dup_nif = nif0;
                        break;
                    }
                }
                if (dup_nif == 0) {
                    /* new interface */
                    nif = (netif *) calloc (1, sizeof(netif));
                    if (nif == 0) {
                        goto err;
                    }
                    if (ptr->IfType == IF_TYPE_TUNNEL) {
                        sprintf (newname, "tun%d", tun);
                        tun ++;
                    } else {
                        sprintf (newname, "net%d", net);
                        net ++;
                    }
                    nif->name = malloc (strlen(newname)+1);
                    nif->displayName = malloc (wcslen(ptr->FriendlyName)*2+2);
                    if (nif->name == 0 || nif->displayName == 0) {
                        goto err;
                    }
                    strcpy (nif->name, newname);
                    wcscpy ((PWCHAR)nif->displayName, ptr->FriendlyName);
                    nif->dNameIsUnicode = TRUE;

                    // the java.net.NetworkInterface abstraction only has index
                    // so the Ipv6IfIndex needs to map onto index
                    nif->index = ptr->Ipv6IfIndex;
                    nif->ipv6Index = ptr->Ipv6IfIndex;
                    nif->hasIpv6Address = TRUE;

                    last->next = nif;
                    last = nif;
                    count++;
                    c = getAddrsFromAdapter(ptr, &nif->addrs);
                    if (c == -1) {
                        goto err;
                    }
                    nif->naddrs += c;
                } else {
                    /* add the addresses from this adapter to the
                     * original (dup_nif)
                     */
                    c = getAddrsFromAdapter(ptr, &dup_nif->addrs);
                    if (c == -1) {
                        goto err;
                    }
                    dup_nif->naddrs += c;
                }
            }
        }
        ptr=ptr->Next;
    }

    free (adapters);
    return count;

err:
    if (*netifPP) {
        free_netif (*netifPP);
    }
    if (adapters) {
        free (adapters);
    }
    return -1;
}