示例#1
0
int main (
    int     argc,
    char    *argv [])
{
    char    *fname = "/etc/apache2/conf.d/php.conf.yaml";
    FILE    *fh;

    if (argc > 1)
        fname = argv [1];

    fh = fopen(fname, "r");

    printf ("Openned :%s:\n", fname);

    yaml_parser_t parser;
    yaml_token_t  token;   /* New variable */

    /* Initialize parser */
    if(!yaml_parser_initialize(&parser))
        fputs("Failed to initialize parser!\n", stderr);
    if(fh == NULL)
        fputs("Failed to open file!\n", stderr);

    /* Set input file */
    yaml_parser_set_input_file(&parser, fh);

    /* START new code */
    do {
        yaml_parser_scan(&parser, &token);
        switch(token.type)
        {
        /* Stream start/end */
        case YAML_STREAM_START_TOKEN:
            puts("STREAM START");
            break;
        case YAML_STREAM_END_TOKEN:
            puts("STREAM END");
            break;
        /* Token types (read before actual token) */
        case YAML_KEY_TOKEN:
            printf("(Key token)   ");
            break;
        case YAML_VALUE_TOKEN:
            printf("(Value token) ");
            break;
        /* Block delimeters */
        case YAML_BLOCK_SEQUENCE_START_TOKEN:
            puts("<b>Start Block (Sequence)</b>");
            break;
        case YAML_BLOCK_ENTRY_TOKEN:
            puts("<b>Start Block (Entry)</b>");
            break;
        case YAML_BLOCK_END_TOKEN:
            puts("<b>End block</b>");
            break;
        /* Data */
        case YAML_BLOCK_MAPPING_START_TOKEN:
            puts("[Block mapping]");
            break;
        case YAML_SCALAR_TOKEN:
            printf("scalar %s \n", token.data.scalar.value);
            break;
        /* Others */
        default:
            printf("Got token of type %d\n", token.type);
        }

        if(token.type != YAML_STREAM_END_TOKEN)
            yaml_token_delete(&token);
    } while (token.type != YAML_STREAM_END_TOKEN);

    yaml_token_delete(&token);
    /* END new code */

    /* Cleanup */
    yaml_parser_delete(&parser);
    fclose(fh);

    return 0;
}
示例#2
0
int main(void) {
	puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
	return EXIT_SUCCESS;
}
示例#3
0
int main(int argc, char **argv)
{
	int sock;
	int msg_size;
	char name[SIZE_STR];
	char path[SIZE_BUF];
	char author[SIZE_STR];
	char buffer[SIZE_BUF];
	char command[SIZE_CMD];
	char content[SIZE_CONTENT];

	ValidateArgs(argc, argv);

	if (interface)
	{
		client.sin_addr.s_addr = inet_addr(szAddress);
		if (client.sin_addr.s_addr == INADDR_NONE)
			usage();
	}
	else
		client.sin_addr.s_addr = htonl(INADDR_ANY);
	client.sin_family = AF_INET;
	client.sin_port = htons(port);
	int len = sizeof(client);

	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		perror("Socket is not created");
		exit(1);
	}

	bzero(buffer, sizeof(buffer));
	while(strcmp(buffer, ":start"))
	{

		fgets(buffer, sizeof(buffer), stdin);
		if (buffer[strlen(buffer) - 1] == '\n')
			buffer[strlen(buffer) - 1] = '\0';
		if ((msg_size = sendto(sock, buffer, strlen(buffer), 0, (struct sockaddr *)&client, sizeof(client))) < 0)
		{
			perror("SEND start message failed");
			exit(1);
		}
	}
	//printf("SEND  [%d bytes]: start message '%s'\n", msg_size, buffer);

	bzero(buffer, sizeof(buffer));
	if ((msg_size = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0)
	{
		perror("RECV directory content failed");
		exit(1);
	}
	//printf("RECV  [%d bytes]: directory content\n", msg_size);
	output(buffer);
	send_report(sock, SUCCESS);

	while(1)
	{
		bzero(path, sizeof(path));
		if ((msg_size = recvfrom(sock, path, sizeof(path), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0)
		{
			perror("RECV current path failed");
			exit(1);
		}
		//printf("RECV  [%d bytes]: current path '%s'\n", msg_size, path);

		send_report(sock, SUCCESS);

		bzero(buffer, sizeof(buffer));
		if ((msg_size = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0)
		{
			perror("RECV invitation message failed");
			exit(1);
		}
		//printf("RECV  [%d bytes]: invitation message\n", msg_size);
		output(buffer);
		char space;
		bzero(name, sizeof(name));
		bzero(buffer, sizeof(buffer));
		bzero(author, sizeof(author));
		bzero(command, sizeof(command));
		bzero(content, sizeof(content));
		scanf("%5s%1c", command, &space);
		if ((msg_size = sendto(sock, command, strlen(command), 0, (struct sockaddr *)&client, sizeof(client))) < 0)
		{
			perror("SEND command failed");
			exit(1);
		}
		//printf("SEND  [%d bytes]: command '%s'\n", msg_size, path);

		if (!strcmp(command, ":exit"))
		{
			bzero(buffer, sizeof(buffer));
			if ((msg_size = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0)	// Receive the content of file
			{
				perror("RECV file or directory content failed");
				exit(1);
			}
			//printf("RECV  [%d bytes]: file or directory content\n", msg_size);
			output(buffer);
			break;
		}

		if (recv_report(sock) < 0)
		{
			puts("!No such command");
			send_report(sock, SUCCESS);
		}

		if (!strcmp(command, "add"))
		{
			char str[SIZE_ARG];
			fgets(name, sizeof(name), stdin);
			if (name[strlen(name) - 1] == '\n')
				name[strlen(name) - 1] = '\0';
			if ((msg_size = sendto(sock, name, strlen(name), 0, (struct sockaddr *)&client, sizeof(client))) < 0)
			{
				perror("SEND command failed");
				exit(1);
			}
			//printf("SEND  [%d bytes]: title of article '%s'\n", msg_size, name);
			if (recv_report(sock) < 0)
			{
				puts("!Such file already exist");
				send_report(sock, SUCCESS);
			}
			else
			{
				int length = sizeof(content) - sizeof(author) - sizeof(name);
				printf("Input author: ");
				fgets(author, sizeof(author), stdin);
				if (author[strlen(author) - 1] == '\n')
					author[strlen(author) - 1] = '\0';
				printf("name's read: %s [%d bytes]\n", name, msg_size);
				printf("author's read: %s [%d bytes]\n", author, msg_size);

				puts("Put content:");
				printf("[%d of %d]  ", (strlen(content)+strlen(str)), length);
				while (fgets(str, sizeof(str), stdin) != NULL)
				{
					if (!strncmp(":end", str, strlen(":end")))
						break;
					if ((strlen(content)+strlen(str)) > length)
					{
						puts("!Text size will not allow. Type less or :end");
						bzero(str, strlen(str));
						printf("[%d of %d]  ", (strlen(content)+strlen(str)), length);
						//__fpurge(stdin);
					}
					strcat(content, str);
					bzero(str, strlen(str));
				}
				if ((msg_size = sendto(sock, author, strlen(author), 0, (struct sockaddr *)&client, sizeof(client))) < 0)
				{
					perror("SEND author of article failed");
					exit(1);
				}
				//printf("SEND  [%d bytes]: author of article '%s'\n", msg_size, author);
				recv_report(sock);

				if ((msg_size = sendto(sock, content, strlen(content), 0, (struct sockaddr *)&client, sizeof(client))) < 0)
				{
					perror("SEND file content failed");
					exit(1);
				}
				//printf("SEND  [%d bytes]: file content '%s'\n", msg_size, content);
				if (recv_report(sock) < 0)
					puts("!Such file already exist");
				send_report(sock, SUCCESS);
			}
		}

		gets(buffer);
		if (!strcmp(command, "open"))
		{
			strcat(path, buffer);
			if ((msg_size = sendto(sock, path, strlen(path), 0, (struct sockaddr *)&client, sizeof(client))) < 0)
			{
				perror("SEND full path to file failed");
				exit(1);
			}
			printf("SEND  [%d bytes]: full path to file '%s'\n", msg_size, path);
		}
		else if (!strcmp(command, "find"))
		{
			if ((msg_size = sendto(sock, buffer, strlen(buffer), 0, (struct sockaddr *)&client, sizeof(client))) < 0)
			{
				perror("SEND author to find failed");
				exit(1);
			}
			//printf("SEND  [%d bytes]: author to find '%s'\n", msg_size, buffer);
		}

		bzero(content, sizeof(content));
		if ((msg_size = recvfrom(sock, content, sizeof(content), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0)	// Receive the content of file
		{
			perror("RECV file or directory content failed");
			exit(1);
		}
		//printf("RECV  [%d bytes]: file or directory content\n", msg_size);
		output(content);
		send_report(sock, SUCCESS);
	}
	recv_msg(sock, content, sizeof(content), 0, (struct sockaddr *)&client, (socklen_t *)&len);
	/*int num = 0;
	char *ptr = &content[1];
	char number[2];
	while(1){
		if ((msg_size = recvfrom(sock, content, sizeof(content), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0)	// Receive the content of file
		{
			perror("RECV file or directory content failed");
			exit(1);
		}
		printf("RECV  [%d bytes]: file or directory content\n", msg_size);
		memset(number, 0, sizeof(number));
		strncpy(number, ptr, 2);
		printf("%d    ", atoi(number));
		output(content);
		if (num != atoi(number))
			send_report(sock, UNSUCCESS);
		else
			send_report(sock, SUCCESS);
		num++;
		if (content[0] == '1')
			break;
	}*/
    close(sock);
	return 0;
}
void *threadfunc()
{
	int cnt,cnt1;
	char str[100];
	char copy[100],tmpstr[100],tmpfinal[100];
	int z;int i;
	char restartFile[100],rstart[100];
	int pos;
	char processID[100],check[400],context[100];
	FILE *fp;
	while(1)
	{
		if(read(sockdes,buff,sizeof(buff)))
		{
			puts(buff);
			if(!strcmp(buff,"CP"))
			{
				FILE *procs;
				procs = popen("ps -e -o pid,cmd","r");
				fscanf(procs,"%s",processID);
				fgets(str,100,procs);

				while(!feof(procs))
				{
					fscanf(procs,"%s",processID);
					fgets(str,100,procs);

					
					if(strstr(str,"a.out")!=NULL)
					{
						sprintf(str,"cr_checkpoint --save-all --kill %s",processID);
						strcpy(tmpstr,"/home/cse4119/context_files/bal/context.");
						strcat(tmpstr,processID);
						printf("\nHere\n");
						for(cnt=0;strcmp(tmpstr,processIDs[cnt])!=0;cnt++)
						{
						//	printf("\n%s --> %s",processIDs[cnt],tmpstr);
						}
						printf("\nHere\n");
						for(cnt1=(cnt+1);cnt1<noOfProcess;cnt1++)
							strcpy(processIDs[cnt1-1],processIDs[cnt1]);
						noOfProcess--;
						strcpy(check,"\0");
						fp=popen(str,"r");
						fgets(check,100,fp);
						fclose(fp);
						
						if(strstr(check,"Checkpoint")!=NULL)
						{
							printf("\nThe selected file could not be checkpointed");
						}
						else
						{
							printf("\nForced Checkpoint due to overload successful\n");
							sprintf(context,"chmod 777 context.%s",processID);
							system(context);
							sprintf(context,"mv context.%s /home/cse4119/context_files/redist/context.%s",processID,processID);
							system(context);
							break;
							
						}
					}
					
				}
				
			}

			else if(strstr(buff,"FAIL")!=NULL)
			{
				for(z=strlen(buff);buff[z]!='/';z--);
					z++;
				pos=0;
				for(;z<=strlen(buff);z++)
					restartFile[pos++]=buff[z];


				printf("\nTo be restarted: %s",restartFile);

				if(strstr(buff,"FAIL")!=NULL)
				{
					for(i=5;i<=strlen(buff);i++)
					{
						rstart[i-5]=buff[i];
					}
				}
							
			//	sprintf(copy,"mv %s %s",rstart,restartFile);
			//	system(copy);
			//	sleep(3);
				printf("&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&&&&&&&&&&&&&&&&&&&\nRESTART\n&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&&&&&&&&&&&&&&&&&&&\n");
				pthread_create(&restartThread,NULL,restartFunc,buff);
				pthread_create(&restartThreadRem,NULL,restartFuncDel,rstart);
			}
			else if(strstr(buff,"context")!=NULL)
			{
				
				sprintf(copy,"mv /home/cse4119/context_files/redist/%s %s",buff,buff);
				system(copy);
				sprintf(tmpfinal,"/home/cse4119/context_files/redist/%s",buff);
			//	printf("&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&&&&&&&&&&&&&&&&&&&\nRESTART\n&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&&&&&&&&&&&&&&&&&&&\n");
				pthread_create(&restartThread,NULL,restartFunc,buff);
				//pthread_create(&restartThreadRem,NULL,restartFuncDel,tmpfinal);
			}
		}
	}
}
int
au_do_update(int idx, long sz)
{
	image_header_t *hdr;
	char *addr;
	long start, end;
	int off, rc;
	uint nbytes;

	hdr = (image_header_t *)LOAD_ADDR;
#if defined(CONFIG_FIT)
	if (genimg_get_format ((void *)hdr) != IMAGE_FORMAT_LEGACY) {
		puts ("Non legacy image format not supported\n");
		return -1;
	}
#endif

	/* disable the power switch */
	*CPLD_VFD_BK |= POWER_OFF;

	/* execute a script */
	if (image_check_type (hdr, IH_TYPE_SCRIPT)) {
		addr = (char *)((char *)hdr + image_get_header_size ());
		/* stick a NULL at the end of the script, otherwise */
		/* parse_string_outer() runs off the end. */
		addr[image_get_data_size (hdr)] = 0;
		addr += 8;
		parse_string_outer(addr, FLAG_PARSE_SEMICOLON);
		return 0;
	}

	start = aufl_layout[FIDX_TO_LIDX(idx)].start;
	end = aufl_layout[FIDX_TO_LIDX(idx)].end;

	/* unprotect the address range */
	/* this assumes that ONLY the firmware is protected! */
	if (idx == IDX_FIRMWARE) {
#undef AU_UPDATE_TEST
#ifdef AU_UPDATE_TEST
		/* erase it where Linux goes */
		start = aufl_layout[1].start;
		end = aufl_layout[1].end;
#endif
		flash_sect_protect(0, start, end);
	}

	/*
	 * erase the address range.
	 */
	debug ("flash_sect_erase(%lx, %lx);\n", start, end);
	flash_sect_erase(start, end);
	wait_ms(100);
	/* strip the header - except for the kernel and ramdisk */
	if (image_check_type (hdr, IH_TYPE_KERNEL) ||
			image_check_type (hdr, IH_TYPE_RAMDISK)) {
		addr = (char *)hdr;
		off = image_get_header_size ();
		nbytes = image_get_image_size (hdr);
	} else {
		addr = (char *)((char *)hdr + image_get_header_size ());
#ifdef AU_UPDATE_TEST
		/* copy it to where Linux goes */
		if (idx == IDX_FIRMWARE)
			start = aufl_layout[1].start;
#endif
		off = 0;
		nbytes = image_get_data_size (hdr);
	}

	/* copy the data from RAM to FLASH */
	debug ("flash_write(%p, %lx %x)\n", addr, start, nbytes);
	rc = flash_write(addr, start, nbytes);
	if (rc != 0) {
		printf("Flashing failed due to error %d\n", rc);
		return -1;
	}

	/* check the dcrc of the copy */
	if (crc32 (0, (uchar *)(start + off), image_get_data_size (hdr)) !=
	    image_get_dcrc (hdr)) {
		printf ("Image %s Bad Data Checksum After COPY\n", aufile[idx]);
		return -1;
	}

	/* protect the address range */
	/* this assumes that ONLY the firmware is protected! */
	if (idx == IDX_FIRMWARE)
		flash_sect_protect(1, start, end);
	return 0;
}
示例#6
0
int					/* O - 1 on success, 0 on error */
translate_messages(cups_array_t *cat,	/* I - Message catalog */
                   const char *lang)	/* I - Output language... */
{
 /*
  * Google provides a simple translation/language tool for translating
  * from one language to another.  It is far from perfect, however it
  * can be used to get a basic translation done or update an existing
  * translation when no other resources are available.
  *
  * Translation requests are sent as HTTP POSTs to
  * "http://translate.google.com/translate_t" with the following form
  * variables:
  *
  *   Name      Description                         Value
  *   --------  ----------------------------------  ----------------
  *   hl        Help language?                      "en"
  *   ie        Input encoding                      "UTF8"
  *   langpair  Language pair                       "en|" + language
  *   oe        Output encoding                     "UTF8"
  *   text      Text to translate                   translation string
  */

  int		ret;			/* Return value */
  _cups_message_t *m;			/* Current message */
  int		tries;			/* Number of tries... */
  http_t	*http;			/* HTTP connection */
  http_status_t	status;			/* Status of POST request */
  char		*idptr,			/* Pointer into msgid */
		buffer[65536],		/* Input/output buffer */
		*bufptr,		/* Pointer into buffer */
		*bufend,		/* Pointer to end of buffer */
		length[16];		/* Content length */
  int		bytes;			/* Number of bytes read */


 /*
  * Connect to translate.google.com...
  */

  puts("Connecting to translate.google.com...");

  if ((http = httpConnect("translate.google.com", 80)) == NULL)
  {
    perror("Unable to connect to translate.google.com");
    return (0);
  }

 /*
  * Scan the current messages, requesting a translation of any untranslated
  * messages...
  */

  for (m = (_cups_message_t *)cupsArrayFirst(cat), ret = 1;
       m;
       m = (_cups_message_t *)cupsArrayNext(cat))
  {
   /*
    * Skip messages that are already translated...
    */

    if (m->str && m->str[0])
      continue;

   /*
    * Encode the form data into the buffer...
    */

    snprintf(buffer, sizeof(buffer),
             "hl=en&ie=UTF8&langpair=en|%s&oe=UTF8&text=", lang);
    bufptr = buffer + strlen(buffer);
    bufend = buffer + sizeof(buffer) - 5;

    for (idptr = m->id; *idptr && bufptr < bufend; idptr ++)
      if (*idptr == ' ')
        *bufptr++ = '+';
      else if (*idptr < ' ' || *idptr == '%')
      {
        sprintf(bufptr, "%%%02X", *idptr & 255);
	bufptr += 3;
      }
      else if (*idptr != '&')
        *bufptr++ = *idptr;

    *bufptr++ = '&';
    *bufptr = '\0';

    sprintf(length, "%d", (int)(bufptr - buffer));

   /*
    * Send the request...
    */

    printf("\"%s\" = ", m->id);
    fflush(stdout);

    tries = 0;

    do
    {
      httpClearFields(http);
      httpSetField(http, HTTP_FIELD_CONTENT_TYPE,
                   "application/x-www-form-urlencoded");
      httpSetField(http, HTTP_FIELD_CONTENT_LENGTH, length);

      if (httpPost(http, "/translate_t"))
      {
	httpReconnect(http);
	httpPost(http, "/translate_t");
      }

      httpWrite2(http, buffer, bufptr - buffer);

      while ((status = httpUpdate(http)) == HTTP_CONTINUE);

      if (status != HTTP_OK && status != HTTP_ERROR)
        httpFlush(http);

      tries ++;
    }
    while (status == HTTP_ERROR && tries < 10);

    if (status == HTTP_OK)
    {
     /*
      * OK, read the translation back...
      */

      bufptr = buffer;
      bufend = buffer + sizeof(buffer) - 1;

      while ((bytes = httpRead2(http, bufptr, bufend - bufptr)) > 0)
        bufptr += bytes;

      if (bytes < 0)
      {
       /*
        * Read error, abort!
	*/

        puts("READ ERROR!");
	ret = 0;
	break;
      }

      *bufptr = '\0';

     /*
      * Find the div containing translation
      */

      if ((bufptr = strstr(buffer, "<div id=result_box")) == NULL)
      {
       /*
        * No textarea, abort!
	*/

        puts("NO div id=result_box!");
	ret = 0;
	break;
      }

      if ((bufptr = strchr(bufptr, '>')) == NULL)
      {
       /*
        * textarea doesn't end, abort!
	*/

        puts("DIV SHORT DATA!");
	ret = 0;
	break;
      }

      bufptr ++;

      if ((bufend = strstr(bufptr, "</div>")) == NULL)
      {
       /*
        * textarea doesn't close, abort!
	*/

        puts("/DIV SHORT DATA!");
	ret = 0;
	break;
      }

      *bufend = '\0';

     /*
      * Copy the translation...
      */

      m->str = strdup(bufptr);

     /*
      * Convert character entities to regular chars...
      */

      for (bufptr = strchr(m->str, '&');
           bufptr;
	   bufptr = strchr(bufptr + 1, '&'))
      {
        if (!strncmp(bufptr, "&lt;", 4))
	{
	  *bufptr = '<';
	  _cups_strcpy(bufptr + 1, bufptr + 4);
	}
        else if (!strncmp(bufptr, "&gt;", 4))
	{
	  *bufptr = '>';
	  _cups_strcpy(bufptr + 1, bufptr + 4);
	}
        else if (!strncmp(bufptr, "&amp;", 5))
	  _cups_strcpy(bufptr + 1, bufptr + 5);
      }

      printf("\"%s\"\n", m->str);
    }
    else if (status == HTTP_ERROR)
    {
      printf("NETWORK ERROR (%s)!\n", strerror(httpError(http)));
      ret = 0;
      break;
    }
    else
    {
      printf("HTTP ERROR %d!\n", status);
      ret = 0;
      break;
    }
  }

  httpClose(http);

  return (ret);
}
示例#7
0
int spi_xfer(struct spi_slave *slave, unsigned int bitlen, const void *dout,
		void *din, unsigned long flags)
{
	volatile spi8xxx_t *spi = &((immap_t *) (CONFIG_SYS_IMMR))->spi;
	unsigned int tmpdout, tmpdin, event;
	int numBlks = bitlen / 32 + (bitlen % 32 ? 1 : 0);
	int tm, isRead = 0;
	unsigned char charSize = 32;

	debug("spi_xfer: slave %u:%u dout %08X din %08X bitlen %u\n",
	      slave->bus, slave->cs, *(uint *) dout, *(uint *) din, bitlen);

	if (flags & SPI_XFER_BEGIN)
		spi_cs_activate(slave);

	spi->event = 0xffffffff;	/* Clear all SPI events */

	/* handle data in 32-bit chunks */
	while (numBlks--) {
		tmpdout = 0;
		charSize = (bitlen >= 32 ? 32 : bitlen);

		/* Shift data so it's msb-justified */
		tmpdout = *(u32 *) dout >> (32 - charSize);

		/* The LEN field of the SPMODE register is set as follows:
		 *
		 * Bit length             setting
		 * len <= 4               3
		 * 4 < len <= 16          len - 1
		 * len > 16               0
		 */

		spi->mode &= ~SPI_MODE_EN;

		if (bitlen <= 16) {
			if (bitlen <= 4)
				spi->mode = (spi->mode & 0xff0fffff) |
				            (3 << 20);
			else
				spi->mode = (spi->mode & 0xff0fffff) |
				            ((bitlen - 1) << 20);
		} else {
			spi->mode = (spi->mode & 0xff0fffff);
			/* Set up the next iteration if sending > 32 bits */
			bitlen -= 32;
			dout += 4;
		}

		spi->mode |= SPI_MODE_EN;

		spi->tx = tmpdout;	/* Write the data out */
		debug("*** spi_xfer: ... %08x written\n", tmpdout);

		/*
		 * Wait for SPI transmit to get out
		 * or time out (1 second = 1000 ms)
		 * The NE event must be read and cleared first
		 */
		for (tm = 0, isRead = 0; tm < SPI_TIMEOUT; ++tm) {
			event = spi->event;
			if (event & SPI_EV_NE) {
				tmpdin = spi->rx;
				spi->event |= SPI_EV_NE;
				isRead = 1;

				*(u32 *) din = (tmpdin << (32 - charSize));
				if (charSize == 32) {
					/* Advance output buffer by 32 bits */
					din += 4;
				}
			}
			/*
			 * Only bail when we've had both NE and NF events.
			 * This will cause timeouts on RO devices, so maybe
			 * in the future put an arbitrary delay after writing
			 * the device.  Arbitrary delays suck, though...
			 */
			if (isRead && (event & SPI_EV_NF))
				break;
		}
		if (tm >= SPI_TIMEOUT)
			puts("*** spi_xfer: Time out during SPI transfer");

		debug("*** spi_xfer: transfer ended. Value=%08x\n", tmpdin);
	}

	if (flags & SPI_XFER_END)
		spi_cs_deactivate(slave);

	return 0;
}
int misc_init_r (void)
{
	/* adjust flash start and size as well as the offset */
	gd->bd->bi_flashstart = 0 - flash_info[0].size;
	gd->bd->bi_flashoffset= flash_info[0].size - CONFIG_SYS_MONITOR_LEN;
#if 0
	volatile unsigned short *fpga_mode =
		(unsigned short *)((ulong)CONFIG_SYS_FPGA_BASE_ADDR + CONFIG_SYS_FPGA_CTRL);
	volatile unsigned char *duart0_mcr =
		(unsigned char *)((ulong)DUART0_BA + 4);
	volatile unsigned char *duart1_mcr =
		(unsigned char *)((ulong)DUART1_BA + 4);

	bd_t *bd = gd->bd;
	char *	tmp;                    /* Temporary char pointer      */
	unsigned char *dst;
	ulong len = sizeof(fpgadata);
	int status;
	int index;
	int i;
	unsigned long CPC0_CR0Reg;

	dst = malloc(CONFIG_SYS_FPGA_MAX_SIZE);
	if (gunzip (dst, CONFIG_SYS_FPGA_MAX_SIZE, (uchar *)fpgadata, &len) != 0) {
		printf ("GUNZIP ERROR - must RESET board to recover\n");
		do_reset (NULL, 0, 0, NULL);
	}

	status = fpga_boot(dst, len);
	if (status != 0) {
		printf("\nFPGA: Booting failed ");
		switch (status) {
		case ERROR_FPGA_PRG_INIT_LOW:
			printf("(Timeout: INIT not low after asserting PROGRAM*)\n ");
			break;
		case ERROR_FPGA_PRG_INIT_HIGH:
			printf("(Timeout: INIT not high after deasserting PROGRAM*)\n ");
			break;
		case ERROR_FPGA_PRG_DONE:
			printf("(Timeout: DONE not high after programming FPGA)\n ");
			break;
		}

		/* display infos on fpgaimage */
		index = 15;
		for (i=0; i<4; i++) {
			len = dst[index];
			printf("FPGA: %s\n", &(dst[index+1]));
			index += len+3;
		}
		putc ('\n');
		/* delayed reboot */
		for (i=20; i>0; i--) {
			printf("Rebooting in %2d seconds \r",i);
			for (index=0;index<1000;index++)
				udelay(1000);
		}
		putc ('\n');
		do_reset(NULL, 0, 0, NULL);
	}

	puts("FPGA:  ");

	/* display infos on fpgaimage */
	index = 15;
	for (i=0; i<4; i++) {
		len = dst[index];
		printf("%s ", &(dst[index+1]));
		index += len+3;
	}
	putc ('\n');

	free(dst);

	/*
	 * Reset FPGA via FPGA_DATA pin
	 */
	SET_FPGA(FPGA_PRG | FPGA_CLK);
	udelay(1000); /* wait 1ms */
	SET_FPGA(FPGA_PRG | FPGA_CLK | FPGA_DATA);
	udelay(1000); /* wait 1ms */
#endif

#if 0
	/*
	 * Enable power on PS/2 interface
	 */
	*fpga_mode |= CONFIG_SYS_FPGA_CTRL_PS2_RESET;

	/*
	 * Enable interrupts in exar duart mcr[3]
	 */
	*duart0_mcr = 0x08;
	*duart1_mcr = 0x08;
#endif
	return (0);
}
示例#9
0
文件: scott.c 项目: cspiegel/garglk
static void LoadDatabase(FILE *f, int loud)
{
	int ni,na,nw,nr,mc,pr,tr,wl,lt,mn,trm;
	int ct;
	short lo;
	Action *ap;
	Room *rp;
	Item *ip;
/* Load the header */

	if(fscanf(f,"%*d %d %d %d %d %d %d %d %d %d %d %d",
		&ni,&na,&nw,&nr,&mc,&pr,&tr,&wl,&lt,&mn,&trm)<10)
		Fatal("Invalid database(bad header)");
	GameHeader.NumItems=ni;
	Items=(Item *)MemAlloc(sizeof(Item)*(ni+1));
	GameHeader.NumActions=na;
	Actions=(Action *)MemAlloc(sizeof(Action)*(na+1));
	GameHeader.NumWords=nw;
	GameHeader.WordLength=wl;
	Verbs=MemAlloc(sizeof(char *)*(nw+1));
	Nouns=MemAlloc(sizeof(char *)*(nw+1));
	GameHeader.NumRooms=nr;
	Rooms=(Room *)MemAlloc(sizeof(Room)*(nr+1));
	GameHeader.MaxCarry=mc;
	GameHeader.PlayerRoom=pr;
	GameHeader.Treasures=tr;
	GameHeader.LightTime=lt;
	LightRefill=lt;
	GameHeader.NumMessages=mn;
	Messages=MemAlloc(sizeof(char *)*(mn+1));
	GameHeader.TreasureRoom=trm;

/* Load the actions */

	ct=0;
	ap=Actions;
	if(loud)
		printf("Reading %d actions.\n",na);
	while(ct<na+1)
	{
		if(fscanf(f,"%hu %hu %hu %hu %hu %hu %hu %hu",
			&ap->Vocab,
			&ap->Condition[0],
			&ap->Condition[1],
			&ap->Condition[2],
			&ap->Condition[3],
			&ap->Condition[4],
			&ap->Action[0],
			&ap->Action[1])!=8)
		{
			printf("Bad action line (%d)\n",ct);
			exit(1);
		}
		ap++;
		ct++;
	}
	ct=0;
	if(loud)
		printf("Reading %d word pairs.\n",nw);
	while(ct<nw+1)
	{
		Verbs[ct]=ReadString(f);
		Nouns[ct]=ReadString(f);
		ct++;
	}
	ct=0;
	rp=Rooms;
	if(loud)
		printf("Reading %d rooms.\n",nr);
	while(ct<nr+1)
	{
		if(fscanf(f,"%hd %hd %hd %hd %hd %hd",
			&rp->Exits[0],&rp->Exits[1],&rp->Exits[2],
			&rp->Exits[3],&rp->Exits[4],&rp->Exits[5])!=6)
		{
			printf("Bad room line (%d)\n",ct);
			exit(1);
		}
		rp->Text=ReadString(f);
		ct++;
		rp++;
	}
	ct=0;
	if(loud)
		printf("Reading %d messages.\n",mn);
	while(ct<mn+1)
	{
		Messages[ct]=ReadString(f);
		ct++;
	}
	ct=0;
	if(loud)
		printf("Reading %d items.\n",ni);
	ip=Items;
	while(ct<ni+1)
	{
		ip->Text=ReadString(f);
		ip->AutoGet=strchr(ip->Text,'/');
		/* Some games use // to mean no auto get/drop word! */
		if(ip->AutoGet && strcmp(ip->AutoGet,"//") && strcmp(ip->AutoGet,"/*"))
		{
			char *t;
			*ip->AutoGet++=0;
			t=strchr(ip->AutoGet,'/');
			if(t!=NULL)
				*t=0;
		}
		if(fscanf(f,"%hd",&lo)!=1)
		{
			printf("Bad item line (%d)\n",ct);
			exit(1);
		}
		ip->Location=(unsigned char)lo;
		ip->InitialLoc=ip->Location;
		ip++;
		ct++;
	}
	ct=0;
	/* Discard Comment Strings */
	while(ct<na+1)
	{
		free(ReadString(f));
		ct++;
	}
	if(fscanf(f,"%d",&ct)!=1)
	{
		puts("Cannot read version");
		exit(1);
	}
	if(loud)
		printf("Version %d.%02d of Adventure ",
		ct/100,ct%100);
	if(fscanf(f,"%d",&ct)!=1)
	{
		puts("Cannot read adventure number");
		exit(1);
	}
	if(loud)
		printf("%d.\nLoad Complete.\n\n",ct);
}
示例#10
0
int main(int argc, char **argv) {
  struct nfq_handle *h;
  struct nfq_q_handle *qh;
  struct nfnl_handle *nh;
  struct termios tio, old_tio;
  fd_set readfds;
  int fd;
  int rv;
  int ret;
  char buf[4096] __attribute__ ((aligned));
  int run = 1;
  
  // opening library handle
  h = nfq_open();
  if (!h) {
    fprintf(stderr, "error during nfq_open()\n");
    exit(1);
  }
  
  // unbinding existing nf_queue handler for AF_INET (if any)
  if (nfq_unbind_pf(h, AF_INET) < 0) {
    fprintf(stderr, "error during nfq_unbind_pf()\n");
    exit(1);
  }
  
  // binding nfnetlink_queue as nf_queue handler for AF_INET
  if (nfq_bind_pf(h, AF_INET) < 0) {
    fprintf(stderr, "error during nfq_bind_pf()\n");
    exit(1);
  }
  
  // binding this socket to queue '1'
  qh = nfq_create_queue(h,  1, &cb, NULL);
  if (!qh) {
    fprintf(stderr, "error during nfq_create_queue()\n");
    exit(1);
  }
  
  // setting copy_packet mode
  if (nfq_set_mode(qh, NFQNL_COPY_PACKET, 0xffff) < 0) {
    fprintf(stderr, "can't set packet_copy mode\n");
    exit(1);
  }

  /* get the terminal settings for stdin */
  tcgetattr(STDIN_FILENO, &tio);
  old_tio = tio;
  
  /* disable canonical mode (buffered i/o) and local echo */
  tio.c_lflag &=(~ICANON & ~ECHO);
  
  /* set the new settings immediately */
  tcsetattr(STDIN_FILENO,TCSANOW,&tio);
  
  fd = nfq_fd(h);

  while(run) {
    FD_ZERO(&readfds);
    FD_SET(0, &readfds);
    FD_SET(fd, &readfds);
  
    ret = select( fd + 1, &readfds, NULL, NULL, NULL);
    if(ret >= 0) {
      if(FD_ISSET(0, &readfds)) {
	int ch = fgetc(stdin);

	// q - quit
	if(ch == 'q') {
	  puts("quit");
	  run = 0;
	}
	
	// i - ignore request
	if((ch == 'i') && pending) {
	  puts("ignored");
	  free(pending);
	  pending = NULL;
	}
	
	// a - accept request
	if((ch == 'a') && pending) {
	  puts("accepted");
	  allowed = realloc(allowed, (allowed_len+1) * sizeof(device_t));
	  allowed[allowed_len++] = *pending;
	  free(pending);
	  pending = NULL;
	}

	// d - deny request
	if((ch == 'd') && pending) {
	  puts("denied");
	  denied = realloc(denied, (denied_len+1) * sizeof(device_t));
	  denied[denied_len++] = *pending;
	  free(pending);
	  pending = NULL;
	}
	
	// s - show
	if(ch == 's') {
	  puts("");
	  int d, i;

	  printf("Allowed:\n");
	  for(d=0;d<allowed_len;d++) {
	    for (i = 0; i < 5; i++)
	      printf("%02x:", allowed[d].hw_addr[i]);
	    printf("%02x\n", allowed[d].hw_addr[5]);
	  }
	  
	  printf("Denied:\n");
	  for(d=0;d<denied_len;d++) {
	    for (i = 0; i < 5; i++)
	      printf("%02x:", denied[d].hw_addr[i]);
	    printf("%02x\n", denied[d].hw_addr[5]);
	  }
	}
      }
      if(FD_ISSET(fd, &readfds)) {
	rv = recv(fd, buf, sizeof(buf), 0);
	nfq_handle_packet(h, buf, rv);
      }
    }
  }
      
  nfq_destroy_queue(qh);
  
  nfq_close(h);

  /* restore the former settings */
  tcsetattr(STDIN_FILENO,TCSANOW,&old_tio);
  
  exit(0);
}
示例#11
0
static int
do_test (void)
{
    pthread_t th;
    int err;

    printf ("&cond = %p\n&mut = %p\n", &cond, &mut);

    puts ("parent: get mutex");

    err = pthread_barrier_init (&bar, NULL, 2);
    if (err != 0)
    {
        puts ("parent: cannot init barrier");
        exit (1);
    }

    puts ("parent: create child");

    err = pthread_create (&th, NULL, tf1, NULL);
    if (err != 0)
    {
        puts ("parent: cannot create thread");
        exit (1);
    }

    puts ("parent: wait for child to lock mutex");

    err = pthread_barrier_wait (&bar);
    if (err != 0 && err != PTHREAD_BARRIER_SERIAL_THREAD)
    {
        puts ("parent: cannot wait for barrier");
        exit (1);
    }

    err = pthread_mutex_lock (&mut);
    if (err != 0)
    {
        puts ("parent: mutex_lock failed");
        exit (1);
    }

    err = pthread_mutex_unlock (&mut);
    if (err != 0)
    {
        puts ("parent: mutex_unlock failed");
        exit (1);
    }

    if (pthread_cancel (th) != 0)
    {
        puts ("cannot cancel thread");
        exit (1);
    }

    void *r;
    err = pthread_join (th, &r);
    if (err != 0)
    {
        puts ("parent: failed to join");
        exit (1);
    }

    if (r != PTHREAD_CANCELED)
    {
        puts ("child hasn't been canceled");
        exit (1);
    }



    puts ("parent: create 2nd child");

    err = pthread_create (&th, NULL, tf2, NULL);
    if (err != 0)
    {
        puts ("parent: cannot create thread");
        exit (1);
    }

    puts ("parent: wait for child to lock mutex");

    err = pthread_barrier_wait (&bar);
    if (err != 0 && err != PTHREAD_BARRIER_SERIAL_THREAD)
    {
        puts ("parent: cannot wait for barrier");
        exit (1);
    }

    err = pthread_mutex_lock (&mut);
    if (err != 0)
    {
        puts ("parent: mutex_lock failed");
        exit (1);
    }

    err = pthread_mutex_unlock (&mut);
    if (err != 0)
    {
        puts ("parent: mutex_unlock failed");
        exit (1);
    }

    if (pthread_cancel (th) != 0)
    {
        puts ("cannot cancel thread");
        exit (1);
    }

    err = pthread_join (th, &r);
    if (err != 0)
    {
        puts ("parent: failed to join");
        exit (1);
    }

    if (r != PTHREAD_CANCELED)
    {
        puts ("child hasn't been canceled");
        exit (1);
    }

    puts ("done");

    return 0;
}
示例#12
0
文件: init.c 项目: 0871087123/rtems
rtems_task Init(
    rtems_task_argument ignored
    )
{
  rtems_rbtree_control  rbtree1;
  rtems_rbtree_node    *p;
  test_node            node1, node2;
  test_node            node_array[100];
  test_node            search_node;
  int                  id;
  int i;

  puts( "\n\n*** TEST OF RTEMS RBTREE API ***" );

  puts( "Init - Initialize rbtree empty" );
  rtems_rbtree_initialize_empty( &rbtree1, &test_compare_function, true );

  if ( !rtems_rbtree_is_unique( &rbtree1 ) )
    puts( "INIT - FAILED IS UNIQUE CHECK" );
  if ( rtems_rbtree_is_unique( NULL ) )
    puts( "INIT - FAILED IS UNIQUE CHECK" );

  /* verify that the rbtree insert work */
  puts( "INIT - Verify rtems_rbtree_insert with two nodes" );
  node1.id = 1;
  node1.key = 1;
  node2.id = 2;
  node2.key = 2;
  rtems_rbtree_insert( &rbtree1, &node1.Node );
  rtems_rbtree_insert( &rbtree1, &node2.Node );

  p = rtems_rbtree_insert( &rbtree1, NULL );
  if (p != (void *)(-1))
    puts( "INIT - FAILED NULL NODE INSERT" );

  _RBTree_Rotate(NULL, RBT_LEFT);
  i = (node1.Node.parent == &node2.Node);
  _RBTree_Rotate( &node1.Node,
                  !node1.Node.child[RBT_LEFT] ? RBT_RIGHT : RBT_LEFT
                );
  if ( (node1.Node.parent == &node2.Node) != i )
    puts( "INIT - FAILED FALSE ROTATION" );

  if (!rb_assert(rbtree1.root) )
    puts( "INIT - FAILED TREE CHECK" );

  for ( p = rtems_rbtree_get_min(&rbtree1), id = 1 ; p ;
      p = rtems_rbtree_get_min(&rbtree1) , id++ ) {
    test_node *t = rtems_rbtree_container_of(p,test_node,Node);
    if ( id > 2 ) {
      puts( "INIT - TOO MANY NODES ON RBTREE" );
      rtems_test_exit(0);
    }
    if ( t->id != id ) {
      puts( "INIT - ERROR ON RBTREE ID MISMATCH" );
      rtems_test_exit(0);
    }

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }
  if (id < 2) {
    puts("INIT - NOT ENOUGH NODES ON RBTREE");
    rtems_test_exit(0);
  }

  puts("INIT - Verify rtems_rbtree_insert with the same value twice");
  node2.key = node1.key;
  rtems_rbtree_insert(&rbtree1, &node1.Node);
  p = rtems_rbtree_insert(&rbtree1, &node2.Node);

  if (p != &node1.Node)
    puts( "INIT - FAILED DUPLICATE INSERT" );

  for ( p = rtems_rbtree_get_min(&rbtree1), id = 1 ; p ;
      p = rtems_rbtree_get_min(&rbtree1) , id++ ) {
    test_node *t = rtems_rbtree_container_of(p,test_node,Node);
    if ( id > 1 ) {
      puts( "INIT - TOO MANY NODES ON RBTREE" );
      rtems_test_exit(0);
    }
    if ( t->id != id ) {
      puts( "INIT - ERROR ON RBTREE ID MISMATCH" );
      rtems_test_exit(0);
    }

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }
  if (id < 1) {
    puts("INIT - NOT ENOUGH NODES ON RBTREE");
    rtems_test_exit(0);
  }
  node2.key = 2;

  /* verify that the rbtree is empty */
  puts( "INIT - Verify rtems_rbtree_is_empty" );
  if(!rtems_rbtree_is_empty(&rbtree1)) {
    puts( "INIT - TREE NOT EMPTY" );
    rtems_test_exit(0);
  }

  puts( "INIT - Verify rtems_XXX on an empty tree" );
  if(rtems_rbtree_get_min(&rbtree1)) {
    puts("INIT - get_min on empty returned non-NULL");
    rtems_test_exit(0);
  }
  if(rtems_rbtree_get_max(&rbtree1)) {
    puts("INIT - get_max on empty returned non-NULL");
    rtems_test_exit(0);
  }
  if(rtems_rbtree_peek_min(&rbtree1)) {
    puts("INIT - peek_min on empty returned non-NULL");
    rtems_test_exit(0);
  }
  if(rtems_rbtree_peek_max(&rbtree1)) {
    puts("INIT - peek_max on empty returned non-NULL");
    rtems_test_exit(0);
  }


  /* verify that the rbtree insert works after a tree is emptied */
  puts( "INIT - Verify rtems_rbtree_insert after empty tree" );
  node1.id = 2;
  node1.key = 2;
  node2.id = 1;
  node2.key = 1;
  rtems_rbtree_insert( &rbtree1, &node1.Node );
  rtems_rbtree_insert( &rbtree1, &node2.Node );

  puts( "INIT - Verify rtems_rbtree_peek_max/min, rtems_rbtree_extract" );
  test_node *t1 = rtems_rbtree_container_of(rtems_rbtree_peek_max(&rbtree1),
         test_node,Node);
  test_node *t2 = rtems_rbtree_container_of(rtems_rbtree_peek_min(&rbtree1),
         test_node,Node);
  if (t1->key - t2->key != 1) {
    puts( "INIT - Peek Min - Max failed" );
    rtems_test_exit(0);
  }
  p = rtems_rbtree_peek_max(&rbtree1);
  rtems_rbtree_extract(&rbtree1, p);
  t1 = rtems_rbtree_container_of(p,test_node,Node);
  if (t1->key != 2) {
    puts( "INIT - rtems_rbtree_extract failed");
    rtems_test_exit(0);
  }
  rtems_rbtree_insert(&rbtree1, p);

  for ( p = rtems_rbtree_get_min(&rbtree1), id = 1 ; p ;
      p = rtems_rbtree_get_min(&rbtree1) , id++ ) {
    test_node *t = rtems_rbtree_container_of(p,test_node,Node);
    if ( id > 2 ) {
      puts( "INIT - TOO MANY NODES ON RBTREE" );
      rtems_test_exit(0);
    }
    if ( t->id != id ) {
      puts( "INIT - ERROR ON RBTREE ID MISMATCH" );
      rtems_test_exit(0);
    }
  }
  
  puts( "INIT - Verify rtems_rbtree_insert with 100 nodes value [0,99]" );
  for (i = 0; i < 100; i++) {
    node_array[i].id = i;
    node_array[i].key = i;
    rtems_rbtree_insert( &rbtree1, &node_array[i].Node );

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  puts( "INIT - Removing 100 nodes" );

  for ( p = rtems_rbtree_get_min(&rbtree1), id = 0 ; p ;
      p = rtems_rbtree_get_min(&rbtree1) , id++ ) {
    test_node *t = rtems_rbtree_container_of(p,test_node,Node);
    if ( id > 99 ) {
      puts( "INIT - TOO MANY NODES ON RBTREE" );
      rtems_test_exit(0);
    }
    if ( t->id != id ) {
      puts( "INIT - ERROR ON RBTREE ID MISMATCH" );
      rtems_test_exit(0);
    }

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }
  
  if(!rtems_rbtree_is_empty(&rbtree1)) {
    puts( "INIT - TREE NOT EMPTY" );
    rtems_test_exit(0);
  }

  puts( "INIT - Verify rtems_rbtree_insert with 100 nodes value [99,0]" );
  for (i = 0; i < 100; i++) {
    node_array[i].id = 99-i;
    node_array[i].key = 99-i;
    rtems_rbtree_insert( &rbtree1, &node_array[i].Node );

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  puts( "INIT - Removing 100 nodes" );

  for ( p = rtems_rbtree_get_min(&rbtree1), id = 0 ; p ;
      p = rtems_rbtree_get_min(&rbtree1) , id++ ) {
    test_node *t = rtems_rbtree_container_of(p,test_node,Node);
    if ( id > 99 ) {
      puts( "INIT - TOO MANY NODES ON RBTREE" );
      rtems_test_exit(0);
    }
    if ( t->id != id ) {
      puts( "INIT - ERROR ON RBTREE ID MISMATCH" );
      rtems_test_exit(0);
    }

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  if(!rtems_rbtree_is_empty(&rbtree1)) {
    puts( "INIT - TREE NOT EMPTY" );
    rtems_test_exit(0);
  }

  /* testing rbtree_extract by adding 100 nodes then removing the 20 with
   * keys specified by the numbers array, then removing the rest */
  puts( "INIT - Verify rtems_rbtree_extract with 100 nodes value [0,99]" );
  for (i = 0; i < 100; i++) {
    node_array[i].id = i;
    node_array[i].key = i;
    rtems_rbtree_insert( &rbtree1, &node_array[i].Node );

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  puts( "INIT - Extracting 20 random nodes" );

  for (i = 0; i < 20; i++) {
    id = numbers[i];
    rtems_rbtree_extract( &rbtree1, &node_array[id].Node );
    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  puts( "INIT - Removing 80 nodes" );

  for ( p = rtems_rbtree_get_min(&rbtree1), id = 0, i = 0 ; p ;
      p = rtems_rbtree_get_min(&rbtree1) , id++ ) {
    test_node *t = rtems_rbtree_container_of(p, test_node, Node);

    while ( id == numbers_sorted[i] ) {
      /* skip if expected minimum (id) is in the set of extracted numbers */
      id++;
      i++;
    }

    if ( id > 99 ) {
      puts( "INIT - TOO MANY NODES ON RBTREE" );
      rtems_test_exit(0);
    }

    if ( t->id != id ) {
      puts( "INIT - ERROR ON RBTREE ID MISMATCH" );
      rtems_test_exit(0);
    }

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  if(!rtems_rbtree_is_empty(&rbtree1)) {
    puts( "INIT - TREE NOT EMPTY" );
    rtems_test_exit(0);
  }

  /* Additional rtems_rbtree_extract test which removes a node
   * with two children while target node has a left child only. */
  for ( i = 0; i < 7; i++ ) {
    node_array[i].id = i;
    node_array[i].key = i;
  }
  rtems_rbtree_insert( &rbtree1, &node_array[3].Node );
  rtems_rbtree_insert( &rbtree1, &node_array[1].Node );
  rtems_rbtree_insert( &rbtree1, &node_array[5].Node );
  rtems_rbtree_insert( &rbtree1, &node_array[0].Node );
  rtems_rbtree_insert( &rbtree1, &node_array[2].Node );
  rtems_rbtree_insert( &rbtree1, &node_array[4].Node );
  rtems_rbtree_insert( &rbtree1, &node_array[6].Node );
  rtems_rbtree_extract( &rbtree1, &node_array[2].Node );
  /* node_array[1] has now only a left child. */
  if ( !node_array[1].Node.child[RBT_LEFT] ||
        node_array[1].Node.child[RBT_RIGHT] )
     puts( "INIT - LEFT CHILD ONLY NOT FOUND" );
  rtems_rbtree_extract( &rbtree1, &node_array[3].Node );
  while( (p = rtems_rbtree_get_max(&rbtree1)) );

  puts( "INIT - Verify rtems_rbtree_get_max with 100 nodes value [99,0]" );
  for (i = 0; i < 100; i++) {
    node_array[i].id = 99-i;
    node_array[i].key = 99-i;
    rtems_rbtree_insert( &rbtree1, &node_array[i].Node );

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  puts( "INIT - Removing 100 nodes" );

  for ( p = rtems_rbtree_get_max(&rbtree1), id = 0 ; p ;
      p = rtems_rbtree_get_max(&rbtree1) , id++ ) {
    test_node *t = rtems_rbtree_container_of(p,test_node,Node);
    if ( id > 99 ) {
      puts( "INIT - TOO MANY NODES ON RBTREE" );
      rtems_test_exit(0);
    }
    if ( t->id != 99-id ) {
      puts( "INIT - ERROR ON RBTREE ID MISMATCH" );
      rtems_test_exit(0);
    }

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  if(!rtems_rbtree_is_empty(&rbtree1)) {
    puts( "INIT - TREE NOT EMPTY" );
    rtems_test_exit(0);
  }

  puts( "INIT - Verify rtems_rbtree_get_max with 100 nodes value [0,99]" );
  for (i = 0; i < 100; i++) {
    node_array[i].id = i;
    node_array[i].key = i;
    rtems_rbtree_insert( &rbtree1, &node_array[i].Node );

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  puts( "INIT - Verify rtems_rbtree_find" );
  search_node.key = 30;
  p = rtems_rbtree_find(&rbtree1, &search_node.Node);
  if(rtems_rbtree_container_of(p,test_node,Node)->id != 30) {
    puts ("INIT - ERROR ON RBTREE ID MISMATCH");
    rtems_test_exit(0);
  }

  puts( "INIT - Verify rtems_rbtree_predecessor/successor");
  p = rtems_rbtree_predecessor(p);
  if(p && rtems_rbtree_container_of(p,test_node,Node)->id != 29) {
    puts ("INIT - ERROR ON RBTREE ID MISMATCH");
    rtems_test_exit(0);
  }
  p = rtems_rbtree_find(&rbtree1, &search_node.Node);
  p = rtems_rbtree_successor(p);
  if(p && rtems_rbtree_container_of(p,test_node,Node)->id != 31) {
    puts ("INIT - ERROR ON RBTREE ID MISMATCH");
    rtems_test_exit(0);
  }

  p = rtems_rbtree_find(&rbtree1, &search_node.Node);
  puts( "INIT - Verify rtems_rbtree_find_header" );
  if (rtems_rbtree_find_header(p) != &rbtree1) {
    puts ("INIT - ERROR ON RBTREE HEADER MISMATCH");
    rtems_test_exit(0);
  }

  if ( _RBTree_Sibling( NULL ) != NULL )
    puts ( "INIT - ERROR ON RBTREE NULL SIBLING MISMATCH" );
  if ( _RBTree_Sibling( rbtree1.root ) != NULL )
    puts ( "INIT - ERROR ON RBTREE NULL SIBLING MISMATCH" );
  if ( _RBTree_Grandparent( NULL ) != NULL )
    puts ( "INIT - ERROR ON RBTREE NULL GRANDPARENT MISMATCH" );
  if ( _RBTree_Is_red( NULL ) != 0 )
    puts ( "INIT - ERROR ON RBTREE NULL IS RED MISMATCH" );
  if ( _RBTree_Is_red( rbtree1.root ) != 0 )
    puts ( "INIT - ERROR ON RBTREE NULL IS RED MISMATCH" );

  puts( "INIT - Removing 100 nodes" );

  for ( p = rtems_rbtree_get_max(&rbtree1), id = 99 ; p ;
      p = rtems_rbtree_get_max(&rbtree1) , id-- ) {
    test_node *t = rtems_rbtree_container_of(p,test_node,Node);
    if ( id < 0 ) {
      puts( "INIT - TOO MANY NODES ON RBTREE" );
      rtems_test_exit(0);
    }
    if ( t->id != id ) {
      puts( "INIT - ERROR ON RBTREE ID MISMATCH" );
      rtems_test_exit(0);
    }

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  if(!rtems_rbtree_is_empty(&rbtree1)) {
    puts( "INIT - TREE NOT EMPTY" );
    rtems_test_exit(0);
  }

  if (rtems_rbtree_find_header(&node_array[0].Node) != NULL) {
    puts ("INIT - ERROR ON RBTREE HEADER MISMATCH");
    rtems_test_exit(0);
  }
  if (rtems_rbtree_find_header(NULL) != NULL) {
    puts ("INIT - ERROR ON RBTREE HEADER MISMATCH");
    rtems_test_exit(0);
  }

  puts("INIT - Insert 20 random numbers");
  for (i = 0; i < 20; i++) {
    node_array[i].id = numbers[i];
    node_array[i].key = numbers[i];
    rtems_rbtree_insert( &rbtree1, &node_array[i].Node );

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  puts( "INIT - Removing 20 nodes" );

  for ( p = rtems_rbtree_get_min(&rbtree1), id = 0 ; p ;
      p = rtems_rbtree_get_min(&rbtree1) , id++ ) {
    test_node *t = rtems_rbtree_container_of(p,test_node,Node);
    if ( id > 19 ) {
      puts( "INIT - TOO MANY NODES ON RBTREE" );
      rtems_test_exit(0);
    }
    if ( t->id != numbers_sorted[id] ) {
      puts( "INIT - ERROR ON RBTREE ID MISMATCH" );
      rtems_test_exit(0);
    }

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  if(!rtems_rbtree_is_empty(&rbtree1)) {
    puts( "INIT - TREE NOT EMPTY" );
    rtems_test_exit(0);
  }

  puts( "INIT - Verify rtems_rbtree_initialize with 100 nodes value [0,99]" );
  for (i = 0; i < 100; i++) {
    node_array[i].id = i;
    node_array[i].key = i;
  }
  rtems_rbtree_initialize( &rbtree1, &test_compare_function,
                           &node_array[0].Node, 100,
                           sizeof(test_node), true );

  puts( "INIT - Removing 100 nodes" );

  for ( p = rtems_rbtree_get_min(&rbtree1), id = 0 ; p ;
      p = rtems_rbtree_get_min(&rbtree1) , id++ ) {
    test_node *t = rtems_rbtree_container_of(p,test_node,Node);
    if ( id > 99 ) {
      puts( "INIT - TOO MANY NODES ON RBTREE" );
      rtems_test_exit(0);
    }

    if ( t->id != id ) {
      puts( "INIT - ERROR ON RBTREE ID MISMATCH" );
      rtems_test_exit(0);
    }

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  if(!rtems_rbtree_is_empty(&rbtree1)) {
    puts( "INIT - TREE NOT EMPTY" );
    rtems_test_exit(0);
  }

  /* Initialize the tree for duplicate keys */
  puts( "Init - Initialize duplicate rbtree empty" );
  rtems_rbtree_initialize_empty( &rbtree1, &test_compare_function, false );

  if ( rtems_rbtree_is_unique( &rbtree1 ) )
    puts( "INIT - FAILED IS UNIQUE CHECK" );
  if ( rtems_rbtree_is_unique( NULL ) )
    puts( "INIT - FAILED IS UNIQUE CHECK" );

  puts( "INIT - Verify rtems_rbtree_insert with 100 nodes value [0,99]" );
  for (i = 0; i < 100; i++) {
    node_array[i].id = i;
    node_array[i].key = i%5;
    rtems_rbtree_insert( &rbtree1, &node_array[i].Node );

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  puts( "INIT - Verify rtems_rbtree_find in a duplicate tree" );
  search_node.key = 2;
  p = rtems_rbtree_find(&rbtree1, &search_node.Node);
  if(rtems_rbtree_container_of(p,test_node,Node)->id != 2) {
    puts ("INIT - ERROR ON RBTREE ID MISMATCH");
    rtems_test_exit(0);
  }

  puts( "INIT - Removing 100 nodes" );

  for ( p = rtems_rbtree_get_min(&rbtree1), id = 0 ; p ;
      p = rtems_rbtree_get_min(&rbtree1) , id++ ) {
    test_node *t = rtems_rbtree_container_of(p,test_node,Node);
    if ( id > 99 ) {
      puts( "INIT - TOO MANY NODES ON RBTREE" );
      rtems_test_exit(0);
    }
    if ( t->id != ( ((id*5)%100) + (id/20) ) ) {
      puts( "INIT - ERROR ON RBTREE ID MISMATCH" );
      rtems_test_exit(0);
    }

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  if(!rtems_rbtree_is_empty(&rbtree1)) {
    puts( "INIT - TREE NOT EMPTY" );
    rtems_test_exit(0);
  }

  puts( "INIT - Verify rtems_rbtree_insert with 100 nodes value [99,0]" );
  for (i = 0; i < 100; i++) {
    node_array[i].id = 99-i;
    node_array[i].key = (99-i)%5;
    rtems_rbtree_insert( &rbtree1, &node_array[i].Node );

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  puts( "INIT - Verify rtems_rbtree_find in a duplicate tree" );
  search_node.key = 2;
  p = rtems_rbtree_find(&rbtree1, &search_node.Node);
  if(rtems_rbtree_container_of(p,test_node,Node)->id != 97) {
    puts ("INIT - ERROR ON RBTREE ID MISMATCH");
    rtems_test_exit(0);
  }

  puts( "INIT - Removing 100 nodes" );

  for ( p = rtems_rbtree_get_min(&rbtree1), id = 0 ; p ;
      p = rtems_rbtree_get_min(&rbtree1) , id++ ) {
    test_node *t = rtems_rbtree_container_of(p,test_node,Node);
    if ( id > 99 ) {
      puts( "INIT - TOO MANY NODES ON RBTREE" );
      rtems_test_exit(0);
    }
    if ( t->id != ( (((99-id)*5)%100) + (id/20) ) ) {
      puts( "INIT - ERROR ON RBTREE ID MISMATCH" );
      rtems_test_exit(0);
    }

    if (!rb_assert(rbtree1.root) )
      puts( "INIT - FAILED TREE CHECK" );
  }

  if(!rtems_rbtree_is_empty(&rbtree1)) {
    puts( "INIT - TREE NOT EMPTY" );
    rtems_test_exit(0);
  }

  puts( "*** END OF RTEMS RBTREE API TEST ***" );
  rtems_test_exit(0);
}
示例#13
0
void press_key(int fd, int key, int value) 
{
  if (key>0) 
    {
      static struct input_event event={
	.type = EV_KEY
      };
      const static struct input_event syn_event={
	.type = EV_SYN,
	.code = SYN_REPORT,
	.value = 0
      };
      
      event.code=key;
      event.value=value;

      write(fd, &event, sizeof(event));
      write(fd, &syn_event, sizeof(event));
    }
}

int main(int argc, char **argv)
{
  int rfd=0, wfd=0, res=0;
  unsigned char buf[16];
  typedef unsigned long long keystate;
  
  int opt;
  unsigned char do_fork=1;
  
  while ((opt = getopt(argc, argv, "f")) != -1) 
    {
      switch (opt) 
	{
	case 'f':
	  do_fork = 0;
	  break;
	default:
	  fprintf (stderr, "Invalid option: -%c\n", opt);
	  return 1;
	}
    }

  if (argc > optind+1) 
    {
      fprintf (stderr, "Usage: %s [device]\n", *argv);
      exit(1);
    }
  if (argc == optind+1) 
    {
      if ((rfd = open (argv[optind], O_RDONLY)) <= 0) 
	{
	  perror (argv[optind]);
	  return 1;
	}
    }
  else 
    {
      rfd=open_kb();
    }
  
  wfd=open_uinput();
  
  if (rfd <= 0) 
    {
      puts ("failed to find keyboard");
      return 1;
    }
  
  if (do_fork) 
    {
      switch(fork())
	{
	case -1:
	  perror ("fork");
	  return 1;
	case 0:
	  break;
	default:
	  return 0;
	}
    }

  keystate prev=0, cur=0;
  while ((res = read(rfd, buf, 16)) > 0) 
    {
      cur=*((keystate*)(buf+2));
      
      if (cur && (cur != prev)) 
	{
	  keystate cur_new = cur & (cur ^ prev);
	  keystate cur_old = prev & (cur ^ prev);

	  if (cur_new || cur_old) 
	    {
	      int i;
	      keystate b;
	      for (i=0, b=1; positions[i]!=0; ++i, b<<=1) 
		{
		  if (cur_old & b)
		    press_key(wfd,positions[i], 0);
		  else if (cur_new & b)
		    press_key(wfd,positions[i], 1);
		}
	      prev=cur;
	    }
	}
    }

  close(rfd);
  ioctl(wfd, UI_DEV_DESTROY);
  close(wfd);

  return 0;
}
示例#14
0
MDA_TASK_RETURN_CODE MDA_TASK_BUOY:: run_single_buoy(int buoy_index, BUOY_COLOR color) {
    puts("Press q to quit");

    assert (buoy_index >= 0 && buoy_index <= 1);
    
    MDA_VISION_MODULE_BUOY buoy_vision;
    MDA_TASK_RETURN_CODE ret_code = TASK_MISSING;

    /// Here we store the starting attitude vector, so we can return to this attitude later
    int starting_yaw = attitude_input->yaw();
    printf("Starting yaw: %d\n", starting_yaw);

    //set (DEPTH, 400);

    TASK_STATE state = STARTING;
    bool done_buoy = false;
    static TIMER timer;
    static TIMER master_timer;
    timer.restart();
    master_timer.restart();


//###### hack code for competition
    set (SPEED, 0);
    
    int hack_depth, hack_time;
    read_mv_setting ("hacks.csv", "BUOY_DEPTH", hack_depth);
    read_mv_setting ("hacks.csv", "BUOY_TIME", hack_time);
    printf ("Buoy: going to depth %d\n", hack_depth);
        fflush(stdout);
    if (hack_depth > 500)
	set (DEPTH, 500);
    if (hack_depth > 600)
        set (DEPTH, 600);
    set (DEPTH, hack_depth);
    set (YAW, starting_yaw);

    printf ("Buoy: moving forward for %d seconds\n", hack_time);
        fflush(stdout);
    timer.restart();
    while (timer.get_time() < hack_time) {
        set (SPEED, 8);
    }
    set(SPEED, 0);

    if (hack_depth > 600)
         set (DEPTH, 600);
    if (hack_depth > 500)
        set (DEPTH, 500);
    set (YAW, starting_yaw);
    return TASK_DONE;
//###### end hack code for competition
    /**
    * Basic Algorithm
    *  - Assume for now that we just want to hit the cylindrical buoys when they're red
    *  - We want to search for 1 or 2 buoys. If we find both:
    *    - Are both non-red and/or cycling? Go for the one indicated by buoy_index
    *    - Is one non-red and/or cycling? Go for that one
    *    - Do we only see one buoy? Go there if non-red and/or cycling
    *
    */
    
    while (1) {
        IplImage* frame = image_input->get_image();
        if (!frame) {
            ret_code = TASK_ERROR;
            break;
        }

        MDA_VISION_RETURN_CODE vision_code = buoy_vision.filter(frame);
        (void) vision_code;
        // clear dwn image - RZ: do we need this?
        //int down_frame_ready = image_input->ready_image(DWN_IMG);
        //(void) down_frame_ready;

        bool valid[2] = {false, false};
        int ang_x[2], ang_y[2];
        int range[2];
        int color[2];
        static bool color_cycling[2] = {false, false};
        static int curr_index = -1;
        static int prev_time = -1;
        static int prev_color = -1;
        static int n_valid_color_find_frames = 0;

        if (!done_buoy) {
            // state machine
            if (state == STARTING) {
                // here we just move forward until we find something, and pan if we havent found anything for a while
                printf ("Starting: Moving Foward for 1 meter\n");
                move (FORWARD, 1);

                if (timer.get_time() > 1) {
                    set (SPEED, 0);
                    timer.restart();
                    buoy_vision.clear_frames();
                    state = STOPPED;
                }
            }
            else if (state == STOPPED) {
                if (timer.get_time() < 0) {
                    printf ("Stopped: Collecting Frames\n");
                }
                else {
                    get_data_from_frame (&buoy_vision, valid, ang_x, ang_y, range, color);

                    if (!valid[0] && !valid[1]) { // no buoys
                        printf ("Stopped: No target\n");
                        if (master_timer.get_time() > 60) { // we've seen nothing for 60 seconds
                            printf ("Master Timer Timeout!!\n");
                            return TASK_MISSING;
                        }
                        if (timer.get_time() > 2) {
                            printf ("Stopped: Timeout\n");
                            timer.restart();
                            state = STARTING;
                        }
                    }
                    else { // turn towards the buoy we want
                        // chose buoy
                        if (valid[0] && valid[1])
                            curr_index = buoy_index;
                        else
                            curr_index = valid[0] ? 0 : 1;

                        printf ("Stopped: Identified buoy %d (%s) as target\n", curr_index, color_int_to_string(color[curr_index]).c_str());
                        move (RIGHT, ang_x[curr_index]);
                        
                        timer.restart();
                        master_timer.restart();
                        prev_color = color[curr_index];
                        prev_time = -1;
                        buoy_vision.clear_frames();
                        n_valid_color_find_frames = 0;
                        state = FIND_COLOR;
                    }
                }
            }
            else if (state == FIND_COLOR) {
                // stare for 6 seconds, check if the buoy color changes
                int t = timer.get_time();
                if (t >= 4) {
                    if (n_valid_color_find_frames <= 2) {
                        printf ("Find Color: Not enough good frames (%d).\n", n_valid_color_find_frames);
                        timer.restart();
                        master_timer.restart();
                        state = STARTING;
                    }
                    else if (color_cycling[curr_index] || prev_color != MV_RED) {
                        printf ("Find Color: Finished. Must approach buoy %d.\n", curr_index);
                        timer.restart();
                        master_timer.restart();
                        state = APPROACH;
                    }
                    else {
                        printf ("Find Color: Finished. No need to do buoy %d.\n", curr_index);
                        done_buoy = true;
                        return TASK_QUIT;
                    }
                }
                else if (t != prev_time) {
                    printf ("Find_Color: examined buoy %d for %d seconds.\n", curr_index, t);
                    get_data_from_frame (&buoy_vision, valid, ang_x, ang_y, range, color, curr_index);

                    if (valid[curr_index]) {  
                        if (color[curr_index] != prev_color) {
                            printf ("\tFound buoy %d as color cycling.\n", curr_index);
                            color_cycling[curr_index] = true;
                        }
                        prev_time = t;
                        n_valid_color_find_frames++;
                    } 
                }
            }
            else if (state == APPROACH) {
                get_data_from_frame (&buoy_vision, valid, ang_x, ang_y, range, color, curr_index);
                if (valid[curr_index]) {
                    printf ("Approach[%d]: range=%d, ang_x=%d\n", curr_index, range[curr_index], ang_x[curr_index]);
                    if (range[curr_index] > 100) { // long range = more freedom to turn/sink
                        if (abs(ang_x[curr_index]) > 5) {
                            set(SPEED, 0);
                            move(RIGHT, ang_x[curr_index]);
                            buoy_vision.clear_frames();
                        }    
                        /*else if (tan(ang_y[curr_index])*range[curr_index] > 50) { // depth in centimeters
                            set(SPEED, 0);
                            move (SINK, 25); // arbitrary rise for now
                        }*/
                        else {
                            set(SPEED, 1);
                        }
                    }
                    else {
                        if (abs(ang_x[curr_index]) > 10) {
                            set(SPEED, 0);
                            move(RIGHT, ang_x[curr_index]);
                            buoy_vision.clear_frames();
                        }
                        else {
                            done_buoy = true;
                        }   
                    }

                    timer.restart();
                    master_timer.restart();
                }
                else {
                    set(SPEED, 0);
                    if (timer.get_time() > 4) { // 4 secs without valid input
                        printf ("Approach: Timeout");
                        timer.restart();
                        state = STOPPED;
                    }
                }
            }
        } // done_buoy
        else { // done_buoy
            // charge forwards, then retreat back some number of meters, then realign sub to starting attitude
            printf("Ramming buoy\n");
            timer.restart();
            while (timer.get_time() < 2)
                move(FORWARD, 2);
            stop();

            // retreat backwards
            printf("Reseting Position\n");
            timer.restart();
            while (timer.get_time() < 3)
                move(REVERSE, 2);
            stop();

            ret_code = TASK_DONE;
            break;
        }

        // Ensure debug messages are printed
        fflush(stdout);
        // Exit if instructed to
        char c = cvWaitKey(TASK_WK);
        if (c != -1) {
            CharacterStreamSingleton::get_instance().write_char(c);
        }
        if (CharacterStreamSingleton::get_instance().wait_key(1) == 'q'){
            stop();
            ret_code = TASK_QUIT;
            break;
        }
    }

    return ret_code;
}
示例#15
0
int main(int argc, char **argv) {
    char buf[65536], *p;
    int i;

    while (fgets(buf, 65536, stdin)) {
        line++;
        p = buf + wsspan(buf);

        while (*p) {
            if (*p == '(') {
                depth++;
                p++;
                if (!curproc && depth > 1)
                    errx(1, "depth > 1 without register-procedure on line %d\n", line);
                if (depth > 3)
                    errx(1, "depth > 3 on line %d\n", line);
                if (depth == 1) {
                    hnum = 0;
                    hmax = 7;
                } else if (depth == 2) {
                    hmax = 3;
                    if (++iomode > 1)
                        curioargs = &curproc->oargs;
                    else
                        curioargs = &curproc->iargs;
                } else if (depth == 3) {
                    struct ioarg *arg = calloc(1, sizeof(*arg));
                    *curioargs = curioarg = arg;
                    curioargs = &arg->next;
                    hnum = 0;
                    hlist = arg->hlist;
                }
            } else if (*p == ')') {
                depth--;
                p++;
                if (depth == 0) {
                    hnum = hmax = inum = onum = iomode = 0;
                    curproc = NULL;
                    hlist = NULL;
                } else if (depth == 1) {
                    curioargs = NULL;
                } else if (depth == 2) {
                    curioarg = NULL;
                }
            } else if (*p == '\"') {
                char *eq = ++p, *neq;

                if ((depth != 1) && (depth != 3))
                    errx(1, "string with depth != 1 or 3 on line %d: %s\n", line, --p);
                if (!curproc)
                    errx(1, "string without register-procedure on line %d\n", line);
                if (hnum >= hmax)
                    errx(1, "too many strings on line %d\n", line);

                while ((neq = strchr(eq, '\"')) && (neq > p) && (neq[-1] == '\\')) {
                    strcpy(neq - 1, neq);
                    eq = neq;
                }
                if (!neq) {
                    --p;
                    if (!fgets(buf + strlen(buf), 65536 - strlen(buf), stdin))
                        errx(1, "EOF in string at line %d\n", line);
                    continue;
                }

                hlist[hnum++] = strndup(p, neq - p);
                p = ++neq;
            } else if (!strncmp(p, "register-procedure", 18)) {
                if (depth != 1)
                    errx(1, "register-procedure at depth %d, line %d\n", depth, line);
                p += 18;
                curproc = &procs[nprocs++];
                hlist = curproc->hlist;
            } else {
                errx(1, "unknown token on line: %s\n", line, p);
            }
            p += wsspan(p);
        }
    }

    qsort(procs, nprocs, sizeof(procs[0]), proccompar);

    for (i = 0; i < nprocs; i++) {
        struct ioarg *arg;

        printf("@defun %s ", procs[i].hlist[0]);
        for (arg = procs[i].iargs; arg; arg = arg->next) {
            if (arg->next)
                printf("%s, ", arg->hlist[0]);
            else
                printf("%s", arg->hlist[0]);
        }
        printf("\n%s--@strong{%s}", procs[i].hlist[2], procs[i].hlist[6]);
        if (procs[i].iargs) {
            puts("\n\n@strong{Inputs}\n@itemize @bullet");
            for (arg = procs[i].iargs; arg; arg = arg->next) {
                arg->hlist[2][0] = toupper(arg->hlist[2][0]);
                printf("@item @emph{%s} (%s)--%s\n", arg->hlist[0],
                       arg->hlist[1], arg->hlist[2]);
            }
            puts("@end itemize");
        }
        if (procs[i].oargs) {
            puts("\n\n@strong{Outputs}\n@itemize @bullet");
            for (arg = procs[i].oargs; arg; arg = arg->next) {
                arg->hlist[2][0] = toupper(arg->hlist[2][0]);
                printf("@item @emph{%s} (%s)--%s\n", arg->hlist[0],
                       arg->hlist[1], arg->hlist[2]);
            }
            puts("@end itemize");
        }
        printf("@end defun\n@emph{%s}\n\n", procs[i].hlist[3]);
    }

    return 0;
}
示例#16
0
int main(int argc, char **argv) {
    int pi[2], pid,primero,termina,no_mas;
    long n;
    char *p, *fin, *ps, s2[BUFSIZ],s[BUFSIZ],nombre[250],st[250],text[70000],tit[1500],tit2[1500],tit0[1500], arg_nombre[250];
    char resp_trabajo[100],nom_a_buscar[100] ,trabajo[100];
    FILE *fp;
    int i,seguir;
    char text1[BUFSIZ],s1[BUFSIZ], *fin1, *ar_preg[500], preguntas[70000], *ar_resp[500];
    char *ar_correctas[500];

    FILE *fp1;
// recibir nombre por dialogo
    if(pipe(pi)==-1) {
        puts("error en pipe");
        exit(1);
    }
    pid=fork();
    if(pid==-1) {
        puts("error en fork");
        exit(1);
    }
    if(pid==0) {
        close(pi[0]);
        dup2(pi[1],1);
        *st='\0';
        execlp("/usr/local/bin/greq","/usr/local/bin/greq","-t",
               "Confirmas? ",
               "-eNombre del TTrabajo",
               "-eTrabajo del alumno/a",
               NULL);
        printf("EEEEEEEEEEEEEEEEEEEEEEEEEE\n");
    }
    close(pi[1]);
    s2[0]='\0';
    n=read(pi[0],s2,BUFSIZ);
    s2[n]='\0';
    if(*s2=='\0')
        exit(1);
    strcpy(resp_trabajo,"resp_");
    p=strchr(s2,'\v');
    *p='\0';
    strcat(resp_trabajo,s2);
    strcpy(nombre,p+1);

    strcpy(arg_nombre,"a=");
    strcat(arg_nombre,nombre);
    if(pipe(pi)==-1) {
        puts("error en pipe");
        exit(1);
    }
    pid=fork();
    if(pid==-1) {
        puts("error en fork");
        exit(1);
    }
    if(pid==0) {
        close(pi[0]);
        dup2(pi[1],1);
        sprintf(st,"-d%s",p);
        execlp("/usr/bin/awk","/usr/bin/awk","-f","muestra.awk",
               arg_nombre,resp_trabajo,NULL);
        printf("EEEEEEEEEEEEEEEEEEEEEEEEEE\n");
    }
    close(pi[1]);
    s2[0]='\0';
    n=read(pi[0],s2,BUFSIZ);
    printf("%s\n",s2);



//
    //generar_preguntas_resp(ar_preg,ar_resp,preguntas,ar_correctas);

    if(pipe(pi)==-1) {
        puts("error en pipe");
        exit(1);
    }
    pid=fork();
    if(pid==-1) {
        puts("error en fork");
        exit(1);
    }
    if(pid==0) {
        close(pi[0]);
        dup2(pi[1],1);
        sprintf(tit,"%s","Respuestas");
        sprintf(tit2,"%s%80s %s %80s","-X","Respuestas de:",nombre," ");
        sprintf(tit0,"%s%80s %85s","-X","Preguntas"," ");
        execlp("/usr/local/bin/greq","/usr/local/bin/greq","-t",tit,
               tit2,"-z",s2,NULL);
        //"-X","-z",preguntas,NULL);
        puts("no ejecuto exec");
    }

    close(pi[1]);
    s2[0]='\0';
    n=read(pi[0],s2,BUFSIZ);
    s2[n]='\0';
    //if(*s2=='\0')
    //exit(1);
    wait(&termina);
    if((termina>>8)==1) // ha cancelado
    {
        exit(1);
    }
    printf("SALGO\n");
    exit(1);
    fp=fopen(resp_trabajo,"r");
    if(fp==NULL) {
        puts("No puedo abrir file");
        exit(1);
    }
    i=0;
    while(fin=fgets(s,BUFSIZ,fp)) {
        if(*s=='\n')
            break;
    }
}
示例#17
0
struct bi_record *
decompress_kernel(unsigned long load_addr, int num_words, unsigned long cksum)
{
#ifdef INTERACTIVE_CONSOLE
	int timer = 0;
	char ch;
#endif
	char *cp;
	struct bi_record *rec;
	unsigned long rec_loc, initrd_loc, TotalMemory = 0;

	serial_fixups();
	com_port = serial_init(0, NULL);

#ifdef CONFIG_LOPEC
	/*
	 * This should work on any board with an MPC10X which is properly
	 * initalized.
	 */
	TotalMemory = mpc10x_get_mem_size(MPC10X_MEM_MAP_B);
#endif

	/* assume the chunk below 8M is free */
	end_avail = (char *)0x00800000;

	/*
	 * Reveal where we were loaded at and where we
	 * were relocated to.
	 */
	puts("loaded at:     "); puthex(load_addr);
	puts(" "); puthex((unsigned long)(load_addr + (4*num_words)));
	puts("\n");
	if ( (unsigned long)load_addr != (unsigned long)&start )
	{
		puts("relocated to:  "); puthex((unsigned long)&start);
		puts(" ");
		puthex((unsigned long)((unsigned long)&start + (4*num_words)));
		puts("\n");
	}

	/*
	 * We link ourself to 0x00800000.  When we run, we relocate
	 * ourselves there.  So we just need __image_begin for the
	 * start. -- Tom
	 */
	zimage_start = (char *)(unsigned long)(&__image_begin);
	zimage_size = (unsigned long)(&__image_end) -
			(unsigned long)(&__image_begin);

	initrd_size = (unsigned long)(&__ramdisk_end) -
		(unsigned long)(&__ramdisk_begin);

	/*
	 * The zImage and initrd will be between start and _end, so they've
	 * already been moved once.  We're good to go now. -- Tom
	 */
	avail_ram = (char *)PAGE_ALIGN((unsigned long)_end);
	puts("zimage at:     "); puthex((unsigned long)zimage_start);
	puts(" "); puthex((unsigned long)(zimage_size+zimage_start));
	puts("\n");

	if ( initrd_size ) {
		puts("initrd at:     ");
		puthex((unsigned long)(&__ramdisk_begin));
		puts(" "); puthex((unsigned long)(&__ramdisk_end));puts("\n");
	}

	avail_ram = (char *)0x00400000;
	end_avail = (char *)0x00800000;
	puts("avail ram:     "); puthex((unsigned long)avail_ram); puts(" ");
	puthex((unsigned long)end_avail); puts("\n");

	if (keyb_present)
		CRT_tstc();  /* Forces keyboard to be initialized */
#ifdef CONFIG_GEMINI
	/*
	 * If cmd_line is empty and cmd_preset is not, copy cmd_preset
	 * to cmd_line.  This way we can override cmd_preset with the
	 * command line from Smon.
	 */

	if ( (cmd_line[0] == '\0') && (cmd_preset[0] != '\0'))
		memcpy (cmd_line, cmd_preset, sizeof(cmd_preset));
#endif

	/* Display standard Linux/PPC boot prompt for kernel args */
	puts("\nLinux/PPC load: ");
	cp = cmd_line;
	memcpy (cmd_line, cmd_preset, sizeof(cmd_preset));
	while ( *cp ) putc(*cp++);

#ifdef INTERACTIVE_CONSOLE
	/*
	 * If they have a console, allow them to edit the command line.
	 * Otherwise, don't bother wasting the five seconds.
	 */
	while (timer++ < 5*1000) {
		if (tstc()) {
			while ((ch = getc()) != '\n' && ch != '\r') {
				/* Test for backspace/delete */
				if (ch == '\b' || ch == '\177') {
					if (cp != cmd_line) {
						cp--;
						puts("\b \b");
					}
				/* Test for ^x/^u (and wipe the line) */
				} else if (ch == '\030' || ch == '\025') {
					while (cp != cmd_line) {
						cp--;
						puts("\b \b");
					}
				} else {
					*cp++ = ch;
					putc(ch);
				}
			}
			break;  /* Exit 'timer' loop */
		}
		udelay(1000);  /* 1 msec */
	}
	*cp = 0;
#endif
	puts("\n");

	puts("Uncompressing Linux...");
	gunzip(0, 0x400000, zimage_start, &zimage_size);
	puts("done.\n");

	/*
	 * Create bi_recs for cmd_line and initrds
	 */
	rec_loc = _ALIGN((unsigned long)(zimage_size) +
			(1 << 20) - 1, (1 << 20));
	rec = (struct bi_record *)rec_loc;

	/* We need to make sure that the initrd and bi_recs do not
	 * overlap. */
	if ( initrd_size ) {
		initrd_loc = (unsigned long)(&__ramdisk_begin);
		/* If the bi_recs are in the middle of the current
		 * initrd, move the initrd to the next MB
		 * boundary. */
		if ((rec_loc > initrd_loc) &&
				((initrd_loc + initrd_size) > rec_loc)) {
			initrd_loc = _ALIGN((unsigned long)(zimage_size)
					+ (2 << 20) - 1, (2 << 20));
		 	memmove((void *)initrd_loc, &__ramdisk_begin,
				 initrd_size);
	         	puts("initrd moved:  "); puthex(initrd_loc);
		 	puts(" "); puthex(initrd_loc + initrd_size);
		 	puts("\n");
		}
	}
 
	rec->tag = BI_FIRST;
	rec->size = sizeof(struct bi_record);
	rec = (struct bi_record *)((unsigned long)rec + rec->size);

	if ( TotalMemory ) {
		rec->tag = BI_MEMSIZE;
		rec->data[0] = TotalMemory;
		rec->size = sizeof(struct bi_record) + sizeof(unsigned long);
		rec = (struct bi_record *)((unsigned long)rec + rec->size);
	}

	rec->tag = BI_CMD_LINE;
	memcpy( (char *)rec->data, cmd_line, strlen(cmd_line)+1);
	rec->size = sizeof(struct bi_record) + strlen(cmd_line) + 1;
	rec = (struct bi_record *)((unsigned long)rec + rec->size);

	if ( initrd_size ) {
		rec->tag = BI_INITRD;
		rec->data[0] = initrd_loc;
		rec->data[1] = initrd_size;
		rec->size = sizeof(struct bi_record) + 2 *
			sizeof(unsigned long);
		rec = (struct bi_record *)((unsigned long)rec +
				rec->size);
	}

	rec->tag = BI_LAST;
	rec->size = sizeof(struct bi_record);
	rec = (struct bi_record *)((unsigned long)rec + rec->size);
	puts("Now booting the kernel\n");
	serial_close(com_port);

	return (struct bi_record *)rec_loc;
}
示例#18
0
void print_task (task_t* task) {
  puts("task");
  printf ("  b = %lld\n  length = %d\n", task->b, task->length);
  print_items (task->length, task->items);
}
示例#19
0
文件: iogen.c 项目: adolg/worldots
static
enum HT_FR
print_inv_nine (void)
/*@globals fileSystem, stdout, errno, internalState@*/
/*@modifies fileSystem, stdout, errno, internalState@*/
{
	int r		= 0;
	int random	= 1 + (int)(9.0 * (rand() / (RAND_MAX + 1.0)));
	if (1 == random)
	{
		r = r < 0 ? r : puts("Þar munu eftir");
		r = r < 0 ? r : puts("undrsamligar");
		r = r < 0 ? r : puts("gullnar tǫflur");
		r = r < 0 ? r : puts("í grasi finnask,");
		r = r < 0 ? r : puts("þærs í árdaga");
		r = r < 0 ? r : puts("áttar hǫfðu.");
		/*
		 * Där skola åter
		 * de underbara
		 * guldbrädspelsbrickorna
		 * i gräset hittas,
		 * som i tidens morgon
		 * dem tillhört hade.
		 */
	}
	else if (2 == random)
	{
		r = r < 0 ? r : puts("Tefldu í túni,");
		r = r < 0 ? r : puts("teitir váru,");
		r = r < 0 ? r : puts("var þeim vettergis");
		r = r < 0 ? r : puts("vant ór gulli,");
		r = r < 0 ? r : puts("uns þrjár kvámu");
		r = r < 0 ? r : puts("þursa meyjar");
		r = r < 0 ? r : puts("ámáttkar mjǫk");
		r = r < 0 ? r : puts("ór Jǫtunheimum.");
		/*
		 * På gården med brädspel
		 * de glada lekte,
		 * armod på guld
		 * fanns ingalunda,
		 * tills tursamöar
		 * trenne kommo,
		 * mycket mäktiga
		 * mör, från jättevärlden.
		 */
	}
	else if (3 == random)
	{
		r = r < 0 ? r : puts("Tafl emk ǫrr at efla,");
		r = r < 0 ? r : puts("íþróttir kank níu,");
		r = r < 0 ? r : puts("týnik trauðla rúnum,");
		r = r < 0 ? r : puts("tíð er bók ok smíðir,");
		r = r < 0 ? r : puts("skríða kank á skíðum,");
		r = r < 0 ? r : puts("skýtk ok rœk, svát nýtir;");
		r = r < 0 ? r : puts("hvártveggja kank hyggja:");
		r = r < 0 ? r : puts("harpslótt ok bragþóttu.");
		/*
		 * I can play at tafl,
		 * nine skills I know
		 * rarely forget I the runes,
		 * I know of books and smithing,
		 * I know how to slide on skis,
		 * shoot and row, well enough;
		 * each of two arts I know,
		 * harp-playing and speaking poetry.
		 */
	}
	else if (4 == random)
	{
		r = r < 0 ? r : puts("Burr var inn ellsti,");
		r = r < 0 ? r : puts("en Barn annat,");
		r = r < 0 ? r : puts("Jóð ok Aðal,");
		r = r < 0 ? r : puts("Arfi, Mǫgr,");
		r = r < 0 ? r : puts("Niðr ok Niðjungr,");
		r = r < 0 ? r : puts("- námu leika, -");
		r = r < 0 ? r : puts("Sonr ok Sveinn,");
		r = r < 0 ? r : puts("- sund ok tafl, -");
		r = r < 0 ? r : puts("Kundr hét enn,");
		r = r < 0 ? r : puts("Konr var inn yngsti.");
		/*
		 * Bur var den äldste,
		 * och Barn den andre,
		 * Jod och Adal,
		 * Arve, Mog;
		 * lekar Nid
		 * och Nidjung lärde
		 * samt Son och Sven
		 * simning och brädspel;
		 * Kund hette en,
		 * Kon var den yngste.
		 */
	}
	else if (5 == random)
	{
		r = r < 0 ? r : puts("Mjǫk eru reifðir");
		r = r < 0 ? r : puts("rógbirtingar,");
		r = r < 0 ? r : puts("þeirs í Haralds túni");
		r = r < 0 ? r : puts("húnum verpa;");
		r = r < 0 ? r : puts("féi eru þeir gœddir");
		r = r < 0 ? r : puts("ok fǫgrum mækum,");
		r = r < 0 ? r : puts("málmi húnlenzkum");
		r = r < 0 ? r : puts("ok mani austrœnu.");
		/*
		 * I höj grad begaves
		 * de krigere,
		 * som i Haralds gård
		 * leger med brikker;
		 * med gods de begaves
		 * og med blanke sværd,
		 * med hunnisk malm
		 * og østlandske trælkvinder.
		 */
	}
	else if (6 == random)
	{
		r = r < 0 ? r : puts("Gestumblindi mælti:\n");
		r = r < 0 ? r : puts("\"Hverjar eru þær snótir,");
		r = r < 0 ? r : puts("er um sinn dróttin");
		r = r < 0 ? r : puts("vápnlausar vega,");
		r = r < 0 ? r : puts("inar jǫrpu hlífa");
		r = r < 0 ? r : puts("um alla daga,");
		r = r < 0 ? r : puts("en inar fegri frýja?");
		r = r < 0 ? r : puts("Heiðrekr konungr,");
		r = r < 0 ? r : puts("hygg þú at gátu.\"\n");
		r = r < 0 ? r : puts("\"Góð er gáta þín,");
		r = r < 0 ? r : puts("Gestumblindi,");
		r = r < 0 ? r : puts("getit er þeirar:\n");
		r = r < 0 ? r : fputs(
		"Þat er hneftafl. Tǫflur drepast vápnlausar ",	stdout);
		r = r < 0 ? r : puts(
			"um hnefann, ok fylgja honum inar rauðu.\"");
		/*
		 * Da sagde Gest:
		 *
		 * Hvilke ere de Møer,
		 * som vaabenløse
		 * kæmpe om sin Herre?
		 * mod de hvides
		 * vilde Angreb
		 * de sorte ham stedse skjerme.
		 * Raad den Gaade
		 * rigtig, Kong Heidrek.
		 *
		 * Heidrek svarede:
		 *
		 * God er din Gaade,
		 * Gest hin blinde!
		 * gjettet er den:
		 * i damspil de sorte
		 * sin Drot forsvare
		 * mod Anfald af de hvide.
		 */
	}
	else if (7 == random)
	{
		r = r < 0 ? r : puts("Gestumblindi mælti:\n");
		r = r < 0 ? r : puts("\"Hvat er þat dýra,");
		r = r < 0 ? r : puts("er drepr fé manna");
		r = r < 0 ? r : puts("ok er járni kringt útan,");
		r = r < 0 ? r : puts("horn hefir átta,");
		r = r < 0 ? r : puts("en hǫfuð ekki");
		r = r < 0 ? r : puts("ok rennr, sem renna má?");
		r = r < 0 ? r : puts("Heiðrekr konungr,");
		r = r < 0 ? r : puts("hygg þú at gátu.\"\n");
		r = r < 0 ? r : puts("\"Gód er gáta þín,");
		r = r < 0 ? r : puts("Gestumblindi,");
		r = r < 0 ? r : puts("getit er þeirar:\n");
		r = r < 0 ? r : fputs(
		"Þat er húnn í hneftafli; hann heitir som ",	stdout);
		r = r < 0 ? r : puts(
			"bjǫrn; hann rennr, þegar honum er kastat.\"");
		/*
		 * Da sagde Gest:
		 *
		 * Hvilket er det Dyr
		 * som dræber Folks Hjorde,
		 * helt af Jern forhudet?
		 * Otte Horn det har,
		 * men Hoved ikke,
		 * og tæller et talrigt Følge
		 * Raad den Gaade
		 * rigtig, Kong Heidrek.
		 *
		 * Heidrek svarade:
		 *
		 * God er din Gaade,
		 * Gest hin blinde!
		 * gjettet er den:
		 * det er Ræven,
		 * som rovbegjerlig
		 * i Damspil Faarene dræber.
		 */
	}
	else if (8 == random)
	{
		r = r < 0 ? r :
		fputs("Jafnan skemmtu þau Helga sér at tafli ok ",
			stdout);
		r = r < 0 ? r :
		fputs("Gunnlaugr. Lagði hvárt þeira góðan þokka til ",
			stdout);
		r = r < 0 ? r :
		fputs("annars bráðliga, sem raunir bar á síðan. Þau ",
			stdout);
		r = r < 0 ? r : fputs("váru mjǫk jafnaldrar.\n\n",
			stdout);
		r = r < 0 ? r :
		fputs("Helga var svá fǫgr, at þat er sǫgn fróðra ",
			stdout);
		r = r < 0 ? r :
		fputs("manna, at hon hafi fegrst kona verit á Íslandi.",
			stdout);
		r = r < 0 ? r :
		fputs(" Hár hennar var svá mikit, at þat mátti hylja ",
			stdout);
		r = r < 0 ? r :
		fputs("hana alla, ok svá fagrt sem gull barit, ok ",
			stdout);
		r = r < 0 ? r :
		fputs("engi kostr þótti þá þvílíkr sem Helga in fagra ",
			stdout);
		r = r < 0 ? r :
		fputs("í ǫllum Borgarfirði ok víðara annars staðar.\n",
			stdout);
		/*
		 * Gunnlög och Helga muntrade sig tidt och ofta med att
		 * spela tafvel. Mycket snart fattade de godt tycke till
		 * hvarandra; hvilket tiden sedan skulle visa. De voro
		 * nästan jemnåriga. Helga var så fager, att sagokunnige
		 * män sagt, att hon varit Islands skönaste qvinna.
		 * Hennes hår var så ymnigt, att hon dermed kunde hölja
		 * sig helt och hållet, och det var vänt som smidt gull.
		 * Och så godt gifte som Helga den fagra fans ej i hela
		 * Borgarfjärden och vida om kring.
		 */
	}
	else /* if (9 == random) */
	{
		r = r < 0 ? r :
		fputs("En konungs synir sǫfnuðu liði ok fengu lítit ",
			stdout);
		r = r < 0 ? r :
		fputs("lið ok sendu orð Friðþjófi ok báðu hann liðs, ",
			stdout);
		r = r < 0 ? r :
		fputs("en hann sat at tafli, er sendimenn kómu til "
			"hans.\n\n", stdout);
		r = r < 0 ? r :
		fputs("Þeir mæltu: \"Konungar várar sendu þér kvedju ",
			stdout);
		r = r < 0 ? r :
		fputs("ok vildu þiggja liðsinni þitt til orrostu með "
			"sér.\"\n\n", stdout);
		r = r < 0 ? r :
		fputs("Hann svarade engu ok mælti við Bjǫrn: \"Leita ",
			stdout);
		r = r < 0 ? r :
		fputs("ráðs fyrir at tefla, því at tvíkostr er þér á ",
			stdout);
		r = r < 0 ? r :
		fputs("tvá vega,\" sagði hann.\n", stdout);
		/*
		 * Björn och Fritiof sutto båda
		 * vid ett schackbord, skönt att skåda.
		 * Silver var varannan ruta,
		 * och varannan var av guld.
		 *
		 * Då steg Hilding in. "Sitt neder!
		 * Upp i högbänk jag dig leder,
		 * töm ditt horn, och låt mig sluta
		 * spelet, fosterfader huld!"
		 *
		 * Hilding kvad: "Från Beles söner
		 * kommer jag till dig med böner.
		 * Tidningarna äro onde,
		 * och till dig står landets hopp."
		 *
		 * Fritiof kvar: "Tag dig till vara,
		 * Björn, ty nu är kung i fara.
		 * Frälsas kan han med en bonde:
		 * den är gjord att offras upp."
		 */
	}

	return HT_FR_SUCCESS;
}
示例#20
0
int main(void)
{
  double  a1 = 1.0, b1 = -10.5, c1 = 32.0, d1 = -30.0;
  double  x[3];
  double X;
  int     solutions;
  int i;
  unsigned long l = 0x3fed0169L;
  struct int_sqrt q;
  long n = 0;

  /* solve soem cubic functions */
  printf("********* CUBIC FUNCTIONS ***********\n");
  /* should get 3 solutions: 2, 6 & 2.5   */
  SolveCubic(a1, b1, c1, d1, &solutions, x);  
  printf("Solutions:");
  for(i=0;i<solutions;i++)
    printf(" %f",x[i]);
  printf("\n");

  a1 = 1.0; b1 = -4.5; c1 = 17.0; d1 = -30.0;
  /* should get 1 solution: 2.5           */
  SolveCubic(a1, b1, c1, d1, &solutions, x);  
  printf("Solutions:");
  for(i=0;i<solutions;i++)
    printf(" %f",x[i]);
  printf("\n");

  a1 = 1.0; b1 = -3.5; c1 = 22.0; d1 = -31.0;
  SolveCubic(a1, b1, c1, d1, &solutions, x);
  printf("Solutions:");
  for(i=0;i<solutions;i++)
    printf(" %f",x[i]);
  printf("\n");

  a1 = 1.0; b1 = -13.7; c1 = 1.0; d1 = -35.0;
  SolveCubic(a1, b1, c1, d1, &solutions, x);
  printf("Solutions:");
  for(i=0;i<solutions;i++)
    printf(" %f",x[i]);
  printf("\n");

  a1 = 3.0; b1 = 12.34; c1 = 5.0; d1 = 12.0;
  SolveCubic(a1, b1, c1, d1, &solutions, x);
  printf("Solutions:");
  for(i=0;i<solutions;i++)
    printf(" %f",x[i]);
  printf("\n");

  a1 = -8.0; b1 = -67.89; c1 = 6.0; d1 = -23.6;
  SolveCubic(a1, b1, c1, d1, &solutions, x);
  printf("Solutions:");
  for(i=0;i<solutions;i++)
    printf(" %f",x[i]);
  printf("\n");

  a1 = 45.0; b1 = 8.67; c1 = 7.5; d1 = 34.0;
  SolveCubic(a1, b1, c1, d1, &solutions, x);
  printf("Solutions:");
  for(i=0;i<solutions;i++)
    printf(" %f",x[i]);
  printf("\n");

  a1 = -12.0; b1 = -1.7; c1 = 5.3; d1 = 16.0;
  SolveCubic(a1, b1, c1, d1, &solutions, x);
  printf("Solutions:");
  for(i=0;i<solutions;i++)
    printf(" %f",x[i]);
  printf("\n");

  /* Now solve some random equations */
  for(a1=1;a1<10;a1+=1) {
    for(b1=10;b1>0;b1-=.25) {
      for(c1=5;c1<15;c1+=0.61) {
	   for(d1=-1;d1>-5;d1-=.451) {
		SolveCubic(a1, b1, c1, d1, &solutions, x);  
		printf("Solutions:");
		for(i=0;i<solutions;i++)
		  printf(" %f",x[i]);
		printf("\n");
	   }
      }
    }
  }


  printf("********* INTEGER SQR ROOTS ***********\n");
  /* perform some integer square roots */
  for (i = 0; i < 100000; i+=2)
    {
      usqrt(i, &q);
			// remainder differs on some machines
     // printf("sqrt(%3d) = %2d, remainder = %2d\n",
     printf("sqrt(%3d) = %2d\n",
	     i, q.sqrt);
    }
  printf("\n");
  for (l = 0x3fed0169L; l < 0x3fed4169L; l++)
    {
	 usqrt(l, &q);
	 //printf("\nsqrt(%lX) = %X, remainder = %X\n", l, q.sqrt, q.frac);
	 printf("sqrt(%lX) = %X\n", l, q.sqrt);
    }


  printf("********* ANGLE CONVERSION ***********\n");
  /* convert some rads to degrees */
/*   for (X = 0.0; X <= 360.0; X += 1.0) */
  for (X = 0.0; X <= 360.0; X += .001)
    printf("%3.0f degrees = %.12f radians\n", X, deg2rad(X));
  puts("");
/*   for (X = 0.0; X <= (2 * PI + 1e-6); X += (PI / 180)) */
  for (X = 0.0; X <= (2 * PI + 1e-6); X += (PI / 5760))
    printf("%.12f radians = %3.0f degrees\n", X, rad2deg(X));
  
  
  return 0;
}
示例#21
0
int main(int argc, char *argv[])
{
  register uint i,j;
  uint ant,n1,n2,n3;
  uint write_count,update,opt_delete,check2,dupp_keys,found_key;
  int error;
  ulong pos;
  unsigned long key_check;
  uchar record[128],record2[128],record3[128],key[10];
  const char *filename,*filename2;
  HP_INFO *file,*file2;
  HP_SHARE *tmp_share;
  HP_KEYDEF keyinfo[MAX_KEYS];
  HA_KEYSEG keyseg[MAX_KEYS*5];
  HEAP_PTR UNINIT_VAR(position);
  HP_CREATE_INFO hp_create_info;
  CHARSET_INFO *cs= &my_charset_latin1;
  my_bool unused;
  MY_INIT(argv[0]);		/* init my_sys library & pthreads */

  filename= "test2";
  filename2= "test2_2";
  file=file2=0;
  get_options(argc,argv);

  bzero(&hp_create_info, sizeof(hp_create_info));
  hp_create_info.max_table_size= 1024L*1024L;
  hp_create_info.keys= keys;
  hp_create_info.keydef= keyinfo;
  hp_create_info.reclength= reclength;
  hp_create_info.max_records= (ulong) flag*100000L;
  hp_create_info.min_records= (ulong) recant/2;

  write_count=update=opt_delete=0;
  key_check=0;

  keyinfo[0].seg=keyseg;
  keyinfo[0].keysegs=1;
  keyinfo[0].flag= 0;
  keyinfo[0].algorithm= HA_KEY_ALG_HASH;
  keyinfo[0].seg[0].type=HA_KEYTYPE_BINARY;
  keyinfo[0].seg[0].start=0;
  keyinfo[0].seg[0].length=6;
  keyinfo[0].seg[0].null_bit=0;
  keyinfo[0].seg[0].charset=cs;
  keyinfo[1].seg=keyseg+1;
  keyinfo[1].keysegs=2;
  keyinfo[1].flag=0;
  keyinfo[1].algorithm= HA_KEY_ALG_HASH;
  keyinfo[1].seg[0].type=HA_KEYTYPE_BINARY;
  keyinfo[1].seg[0].start=7;
  keyinfo[1].seg[0].length=6;
  keyinfo[1].seg[0].null_bit=0;
  keyinfo[1].seg[0].charset=cs;
  keyinfo[1].seg[1].type=HA_KEYTYPE_TEXT;
  keyinfo[1].seg[1].start=0;			/* key in two parts */
  keyinfo[1].seg[1].length=6;
  keyinfo[1].seg[1].null_bit=0;
  keyinfo[1].seg[1].charset=cs;
  keyinfo[2].seg=keyseg+3;
  keyinfo[2].keysegs=1;
  keyinfo[2].flag=HA_NOSAME;
  keyinfo[2].algorithm= HA_KEY_ALG_HASH;
  keyinfo[2].seg[0].type=HA_KEYTYPE_BINARY;
  keyinfo[2].seg[0].start=12;
  keyinfo[2].seg[0].length=8;
  keyinfo[2].seg[0].null_bit=0;
  keyinfo[2].seg[0].charset=cs;
  keyinfo[3].seg=keyseg+4;
  keyinfo[3].keysegs=1;
  keyinfo[3].flag=HA_NOSAME;
  keyinfo[3].algorithm= HA_KEY_ALG_HASH;
  keyinfo[3].seg[0].type=HA_KEYTYPE_BINARY;
  keyinfo[3].seg[0].start=37;
  keyinfo[3].seg[0].length=1;
  keyinfo[3].seg[0].null_bit=1;
  keyinfo[3].seg[0].null_pos=38;
  keyinfo[3].seg[0].charset=cs;

  bzero((char*) key1,sizeof(key1));
  bzero((char*) key3,sizeof(key3));

  printf("- Creating heap-file\n");
  if (heap_create(filename, &hp_create_info, &tmp_share, &unused) ||
      !(file= heap_open(filename, 2)))
    goto err;
  signal(SIGINT,endprog);

  printf("- Writing records:s\n");
  strmov((char*) record,"          ..... key");

  for (i=0 ; i < recant ; i++)
  {
    n1=rnd(1000); n2=rnd(100); n3=rnd(min(recant*5,MAX_RECORDS));
    make_record(record,n1,n2,n3,"Pos",write_count);

    if (heap_write(file,record))
    {
      if (my_errno != HA_ERR_FOUND_DUPP_KEY || key3[n3] == 0)
      {
	printf("Error: %d in write at record: %d\n",my_errno,i);
	goto err;
      }
      if (verbose) printf("   Double key: %d\n",n3);
    }
    else
    {
      if (key3[n3] == 1)
      {
	printf("Error: Didn't get error when writing second key: '%8d'\n",n3);
	goto err;
      }
      write_count++; key1[n1]++; key3[n3]=1;
      key_check+=n1;
    }
    if (testflag == 1 && heap_check_heap(file,0))
    {
      puts("Heap keys crashed");
      goto err;
    }
  }
  if (testflag == 1)
    goto end;
  if (heap_check_heap(file,0))
  {
    puts("Heap keys crashed");
    goto err;
  }

  printf("- Delete\n");
  for (i=0 ; i < write_count/10 ; i++)
  {
    for (j=rnd(1000)+1 ; j>0 && key1[j] == 0 ; j--) ;
    if (j != 0)
    {
      sprintf((char*) key,"%6d",j);
      if (heap_rkey(file,record,0,key,6, HA_READ_KEY_EXACT))
      {
	printf("can't find key1: \"%s\"\n",(char*) key);
	goto err;
      }
      if (heap_delete(file,record))
      {
	printf("error: %d; can't delete record: \"%s\"\n", my_errno,(char*) record);
	goto err;
      }
      opt_delete++;
      key1[atoi((char*) record+keyinfo[0].seg[0].start)]--;
      key3[atoi((char*) record+keyinfo[2].seg[0].start)]=0;
      key_check-=atoi((char*) record);
      if (testflag == 2 && heap_check_heap(file,0))
      {
	puts("Heap keys crashed");
	goto err;
      }
    }
    else
      puts("Warning: Skipping delete test because no dupplicate keys");
  }
  if (testflag==2) goto end;
  if (heap_check_heap(file,0))
  {
    puts("Heap keys crashed");
    goto err;
  }

  printf("- Update\n");
  for (i=0 ; i < write_count/10 ; i++)
  {
    n1=rnd(1000); n2=rnd(100); n3=rnd(min(recant*2,MAX_RECORDS));
    make_record(record2, n1, n2, n3, "XXX", update);
    if (rnd(2) == 1)
    {
      if (heap_scan_init(file))
	goto err;
      j=rnd(write_count-opt_delete);
      while ((error=heap_scan(file,record) == HA_ERR_RECORD_DELETED) ||
	     (!error && j))
      {
	if (!error)
	  j--;
      }
      if (error)
	goto err;
    }
    else
    {
      for (j=rnd(1000)+1 ; j>0 && key1[j] == 0 ; j--) ;
      if (!key1[j])
	continue;
      sprintf((char*) key,"%6d",j);
      if (heap_rkey(file,record,0,key,6, HA_READ_KEY_EXACT))
      {
	printf("can't find key1: \"%s\"\n",(char*) key);
	goto err;
      }
    }
    if (heap_update(file,record,record2))
    {
      if (my_errno != HA_ERR_FOUND_DUPP_KEY || key3[n3] == 0)
      {
	printf("error: %d; can't update:\nFrom: \"%s\"\nTo:   \"%s\"\n",
	       my_errno,(char*) record, (char*) record2);
	goto err;
      }
      if (verbose)
	printf("Double key when tried to update:\nFrom: \"%s\"\nTo:   \"%s\"\n",
               (char*) record, (char*) record2);
    }
    else
    {
      key1[atoi((char*) record+keyinfo[0].seg[0].start)]--;
      key3[atoi((char*) record+keyinfo[2].seg[0].start)]=0;
      key1[n1]++; key3[n3]=1;
      update++;
      key_check=key_check-atoi((char*) record)+n1;
    }
    if (testflag == 3 && heap_check_heap(file,0))
    {
      puts("Heap keys crashed");
      goto err;
    }
  }
  if (testflag == 3) goto end;
  if (heap_check_heap(file,0))
  {
    puts("Heap keys crashed");
    goto err;
  }

  for (i=999, dupp_keys=found_key=0 ; i>0 ; i--)
  {
    if (key1[i] > dupp_keys) { dupp_keys=key1[i]; found_key=i; }
    sprintf((char*) key,"%6d",found_key);
  }

  if (dupp_keys > 3)
  {
    if (!silent)
      printf("- Read first key - next - delete - next -> last\n");
    DBUG_PRINT("progpos",("first - next - delete - next -> last"));

    if (heap_rkey(file,record,0,key,6, HA_READ_KEY_EXACT))
      goto err;
    if (heap_rnext(file,record3)) goto err;
    if (heap_delete(file,record3)) goto err;
    key_check-=atoi((char*) record3);
    key1[atoi((char*) record+keyinfo[0].seg[0].start)]--;
    key3[atoi((char*) record+keyinfo[2].seg[0].start)]=0;
    opt_delete++;
    ant=2;
    while ((error=heap_rnext(file,record3)) == 0 ||
	   error == HA_ERR_RECORD_DELETED)
      if (! error)
	ant++;
    if (ant != dupp_keys)
    {
      printf("next: I can only find: %d records of %d\n",
	     ant,dupp_keys);
      goto end;
    }
    dupp_keys--;
    if (heap_check_heap(file,0))
    {
      puts("Heap keys crashed");
      goto err;
    }

    if (!silent)
      printf("- Read last key - delete - prev - prev - opt_delete - prev -> first\n");

    if (heap_rlast(file,record3,0)) goto err;
    if (heap_delete(file,record3)) goto err;
    key_check-=atoi((char*) record3);
    key1[atoi((char*) record+keyinfo[0].seg[0].start)]--;
    key3[atoi((char*) record+keyinfo[2].seg[0].start)]=0;
    opt_delete++;
    if (heap_rprev(file,record3) || heap_rprev(file,record3))
      goto err;
    if (heap_delete(file,record3)) goto err;
    key_check-=atoi((char*) record3);
    key1[atoi((char*) record+keyinfo[0].seg[0].start)]--;
    key3[atoi((char*) record+keyinfo[2].seg[0].start)]=0;
    opt_delete++;
    ant=3;
    while ((error=heap_rprev(file,record3)) == 0 ||
	   error == HA_ERR_RECORD_DELETED)
    {
      if (! error)
	ant++;
    }
    if (ant != dupp_keys)
    {
      printf("next: I can only find: %d records of %d\n",
	     ant,dupp_keys);
      goto end;
    }
    dupp_keys-=2;
    if (heap_check_heap(file,0))
    {
      puts("Heap keys crashed");
      goto err;
    }
  }
  else
    puts("Warning: Not enough duplicated keys:  Skipping delete key check");

  if (!silent)
    printf("- Read (first) - next - delete - next -> last\n");
  DBUG_PRINT("progpos",("first - next - delete - next -> last"));

  if (heap_scan_init(file))
    goto err;
  while ((error=heap_scan(file,record3) == HA_ERR_RECORD_DELETED)) ;
  if (error)
    goto err;
  if (heap_delete(file,record3)) goto err;
  key_check-=atoi((char*) record3);
  opt_delete++;
  key1[atoi((char*) record+keyinfo[0].seg[0].start)]--;
  key3[atoi((char*) record+keyinfo[2].seg[0].start)]=0;
  ant=0;
  while ((error=heap_scan(file,record3)) == 0 ||
	 error == HA_ERR_RECORD_DELETED)
    if (! error)
      ant++;
  if (ant != write_count-opt_delete)
  {
    printf("next: Found: %d records of %d\n",ant,write_count-opt_delete);
    goto end;
  }
  if (heap_check_heap(file,0))
  {
    puts("Heap keys crashed");
    goto err;
  }

  puts("- Test if: Read rrnd - same - rkey - same");
  DBUG_PRINT("progpos",("Read rrnd - same"));
  pos=rnd(write_count-opt_delete-5)+5;
  heap_scan_init(file);
  i=5;
  while ((error=heap_scan(file,record)) == HA_ERR_RECORD_DELETED ||
	 (error == 0 && pos))
  {
    if (!error)
      pos--;
    if (i-- == 0)
    {
      bmove(record3,record,reclength);
      position=heap_position(file);
    }
  }
  if (error)
    goto err;
  bmove(record2,record,reclength);
  if (heap_rsame(file,record,-1) || heap_rsame(file,record2,2))
    goto err;
  if (memcmp(record2,record,reclength))
  {
    puts("heap_rsame didn't find right record");
    goto end;
  }

  puts("- Test of read through position");
  if (heap_rrnd(file,record,position))
    goto err;
  if (memcmp(record3,record,reclength))
  {
    puts("heap_frnd didn't find right record");
    goto end;
  }

  printf("- heap_info\n");
  {
    HEAPINFO info;
    heap_info(file,&info,0);
    /* We have to test with opt_delete +1 as this may be the case if the last
       inserted row was a duplicate key */
    if (info.records != write_count-opt_delete ||
	(info.deleted != opt_delete && info.deleted != opt_delete+1))
    {
      puts("Wrong info from heap_info");
      printf("Got: records: %ld(%d)  deleted: %ld(%d)\n",
	     info.records,write_count-opt_delete,info.deleted,opt_delete);
    }
  }

#ifdef OLD_HEAP_VERSION
  {
    uint check;
    printf("- Read through all records with rnd\n");
    if (heap_extra(file,HA_EXTRA_RESET) || heap_extra(file,HA_EXTRA_CACHE))
    {
      puts("got error from heap_extra");
      goto end;
    }
    ant=check=0;
    while ((error=heap_rrnd(file,record,(ulong) -1)) != HA_ERR_END_OF_FILE &&
	   ant < write_count + 10)
    {
      if (!error)
      {
	ant++;
	check+=calc_check(record,reclength);
      }
    }
    if (ant != write_count-opt_delete)
    {
      printf("rrnd: I can only find: %d records of %d\n", ant,
	     write_count-opt_delete);
      goto end;
    }
    if (heap_extra(file,HA_EXTRA_NO_CACHE))
    {
      puts("got error from heap_extra(HA_EXTRA_NO_CACHE)");
      goto end;
    }
  }
#endif

  printf("- Read through all records with scan\n");
  if (heap_reset(file) || heap_extra(file,HA_EXTRA_CACHE))
  {
    puts("got error from heap_extra");
    goto end;
  }
  ant=check2=0;
  heap_scan_init(file);
  while ((error=heap_scan(file,record)) != HA_ERR_END_OF_FILE &&
	 ant < write_count + 10)
  {
    if (!error)
    {
      ant++;
      check2+=calc_check(record,reclength);
    }
  }
  if (ant != write_count-opt_delete)
  {
    printf("scan: I can only find: %d records of %d\n", ant,
	   write_count-opt_delete);
    goto end;
  }
#ifdef OLD_HEAP_VERSION
  if (check != check2)
  {
    puts("scan: Checksum didn't match reading with rrnd");
    goto end;
  }
#endif


  if (heap_extra(file,HA_EXTRA_NO_CACHE))
  {
    puts("got error from heap_extra(HA_EXTRA_NO_CACHE)");
    goto end;
  }

  for (i=999, dupp_keys=found_key=0 ; i>0 ; i--)
  {
    if (key1[i] > dupp_keys) { dupp_keys=key1[i]; found_key=i; }
    sprintf((char*) key,"%6d",found_key);
  }
  printf("- Read through all keys with first-next-last-prev\n");
  ant=0;
  for (error=heap_rkey(file,record,0,key,6, HA_READ_KEY_EXACT);
      ! error ;
       error=heap_rnext(file,record))
    ant++;
  if (ant != dupp_keys)
  {
    printf("first-next: I can only find: %d records of %d\n", ant,
	   dupp_keys);
    goto end;
  }

  ant=0;
  for (error=heap_rlast(file,record,0) ;
      ! error ;
      error=heap_rprev(file,record))
  {
    ant++;
    check2+=calc_check(record,reclength);
  }
  if (ant != dupp_keys)
  {
    printf("last-prev: I can only find: %d records of %d\n", ant,
	   dupp_keys);
    goto end;
  }

  if (testflag == 4) goto end;

  printf("- Reading through all rows through keys\n");
  if (!(file2=heap_open(filename, 2)))
    goto err;
  if (heap_scan_init(file))
    goto err;
  while ((error=heap_scan(file,record)) != HA_ERR_END_OF_FILE)
  {
    if (error == 0)
    {
      if (heap_rkey(file2,record2,2,record+keyinfo[2].seg[0].start,8,
		    HA_READ_KEY_EXACT))
      {
	printf("can't find key3: \"%.8s\"\n",
	       record+keyinfo[2].seg[0].start);
	goto err;
      }
    }
  }
  heap_close(file2);

  printf("- Creating output heap-file 2\n");
  hp_create_info.keys= 1;
  hp_create_info.max_records= 0;
  hp_create_info.min_records= 0;
  if (heap_create(filename2, &hp_create_info, &tmp_share, &unused) ||
      !(file2= heap_open_from_share_and_register(tmp_share, 2)))
    goto err;

  printf("- Copying and removing records\n");
  if (heap_scan_init(file))
    goto err;
  while ((error=heap_scan(file,record)) != HA_ERR_END_OF_FILE)
  {
    if (error == 0)
    {
      if (heap_write(file2,record))
	goto err;
      key_check-=atoi((char*) record);
      write_count++;
      if (heap_delete(file,record))
	goto err;
      opt_delete++;
    }
    pos++;
  }
  printf("- Checking heap tables\n");
  if (heap_check_heap(file,1) || heap_check_heap(file2,1))
  {
    puts("Heap keys crashed");
    goto err;
  }

  if (my_errno != HA_ERR_END_OF_FILE)
    printf("error: %d from heap_rrnd\n",my_errno);
  if (key_check)
    printf("error: Some read got wrong: check is %ld\n",(long) key_check);

end:
  printf("\nFollowing test have been made:\n");
  printf("Write records: %d\nUpdate records: %d\nDelete records: %d\n", write_count,update,opt_delete);
  heap_clear(file);
  if (heap_close(file) || (file2 && heap_close(file2)))
    goto err;
  heap_delete_table(filename2);
  hp_panic(HA_PANIC_CLOSE);
  my_end(MY_GIVE_INFO);
  return(0);
err:
  printf("Got error: %d when using heap-database\n",my_errno);
  (void) heap_close(file);
  return(1);
} /* main */
示例#22
0
/**
 * boot_get_ramdisk - main ramdisk handling routine
 * @argc: command argument count
 * @argv: command argument list
 * @images: pointer to the bootm images structure
 * @arch: expected ramdisk architecture
 * @rd_start: pointer to a ulong variable, will hold ramdisk start address
 * @rd_end: pointer to a ulong variable, will hold ramdisk end
 *
 * boot_get_ramdisk() is responsible for finding a valid ramdisk image.
 * Curently supported are the following ramdisk sources:
 *      - multicomponent kernel/ramdisk image,
 *      - commandline provided address of decicated ramdisk image.
 *
 * returns:
 *     0, if ramdisk image was found and valid, or skiped
 *     rd_start and rd_end are set to ramdisk start/end addresses if
 *     ramdisk image is found and valid
 *
 *     1, if ramdisk image is found but corrupted, or invalid
 *     rd_start and rd_end are set to 0 if no ramdisk exists
 */
int boot_get_ramdisk(int argc, char * const argv[], bootm_headers_t *images,
		uint8_t arch, ulong *rd_start, ulong *rd_end)
{
	ulong rd_addr, rd_load;
	ulong rd_data, rd_len;
	const image_header_t *rd_hdr;
	void *buf;
#ifdef CONFIG_SUPPORT_RAW_INITRD
	char *end;
#endif
#if defined(CONFIG_FIT)
	const char	*fit_uname_config = images->fit_uname_cfg;
	const char	*fit_uname_ramdisk = NULL;
	ulong		default_addr;
	int		rd_noffset;
#endif
	const char *select = NULL;

	*rd_start = 0;
	*rd_end = 0;

	if (argc >= 2)
		select = argv[1];
	/*
	 * Look for a '-' which indicates to ignore the
	 * ramdisk argument
	 */
	if (select && strcmp(select, "-") ==  0) {
		debug("## Skipping init Ramdisk\n");
		rd_len = rd_data = 0;
	} else if (select || genimg_has_config(images)) {
#if defined(CONFIG_FIT)
		if (select) {
			/*
			 * If the init ramdisk comes from the FIT image and
			 * the FIT image address is omitted in the command
			 * line argument, try to use os FIT image address or
			 * default load address.
			 */
			if (images->fit_uname_os)
				default_addr = (ulong)images->fit_hdr_os;
			else
				default_addr = load_addr;

			if (fit_parse_conf(select, default_addr,
					   &rd_addr, &fit_uname_config)) {
				debug("*  ramdisk: config '%s' from image at "
						"0x%08lx\n",
						fit_uname_config, rd_addr);
			} else if (fit_parse_subimage(select, default_addr,
						&rd_addr, &fit_uname_ramdisk)) {
				debug("*  ramdisk: subimage '%s' from image at "
						"0x%08lx\n",
						fit_uname_ramdisk, rd_addr);
			} else
#endif
			{
				rd_addr = simple_strtoul(select, NULL, 16);
				debug("*  ramdisk: cmdline image address = "
						"0x%08lx\n",
						rd_addr);
			}
#if defined(CONFIG_FIT)
		} else {
			/* use FIT configuration provided in first bootm
			 * command argument. If the property is not defined,
			 * quit silently.
			 */
			rd_addr = map_to_sysmem(images->fit_hdr_os);
			rd_noffset = fit_get_node_from_config(images,
					FIT_RAMDISK_PROP, rd_addr);
			if (rd_noffset == -ENOLINK)
				return 0;
			else if (rd_noffset < 0)
				return 1;
		}
#endif

		/* copy from dataflash if needed */
		rd_addr = genimg_get_image(rd_addr);

		/*
		 * Check if there is an initrd image at the
		 * address provided in the second bootm argument
		 * check image type, for FIT images get FIT node.
		 */
		buf = map_sysmem(rd_addr, 0);
		switch (genimg_get_format(buf)) {
		case IMAGE_FORMAT_LEGACY:
			printf("## Loading init Ramdisk from Legacy "
					"Image at %08lx ...\n", rd_addr);

			bootstage_mark(BOOTSTAGE_ID_CHECK_RAMDISK);
			rd_hdr = image_get_ramdisk(rd_addr, arch,
							images->verify);

			if (rd_hdr == NULL)
				return 1;

			rd_data = image_get_data(rd_hdr);
			rd_len = image_get_data_size(rd_hdr);
			rd_load = image_get_load(rd_hdr);
			break;
#if defined(CONFIG_FIT)
		case IMAGE_FORMAT_FIT:
			rd_noffset = fit_image_load(images, FIT_RAMDISK_PROP,
					rd_addr, &fit_uname_ramdisk,
					&fit_uname_config, arch,
					IH_TYPE_RAMDISK,
					BOOTSTAGE_ID_FIT_RD_START,
					FIT_LOAD_IGNORED, &rd_data, &rd_len);
			if (rd_noffset < 0)
				return 1;

			images->fit_hdr_rd = map_sysmem(rd_addr, 0);
			images->fit_uname_rd = fit_uname_ramdisk;
			images->fit_noffset_rd = rd_noffset;
			break;
#endif
		default:
#ifdef CONFIG_SUPPORT_RAW_INITRD
			end = NULL;
			if (select)
				end = strchr(select, ':');
			if (end) {
				rd_len = simple_strtoul(++end, NULL, 16);
				rd_data = rd_addr;
			} else
#endif
			{
				puts("Wrong Ramdisk Image Format\n");
				rd_data = rd_len = rd_load = 0;
				return 1;
			}
		}
	} else if (images->legacy_hdr_valid &&
			image_check_type(&images->legacy_hdr_os_copy,
						IH_TYPE_MULTI)) {

		/*
		 * Now check if we have a legacy mult-component image,
		 * get second entry data start address and len.
		 */
		bootstage_mark(BOOTSTAGE_ID_RAMDISK);
		printf("## Loading init Ramdisk from multi component "
				"Legacy Image at %08lx ...\n",
				(ulong)images->legacy_hdr_os);

		image_multi_getimg(images->legacy_hdr_os, 1, &rd_data, &rd_len);
	} else {
		/*
		 * no initrd image
		 */
		bootstage_mark(BOOTSTAGE_ID_NO_RAMDISK);
		rd_len = rd_data = 0;
	}

	if (!rd_data) {
		debug("## No init Ramdisk\n");
	} else {
		*rd_start = rd_data;
		*rd_end = rd_data + rd_len;
	}
	debug("   ramdisk start = 0x%08lx, ramdisk end = 0x%08lx\n",
			*rd_start, *rd_end);

	return 0;
}
int
au_check_header_valid(int idx, long nbytes)
{
	image_header_t *hdr;
	unsigned long checksum;
	unsigned char buf[4];

	hdr = (image_header_t *)LOAD_ADDR;
#if defined(CONFIG_FIT)
	if (genimg_get_format ((void *)hdr) != IMAGE_FORMAT_LEGACY) {
		puts ("Non legacy image format not supported\n");
		return -1;
	}
#endif

	/* check the easy ones first */
#undef CHECK_VALID_DEBUG
#ifdef CHECK_VALID_DEBUG
	printf("magic %#x %#x ", image_get_magic (hdr), IH_MAGIC);
	printf("arch %#x %#x ", image_get_arch (hdr), IH_ARCH_ARM);
	printf("size %#x %#lx ", image_get_data_size (hdr), nbytes);
	printf("type %#x %#x ", image_get_type (hdr), IH_TYPE_KERNEL);
#endif
	if (nbytes < image_get_header_size ()) {
		printf ("Image %s bad header SIZE\n", aufile[idx]);
		return -1;
	}
	if (!image_check_magic (hdr) || !image_check_arch (hdr, IH_ARCH_ARM)) {
		printf ("Image %s bad MAGIC or ARCH\n", aufile[idx]);
		return -1;
	}
	/* check the hdr CRC */
	if (!image_check_hcrc (hdr)) {
		printf ("Image %s bad header checksum\n", aufile[idx]);
		return -1;
	}
	/* check the type - could do this all in one gigantic if() */
	if ((idx == IDX_FIRMWARE) &&
		!image_check_type (hdr, IH_TYPE_FIRMWARE)) {
		printf ("Image %s wrong type\n", aufile[idx]);
		return -1;
	}
	if ((idx == IDX_KERNEL) && !image_check_type (hdr, IH_TYPE_KERNEL)) {
		printf ("Image %s wrong type\n", aufile[idx]);
		return -1;
	}
	if ((idx == IDX_DISK) && !image_check_type (hdr, IH_TYPE_FILESYSTEM)) {
		printf ("Image %s wrong type\n", aufile[idx]);
		return -1;
	}
	if ((idx == IDX_APP) && !image_check_type (hdr, IH_TYPE_RAMDISK)
		&& !image_check_type (hdr, IH_TYPE_FILESYSTEM)) {
		printf ("Image %s wrong type\n", aufile[idx]);
		return -1;
	}
	if ((idx == IDX_PREPARE || idx == IDX_PREINST || idx == IDX_POSTINST)
		&& !image_check_type (hdr, IH_TYPE_SCRIPT)) {
		printf ("Image %s wrong type\n", aufile[idx]);
		return -1;
	}
	/* special case for prepare.img */
	if (idx == IDX_PREPARE)
		return 0;
	/* recycle checksum */
	checksum = image_get_data_size (hdr);
	/* for kernel and app the image header must also fit into flash */
	if ((idx != IDX_DISK) && (idx != IDX_FIRMWARE))
		checksum += image_get_header_size ();
	/* check the size does not exceed space in flash. HUSH scripts */
	/* all have ausize[] set to 0 */
	if ((ausize[idx] != 0) && (ausize[idx] < checksum)) {
		printf ("Image %s is bigger than FLASH\n", aufile[idx]);
		return -1;
	}
	/* check the time stamp from the EEPROM */
	/* read it in */
	i2c_read_multiple(0x54, auee_off[idx].time, 1, buf, sizeof(buf));
#ifdef CHECK_VALID_DEBUG
	printf ("buf[0] %#x buf[1] %#x buf[2] %#x buf[3] %#x "
		"as int %#x time %#x\n",
		buf[0], buf[1], buf[2], buf[3],
		*((unsigned int *)buf), image_get_time (hdr));
#endif
	/* check it */
	if (*((unsigned int *)buf) >= image_get_time (hdr)) {
		printf ("Image %s is too old\n", aufile[idx]);
		return -1;
	}

	return 0;
}
示例#24
0
/**
 * boot_ramdisk_high - relocate init ramdisk
 * @lmb: pointer to lmb handle, will be used for memory mgmt
 * @rd_data: ramdisk data start address
 * @rd_len: ramdisk data length
 * @initrd_start: pointer to a ulong variable, will hold final init ramdisk
 *      start address (after possible relocation)
 * @initrd_end: pointer to a ulong variable, will hold final init ramdisk
 *      end address (after possible relocation)
 *
 * boot_ramdisk_high() takes a relocation hint from "initrd_high" environement
 * variable and if requested ramdisk data is moved to a specified location.
 *
 * Initrd_start and initrd_end are set to final (after relocation) ramdisk
 * start/end addresses if ramdisk image start and len were provided,
 * otherwise set initrd_start and initrd_end set to zeros.
 *
 * returns:
 *      0 - success
 *     -1 - failure
 */
int boot_ramdisk_high(struct lmb *lmb, ulong rd_data, ulong rd_len,
		  ulong *initrd_start, ulong *initrd_end)
{
	char	*s;
	ulong	initrd_high;
	int	initrd_copy_to_ram = 1;

	if ((s = getenv("initrd_high")) != NULL) {
		/* a value of "no" or a similar string will act like 0,
		 * turning the "load high" feature off. This is intentional.
		 */
		initrd_high = simple_strtoul(s, NULL, 16);
		if (initrd_high == ~0)
			initrd_copy_to_ram = 0;
	} else {
		/* not set, no restrictions to load high */
		initrd_high = ~0;
	}


#ifdef CONFIG_LOGBUFFER
	/* Prevent initrd from overwriting logbuffer */
	lmb_reserve(lmb, logbuffer_base() - LOGBUFF_OVERHEAD, LOGBUFF_RESERVE);
#endif

	debug("## initrd_high = 0x%08lx, copy_to_ram = %d\n",
			initrd_high, initrd_copy_to_ram);

	if (rd_data) {
		if (!initrd_copy_to_ram) {	/* zero-copy ramdisk support */
			debug("   in-place initrd\n");
			*initrd_start = rd_data;
			*initrd_end = rd_data + rd_len;
			lmb_reserve(lmb, rd_data, rd_len);
		} else {
			if (initrd_high)
				*initrd_start = (ulong)lmb_alloc_base(lmb,
						rd_len, 0x1000, initrd_high);
			else
				*initrd_start = (ulong)lmb_alloc(lmb, rd_len,
								 0x1000);

			if (*initrd_start == 0) {
				puts("ramdisk - allocation error\n");
				goto error;
			}
			bootstage_mark(BOOTSTAGE_ID_COPY_RAMDISK);

			*initrd_end = *initrd_start + rd_len;
			printf("   Loading Ramdisk to %08lx, end %08lx ... ",
					*initrd_start, *initrd_end);

			memmove_wd((void *)*initrd_start,
					(void *)rd_data, rd_len, CHUNKSZ);

#ifdef CONFIG_MP
			/*
			 * Ensure the image is flushed to memory to handle
			 * AMP boot scenarios in which we might not be
			 * HW cache coherent
			 */
			flush_cache((unsigned long)*initrd_start, rd_len);
#endif
			puts("OK\n");
		}
	} else {
		*initrd_start = 0;
		*initrd_end = 0;
	}
	debug("   ramdisk load start = 0x%08lx, ramdisk load end = 0x%08lx\n",
			*initrd_start, *initrd_end);

	return 0;

error:
	return -1;
}
示例#25
0
static int
check_gpt_label(void)
{
	struct partition *first = pt_offset(MBRbuffer, 0);
	struct pte pe;
	uint32_t crc;

	/* LBA 0 contains the legacy MBR */

	if (!valid_part_table_flag(MBRbuffer)
	 || first->sys_ind != LEGACY_GPT_TYPE
	) {
		current_label_type = 0;
		return 0;
	}

	/* LBA 1 contains the GPT header */

	read_pte(&pe, 1);
	gpt_hdr = (void *)pe.sectorbuffer;

	if (gpt_hdr->magic != SWAP_LE64(GPT_MAGIC)) {
		current_label_type = 0;
		return 0;
	}

	if (!global_crc32_table) {
		global_crc32_table = crc32_filltable(NULL, 0);
	}

	crc = SWAP_LE32(gpt_hdr->hdr_crc32);
	gpt_hdr->hdr_crc32 = 0;
	if (gpt_crc32(gpt_hdr, SWAP_LE32(gpt_hdr->hdr_size)) != crc) {
		/* FIXME: read the backup table */
		puts("\nwarning: GPT header CRC is invalid\n");
	}

	n_parts = SWAP_LE32(gpt_hdr->n_parts);
	part_entry_len = SWAP_LE32(gpt_hdr->part_entry_len);
	if (n_parts > GPT_MAX_PARTS
	 || part_entry_len > GPT_MAX_PART_ENTRY_LEN
	 || SWAP_LE32(gpt_hdr->hdr_size) > sector_size
	) {
		puts("\nwarning: unable to parse GPT disklabel\n");
		current_label_type = 0;
		return 0;
	}

	part_array_len = n_parts * part_entry_len;
	part_array = xmalloc(part_array_len);
	seek_sector(SWAP_LE64(gpt_hdr->first_part_lba));
	if (full_read(dev_fd, part_array, part_array_len) != part_array_len) {
		fdisk_fatal(unable_to_read);
	}

	if (gpt_crc32(part_array, part_array_len) != gpt_hdr->part_array_crc32) {
		/* FIXME: read the backup table */
		puts("\nwarning: GPT array CRC is invalid\n");
	}

	puts("Found valid GPT with protective MBR; using GPT\n");

	current_label_type = LABEL_GPT;
	return 1;
}
示例#26
0
int main( int argc, char *argv[])
{
  Arb_connection *conn = NULL;
  int rc;
  int i;

  char server[128];
  char database[128];		/* schema */
  char user[128];
  char password[128];
  char application[128];
  char infile[256];
  Widget widgets[WIDGET_ARRSZ];
  short  iind[WIDGET_ARRSZ][MAX_TBL_COLS];
  
  memset( widgets, 0, sizeof(widgets));
  memset( iind, 0, sizeof(iind));


  get_env_param( argc, argv, 0, server, database, user, password);

  strcpy( application, __FILE__);

#if 0
  printf( "server   = '%s'\n"
	  "database = '%s'\n"
	  "user     = '******'\n"
	  "password = '******'\n"
	  "application = '%s'\n",
	  server, database, user, password, application);
#endif


  init_DLAYER_THREAD();
  rc = arb_database_login( server, database, user, password, application,
			   ALLOW_BCP, &conn);


  if( rc == SUCCESS)
    puts( "Login successful.");
  else
    {
      puts( "Login failed.");
      exit(1);
    }

  rc = arb_enable_logging( "widget1.log");
  if( rc == SUCCESS)
    puts( "Logging enabled.");
  else
    puts( "Logging failed."), abort();



  drop_table( conn, TABLENAME);
  create_testcols_table( conn);
  create_insert_procedure( conn);
  init_Widgets( widgets);


  populate_table( conn, widgets);
  arb_close(conn,1);

  exit_DLAYER_THREAD();

  return 0;
}
示例#27
0
void gWindow::debug() {
	printf("---- window stack (id=%d): ----\n", getId());
	for (unsigned i=0; i<subWindows.size; i++)
		printf("[gWindow] %p (id=%d)\n", (void*)subWindows.at(i), subWindows.at(i)->getId());
	puts("----");
}
示例#28
0
void maxcoinMiner_openCL_generateOrUpdateKernel()
{
	if( maxcoinOpenCLKernelInited )
		return;
	maxcoinOpenCLKernelInited = true;
	printf("Compiling OpenCL kernel...\n");

	char* kernel_src = (char*)malloc(1024*512);
	strcpy(kernel_src, "");

	cl_int clerr = 0;
	// init input buffer
	maxcoinGPU.buffer_blockInputData = malloc(80+8); // endian swapped block data + share target attached at the end
	memset(maxcoinGPU.buffer_blockInputData, 0x00, 80+8);
	maxcoinGPU.clBuffer_blockInputData = clCreateBuffer(openCL_getActiveContext(), CL_MEM_READ_WRITE, 88, maxcoinGPU.buffer_blockInputData, &clerr);
	// init output buffer
	sint32 outputBlocks = 256;
	maxcoinGPU.buffer_nonceOutputData = malloc(outputBlocks*4*sizeof(uint32));
	memset(maxcoinGPU.buffer_nonceOutputData, 0x00, outputBlocks*4*sizeof(uint32));
	maxcoinGPU.clBuffer_nonceOutputData = clCreateBuffer(openCL_getActiveContext(), CL_MEM_READ_WRITE, outputBlocks*4*sizeof(uint32), maxcoinGPU.buffer_nonceOutputData, &clerr);

	maxcoinMiner_openCL_appendKeccakFunction(kernel_src);

	strcat(kernel_src, "__kernel void xptMiner_cl_maxcoin_keccak(__global unsigned long *blockData, __global unsigned int *nonceIndexOut)\r\n");
	strcat(kernel_src, "{\r\n");

	strcat(kernel_src, 
	"unsigned long nonceAndBits = blockData[9] & 0x00000000FFFFFFFF;\r\n"
	"unsigned long shareTarget = blockData[10];\r\n"
	"nonceIndexOut[get_local_id(0)] = 0xFFFFFFFF;\r\n"

	"nonceAndBits += 0x100000000UL*0x1000UL*(unsigned long)get_local_id(0);\r\n"
	
	//"nonceAndBits = 0x01f94bdb00000000UL;\r\n"

	"for(int i=0; i<0x1000; i++) {\r\n"
	//"for(int i=0; i<1; i++) {\r\n"
	//"if( keccak256_maxcoin_opt_v(blockData, nonceAndBits) < shareTarget ) nonceIndexOut[0] = nonceAndBits>>32;\r\n"
	"if( keccak256_maxcoin_opt_v(blockData, nonceAndBits) < 0x0040000000000000UL ) nonceIndexOut[get_local_id(0)] = nonceAndBits>>32;\r\n"
	"nonceAndBits += 0x100000000UL;\r\n"
	"}\r\n");

	strcat(kernel_src, "}\r\n");

	const char* source = kernel_src;
	size_t src_size = strlen(kernel_src);
	cl_program program = clCreateProgramWithSource(openCL_getActiveContext(), 1, &source, &src_size, &clerr);
	if(clerr != CL_SUCCESS)
		printf("Error creating OpenCL program\n");
	// builds the program
	clerr = clBuildProgram(program, 1, openCL_getActiveDeviceID(), NULL, NULL, NULL);
	if(clerr != CL_SUCCESS)
		printf("Error compiling OpenCL program\n");
	// shows the log
	char* build_log;
	size_t log_size;
	// First call to know the proper size
	clGetProgramBuildInfo(program, *openCL_getActiveDeviceID(), CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);
	build_log = (char*)malloc(log_size+1);
	memset(build_log, 0x00, log_size+1);
	// Second call to get the log
	clGetProgramBuildInfo(program, *openCL_getActiveDeviceID(), CL_PROGRAM_BUILD_LOG, log_size, build_log, NULL);
	build_log[log_size] = '\0';
	puts(build_log);
	free(build_log);

	maxcoinGPU.kernel_keccak = clCreateKernel(program, "xptMiner_cl_maxcoin_keccak", &clerr);

	clerr = clSetKernelArg(maxcoinGPU.kernel_keccak, 0, sizeof(cl_mem), &maxcoinGPU.clBuffer_blockInputData);
	clerr = clSetKernelArg(maxcoinGPU.kernel_keccak, 1, sizeof(cl_mem), &maxcoinGPU.clBuffer_nonceOutputData);

	free(kernel_src);
}
示例#29
0
void client_init(){
    int sockfd, portno, n;
    struct sockaddr_in serveraddr;
    struct hostent *server;
    char *hostname = serv_ip;
    char buf[BUFSIZE];
    char server_reply[50];

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) 
        error("ERROR opening socket");

    setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));

    server = gethostbyname(hostname);
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host as %s\n", hostname);
        exit(0);
    }

    bzero((char *) &serveraddr, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, 
    (char *)&serveraddr.sin_addr.s_addr, server->h_length);
    serveraddr.sin_port = htons(PORT);

    if (connect(sockfd, &serveraddr, sizeof(serveraddr)) < 0) 
      error("ERROR connecting");

    if(read(sockfd, server_reply , BUFSIZE) < 0){
        printf("recv failed\n");
      }
    else{
      printf("TCP connection established\n");
      printf("%s\n", server_reply);
    }
    if(read(sockfd, server_reply , BUFSIZE) < 0){
        printf("recv failed\n");
    }
    else{ //Gets client ID from master
      my_ID = atoi(server_reply);
      printf("My ID is: %d\n", my_ID);
    }

    pthread_t client_thread1,elev_thread,button_thread;

    master_socket = malloc(1);
    *master_socket = sockfd;

    pthread_create(&client_thread1, NULL, tcp_recieve, (void*) master_socket);
    pthread_create(&elev_thread, NULL, elevator_control, NULL);
    pthread_create(&button_thread, NULL, button_check, NULL);
    
    pthread_join(client_thread1, NULL);
    puts("TCP Recieve killed");
    pthread_join(elev_thread,NULL);
    puts("Elevator Thread Killed");
    pthread_join(button_thread, NULL);
    puts("Button Check Thread Killed");
    close(sockfd);

    //If connections is lost to master, clients with lowest ID's tries to initialize first
    if(my_ID == 0){
      connection_init();
    }
    else if(my_ID == 1){
      sleep(5);
      connection_init();
    }
    else if(my_ID = 2){
      sleep(10);
      connection_init();
    }
}
示例#30
0
void
DmxMsg::display (void)
{
    DtMailEnv			env;
    boolean_t		FirstIsText = B_FALSE;
    DtMail::BodyPart	*firstPart = NULL, *nextpart = NULL;
    char			*type;
    char			*description = NULL;
    char			*sunDataDescription = NULL;
    char			*name = NULL;
    void * contents = NULL;
    unsigned long length = 0;
    int mode = 0;
    char *buf = NULL;
// For CHARSET
    char *mime_cs = NULL, *from_cs = NULL, *to_cs = NULL;
    char *v3_cs = new char [64];

    if (cachedValues != B_TRUE)
        parse ();	// read in body part info

    firstPart = bodyParts [0];

    firstPart->getContents(env,
                           (const void **) &contents,
                           &length,
                           NULL,	//type
                           NULL,	//name
                           NULL,	//mode
                           NULL);	//description

    if (handleError (env, "getContents") == B_TRUE)
        exit (1);

// For CHARSET

    DtMailValueSeq value;
    boolean_t err = B_FALSE;

// Get the bodypart's charset - Try MIME first then V3
    firstPart->getHeader(env, DtMailMessageContentType, DTM_TRUE, value);
    if (env.isNotSet()) {
        mime_cs = firstPart->csFromContentType(value);
    } else {
        env.clear();
        value.clear();
        firstPart->getHeader(env, DtMailMessageV3charset, DTM_TRUE, value);
        if (env.isNotSet()) {
            strcpy(v3_cs, *(value[0]));
        } else {
            err = B_TRUE;
            env.clear();
            value.clear();
        }
    }
// If cannot obtain bodypart's charset header, then maybe this message
// has only one bodypart, then in this case the charset header maybe
// among the message's envelope (main message headers).
// Get the envelope of the message (in order to access the headers)
    DtMail::Envelope *envelope = NULL;
    if (err == B_TRUE) {
        envelope = message->getEnvelope(env);
        err = B_FALSE;
#ifdef DEBUG
        env.logError(DTM_FALSE, "DEBUG dtmailpr: Looking at main message header\n");
#endif
    }
    if (envelope != NULL) {
//   Check for MIME charset header and then for V3 charset header
        envelope->getHeader(env, DtMailMessageContentType, DTM_TRUE, value);
        if (env.isNotSet()) {
            mime_cs = firstPart->csFromContentType(value);
        } else {
            err = B_TRUE;
            env.clear();
        }
        if (mime_cs == NULL || err == B_TRUE) {
            value.clear();
            envelope->getHeader(env, DtMailMessageV3charset, DTM_TRUE, value);
            if (env.isNotSet()) {
                strcpy(v3_cs, *(value[0]));
            } else {
                err = B_TRUE;
                env.clear();
            }
        }
    } else {
#ifdef DEBUG
        env.logError(DTM_FALSE, "DEBUG dtmailpr: envelope is null\n");
#endif
        env.clear();
    }

// Default codeset in case mime_cs and v3_cs are both null.
    if ((mime_cs == NULL) && (strlen(v3_cs) == 0)) {
        char *ret = NULL;
        firstPart->DtXlateOpToStdLocale(DtLCX_OPER_SETLOCALE,
                                        setlocale(LC_CTYPE, NULL),
                                        NULL,
                                        NULL,
                                        &ret);
        strcpy(v3_cs, "DEFAULT");
        strcat(v3_cs, ".");
        strcat(v3_cs, ret);
        if (ret)
            free(ret);
    }

// Get iconv from and to codeset and do conversion.
    int converted = 0;
    if (mime_cs) {
        from_cs = firstPart->csToConvName(mime_cs);
#ifdef DEBUG
        env.logError(DTM_FALSE, "DEBUG dtmailpr: mime_cs = %s\n", mime_cs);
#endif
    } else {
        from_cs = firstPart->csToConvName(v3_cs);
#ifdef DEBUG
        env.logError(DTM_FALSE, "DEBUG dtmailpr: v3_cs = %s\n", v3_cs);
#endif
    }
    to_cs = firstPart->locToConvName();

#ifdef DEBUG
    if ( from_cs == NULL )
        env.logError(DTM_FALSE, "DEBUG dtmailpr: from_cs is NULL\n");
    else
        env.logError(DTM_FALSE, "DEBUG dtmailpr: from_cs = %s\n", from_cs);

    if ( to_cs == NULL )
        env.logError(DTM_FALSE, "DEBUG dtmailpr: to_cs is NULL\n");
    else
        env.logError(DTM_FALSE, "DEBUG dtmailpr: to_cs = %s\n", to_cs);
#endif

    if ( from_cs && to_cs ) {
        if ( strcasecmp(from_cs, to_cs) != 0 ) {
            converted = firstPart->csConvert((char **)&contents, length, 0, from_cs, to_cs);
#ifdef DEBUG
            env.logError(DTM_FALSE, "DEBUG dtmailpr: converted = %d\n", converted);
#endif
        }
    }
    if ( mime_cs )
        free ( mime_cs );
    if ( from_cs )
        free( from_cs );
    if ( to_cs )
        free ( to_cs );

// End of For CHARSET


    buf = new char [length + 1];
    memset (buf, 0, (size_t) length + 1);

    // have to "seek" length bytes into the
    // contents buffer
    memmove (buf, contents, (size_t) length);
    buf [length] = '\0';	// null-terminate
    // that puppy

// For CHARSET
    if (converted && contents)
        free(contents);

    char	*numbuf = new char [10241];
    memset (numbuf, 0, 1024);

#ifdef NEVER
    // Don't want "Message 1:" appearing in print output
    sprintf (numbuf, "Messsage %s:\n%s\n",
             addlInfo, printHeader (MSGHEADER));
#endif
    puts(printHeader(MSGHEADER));
    puts(buf);

    fflush(stdout);

    // No attachments?  We're done.
    if (numBPs < 2)
        return;

    int	i = 0;

    char	*attbuf = NULL;

    printf ("\n");
    for (i = 1; i < numBPs ; i++)
    {
        nextpart = bodyParts [i];

        if (nextpart == NULL)
            fprintf (stderr, "Error getting part!\n");

        length = 0;
        type = "";
        sunDataDescription = "";
        description = "";
        name = "";
        mode = -1;

        nextpart->getContents(env, NULL, &length, &type,
                              &name, &mode, &sunDataDescription);
        if (handleError (env, "getContents") == B_TRUE)
            exit (1);

        if (type == NULL)
            type = "(unknown)";

        if (sunDataDescription == NULL)
        {
            description = "";
        } else {
            // should add bracket or something
            attbuf = new char [strlen (sunDataDescription) +10];
            sprintf (attbuf, " (%s)", sunDataDescription);
            description = attbuf;
        }

        if (name == NULL)
            name = "(name)";

        printf ("[%d] \"%s\"%s, ", i, name, description);
        printf ("%s, %d bytes\n", type, length);

        if (attbuf != NULL)
            delete [] attbuf;

    }

    delete [] v3_cs;
    return;
}