void struct_index_container_o2o(char *type) {
    write_code(index_container_file, "\n\nstruct index_container_o2o_%s {\n", type);
    write_code(index_container_file, "    struct file_mapper fm;\n");
    write_code(index_container_file, "    struct index_key_rec_o2o_%s *data;\n", type);
    write_code(index_container_file, "    struct index_header_o2o *header;\n");
    write_code(index_container_file, "};");
}
Esempio n. 2
0
void index_gen_fw_compar(char *type){
    write_code(index_gen_file, "\n\nstatic inline int index_gen_fw_compar_%s(const void *a, const void *b) {\n", type);
    write_code(index_gen_file, "    struct index_gen_fw_index_%s *aa = (struct index_gen_fw_index_%s *)a;\n", type, type);
    write_code(index_gen_file, "    struct index_gen_fw_index_%s *bb = (struct index_gen_fw_index_%s *)b;\n", type, type);
    write_code(index_gen_file, "    return aa->key < bb->key ? -1 : (bb->key < aa->key ? 1 : (aa->row_loc < bb->row_loc ? -1 : (bb->row_loc < aa->row_loc ? 1 : 0))) ;\n");
    write_code(index_gen_file, "}");
}
Esempio n. 3
0
void struct_index_key_rec_o2m(char *type) {
    write_code(index_gen_file, "\n\nstruct index_key_rec_o2m_%s {\n", type);
    write_code(index_gen_file, "    %s key;\n", type);
    write_code(index_gen_file, "    uint32_t size;\n");
    write_code(index_gen_file, "    uint32_t vect;\n");
    write_code(index_gen_file, "};");
}
Esempio n. 4
0
    void operator()(text_block const& text, int const depth) {
#ifdef MEOW_SOURCE_HIGHLIGHT
        if (text.get_parent()) {
            auto& parent = static_cast<html::ast const&>(*text.get_parent());
            if (parent.get_name() == "code") {
                auto sourceIt = parent.get_attributes().find("source");
                if (sourceIt != parent.get_attributes().end()) {
                    write_code(text, sourceIt->second, true);
                    return;
                }

                sourceIt = parent.get_attributes().find("langdef");
                if (sourceIt != parent.get_attributes().end()) {
                    write_code(text, sourceIt->second, false);
                    return;
                }
            }
        }
#endif

        if (! text.get_lines().empty()) {
            if (indent_) indent(depth);
            auto it = text.get_lines().begin();
            escape_line(*it);
            for (++it; it != text.get_lines().end(); ++it) {
                stream_ << std::endl;
                if (indent_) indent(depth);
                escape_line(*it);
            }
        }
        if (indent_) stream_ << std::endl;
    }
void index_container_o2m_lookup(char *type) {
    write_code(index_container_file, "\n\nstatic inline int index_container_o2m_lookup_%s(struct index_container_o2m_%s *ic, %s key, uint32_t **vect, uint32_t *size) {\n", type, type, type);
    write_code(index_container_file, "    uint32_t loc;\n");
    write_code(index_container_file, "    if (0 > index_container_o2m_bsearch_%s(ic->keys, ic->header->num_keys, key, &loc))\n", type);
    write_code(index_container_file, "        return -1;\n");
    write_code(index_container_file, "    struct index_key_rec_o2m_%s *key_rec = ic->keys + loc;\n", type);
    write_code(index_container_file, "    *vect = ic->vect + key_rec->vect;\n");
    write_code(index_container_file, "    *size = key_rec->size;\n");
    write_code(index_container_file, "    return 0;\n");
    write_code(index_container_file, "};");
}
void ds_code_gen_index_container(const char *filename) {
    if (!(index_container_file = fopen(filename, "w")))
        die_perror("fopen");

    write_generated_file_comment(index_container_file, __FILE__);
    write_code(index_container_file, "#include <limits.h>");
    uint32_t i = 0;
    for (; i < sizeof(ds_types) / sizeof(ds_types[0]); i++) {
        struct_index_container_o2o(ds_types[i]);
        index_container_o2o_bsearch(ds_types[i]);
        index_container_o2o_init(ds_types[i]);
        index_container_o2o_init2(ds_types[i]);
        index_container_o2o_lookup(ds_types[i]);
        index_container_o2o_exist(ds_types[i]);
        index_container_o2o_min_element(ds_types[i]);
        index_container_o2o_max_element(ds_types[i]);
        index_container_o2o_free(ds_types[i]);
        struct_index_container_o2m(ds_types[i]);
        index_container_o2m_init(ds_types[i]);
        index_container_o2m_bsearch(ds_types[i]);
        index_container_o2m_lookup(ds_types[i]);
        index_container_o2m_exist(ds_types[i]);
        index_container_o2m_free(ds_types[i]);
    }

    if (0 != fclose(index_container_file))
        die_perror("fclose");
}
Esempio n. 7
0
void encode_ascii_to_64(char* input_file, char* output_file) {
	char arr[READ_ENCODE_LENGTH], processed[RESULT_ENCODE_LENGTH];
	arr[READ_ENCODE_LENGTH - 1] = '\0';
	processed[RESULT_ENCODE_LENGTH - 1] = '\0';
  
	FILE* input;
	FILE* output;
	if (!input_file && !output_file) {
		input = stdin;
		output = stdout;
	} else {
		input = fopen(input_file, "r");
		output = fopen(output_file, "w");
	}
	if (!input || !output) return;
	
	size_t read_size;
	
	for (int i = 0; !feof(input); i += READ_ENCODE_LENGTH - 1) {
		read_size = get_encode_chars(input, arr);
		if (read_size == 3 && feof(input)) break;
		_encode_ascii_to_64(arr, read_size, processed);
                if (read_size != 0) write_code(output, processed);
	}
	
	fclose(input);
	fclose(output);
}
Esempio n. 8
0
File: 7a.c Progetto: 7shi/Betelgeuse
void assemble_opr_value(enum Op op, enum Regs ra, int vb, enum Regs rc)
{
    int op1 = ((int)op) >> 16 << 26, op2 = (((int)op) & 0x7f) << 5;
    if (vb < 0 || vb > 255)
        printf("%d: error: literal is over 8bit: %x\n", curline, vb);
    else
        write_code(op1 | (((int)ra) << 21) | (vb << 13) | 0x1000 | op2 | (int)rc);
}
Esempio n. 9
0
File: 7a.c Progetto: 7shi/Betelgeuse
void assemble_mbr(enum Op op, enum Regs ra, enum Regs rb, int hint)
{
    int op1 = ((int)op) >> 16 << 26, op2 = (((int)op) & 3) << 14;
    if (hint < 0 || hint > 0x3fff)
        printf("%d: error: hint is over 14bit: %x\n", curline, hint);
    else
        write_code(op1 | (((int)ra) << 21) | (((int)rb) << 16) | op2 | hint);
}
Esempio n. 10
0
static void bomb (char *p_name)
{
char_varying(256)   msgvs;

     strcpy_vstr_nstr (&msgvs, "FATAL ERROR: Call to unimplemented function '");
     strcat_vstr_nstr (&msgvs, p_name);
     strcat_vstr_nstr (&msgvs, "'. Entering debugger.");
     s$write_code (&msgvs, &0);

     strcpy_vstr_nstr (&msgvs, "Please capture the output of the 'trace' request and mail it to [email protected].");
     s$write_code (&msgvs, &0);

     vos_call_debug ();

     strcpy_vstr_nstr (&msgvs, "Return from debugger. Stopping program. Sorry but this error is unrecoverable.");
     s$write_code (&msgvs, &0);
     s$stop_program (&"", &1);
}
Esempio n. 11
0
File: 7a.c Progetto: 7shi/Betelgeuse
void assemble_pcd(int op1, int num)
{
    if (op1 < 0 || op1 > 0x3f)
        printf("%d: error: opcode is over 6bit: %x\n", curline, op1);
    else if (num < 0 || num > 0x03ffffff)
        printf("%d: error: num is over 26bit: %x\n", curline, num);
    else
        write_code((op1 << 26) | num);
}
Esempio n. 12
0
int main(int argc, char *argv[])
{
	while(1)
	{
		write_code();
		comment_out_code();
		stand_outside_door_and_wait_for_check();
	}
}
Esempio n. 13
0
File: 7a.c Progetto: 7shi/Betelgeuse
void assemble_mem(enum Op op, enum Regs ra, enum Regs rb, int disp)
{
    int op1 = ((int)op) >> 16 << 26;
    if (disp < -0x8000)
        printf("%d: error: disp < -0x8000: -%x\n", curline, -disp);
    else if (disp > 0x7fff)
        printf("%d: error: disp > 0x7fff: %x\n", curline, disp);
    else
        write_code(op1 | (((int)ra) << 21) | (((int)rb) << 16) | (uint16_t)(int16_t)disp);
}
Esempio n. 14
0
File: 7a.c Progetto: 7shi/Betelgeuse
void assemble_bra(enum Op op, enum Regs ra, int disp)
{
    int op1 = ((int)op) >> 16 << 26;
    if (disp < -0x100000)
        printf("%d: error: disp < -0x100000: -%x\n", curline, -disp);
    else if (disp > 0xfffff)
        printf("%d: error: disp > 0xfffff: %x\n", curline, disp);
    else
        write_code(op1 | (((int)ra) << 21) | (((unsigned int)disp) & 0x1fffff));
}
void index_container_o2o_init2(char *type) {
    write_code(index_container_file, "\n\nstatic inline int index_container_o2o_init2_%s(struct index_container_o2o_%s *ic, const char *base_path, const char *db, const char *table, const char *field) {\n", type, type);
    write_code(index_container_file, "    char filename[PATH_MAX];\n");
    write_code(index_container_file, "    if (PATH_MAX <= snprintf(filename, PATH_MAX, \"%%s/%%s/%%s/%%s.idx\", base_path, db, table, field))\n");
    write_code(index_container_file, "        return LOGGER_ERROR(\"filename too long\"), -1;\n");
    write_code(index_container_file, "    return file_mapper_init(&ic->fm, filename);\n");
    write_code(index_container_file, "};");
}
Esempio n. 16
0
void init_dev_para()
{
	u8 idata tmp8;
	if((sata.fis_rcv_content[7] & 0x0F) != (max_head_per_cylnd-1))goto init_dev_para_err;
	if(sata.fis_rcv_content[12]!=max_sec_per_head)goto init_dev_para_err;
	tmp8 = read_code(0x006A+identify_data_addr);
	//The device shall also clear bit 0 of word 53 in the IDENTIFY DEVICE data to zero
	tmp8 = tmp8 | 0x01;
	enable_code_program;
    write_code(0x006A+identify_data_addr,tmp8);
	disable_code_program;
	tx_fis_34(status_good,error_no,int_set);
	return;
init_dev_para_err:
	tmp8 = read_code(0x006A+identify_data_addr);
	//The device shall also clear bit 0 of word 53 in the IDENTIFY DEVICE data to zero
	tmp8 = tmp8 & 0xfe;
	enable_code_program;
    write_code(0x006A+identify_data_addr,tmp8);
	disable_code_program;
	tx_fis_34(status_bad,error_abort,int_set);

}
void struct_index_container_o2m(char *type) {
    write_code(index_container_file, "\n\nstruct index_container_o2m_%s {\n", type);
    write_code(index_container_file, "    struct file_mapper fm;\n");
    write_code(index_container_file, "    struct index_header_o2m *header;\n");
    write_code(index_container_file, "    uint32_t *vect;\n");
    write_code(index_container_file, "    struct index_key_rec_o2m_%s *keys;\n", type);
    write_code(index_container_file, "};");

}
Esempio n. 18
0
void sccwriter::write_expr( Expr* code, std::ostream& os, int ind, std::string& expr, int opts )
{
  if( code->getclass()==SYMS_EXPR && is_var( ((SymSExpr*)code)->s ) )
  {
    get_var_name( ((SymSExpr*)code)->s, expr );
    indent( os, ind );
    os << expr.c_str() << "->inc();" << std::endl;
  }
  else
  {
    std::ostringstream ss;
    ss << "e" << exprCount;
    exprCount++;
    //declare the expression
    indent( os, ind );
    if( code->getclass()==SYMS_EXPR && !is_var( ((SymSExpr*)code)->s ) )
    {
      os << "static ";
    }
    os << "Expr* " << ss.str().c_str() << ";" << std::endl;
    //write the expression
    std::ostringstream ss2;
    ss2 << ss.str().c_str();
    write_code( code, os, ind, ss2.str().c_str(), opts );

    //if is not a sym expression, then decrement the expression and return null
    if( opts&opt_write_check_sym_expr )
    {
      indent( os, ind );
      os << "if (" << expr.c_str() << "->getclass() != SYM_EXPR) {" << std::endl;
      indent( os, ind+1 );
      os << "exit( 1 );" << std::endl;
      indent( os, ind );
      os << "}" << std::endl;
    }

    expr = std::string( ss.str().c_str() );
    vars.push_back( expr );
  }
  //increment the counter for memory management
  //indent( os, ind );
  //os << expr.c_str() << "->inc();" << std::endl;
}
Esempio n. 19
0
void ds_code_gen_index_gen(const char *filename) {
    if (!(index_gen_file = fopen(filename, "w")))
        die_perror("fopen");

    write_generated_file_comment(index_gen_file, __FILE__);
    write_code(index_gen_file, "#include <limits.h>");
    uint32_t i = 0;
    for (; i < sizeof(ds_types) / sizeof(ds_types[0]); i++) {
        struct_fw_index(ds_types[i]);
        struct_index_key_rec_o2o(ds_types[i]);
        struct_index_key_rec_o2m(ds_types[i]);
        index_gen_fw_compar(ds_types[i]);
        index_gen_generate_mem_o2o(ds_types[i]);
        index_gen_generate_mem_o2m(ds_types[i]);
        _index_gen_generate_ds_file(ds_types[i]);
        index_gen_generate_ds_file_o2o(ds_types[i]);
        index_gen_generate_ds_file_o2m(ds_types[i]);
        index_gen_generate_ds_file_o2o_ht(ds_types[i]);
    }

    if (0 != fclose(index_gen_file))
        die_perror("fclose");
}
Esempio n. 20
0
int main(int argc, char *argv[])
{
   int ret = 1;
   char *basic_buf;
   int basic_len;

   /* Get options */
   if (parse_cmdline(argc, argv)) {
      return ret;
   }

   /* Get length of binfile */
   binlen = get_binlen(opt.binfile);
   if (binlen == 0) {
      fprintf(stderr, "Error: empty or non-existing BIN-file, giving up\n");
      goto cleanup;
   }

   if (opt.scrfile) {
      if (get_binlen(opt.scrfile) != SCRLEN) {
         fprintf(stderr, "Error: wrong filesize on %s\n", opt.scrfile);
         goto cleanup;
      }
   }

   /* Open filepointers */
   if (open_files()) {
      fprintf(stderr, "Error: could not open files, giving up\n");
      goto cleanup;
   }

   snprintf(basenamez, opt.baselen + 1, "%s", opt.basename);

   if (!opt.no_basic) {
      /* Creater BASIC loader code */
      if (create_basic_loader()) {
         fprintf(stderr, "Error: could not create BASIC loader, giving up\n");
      }

      if (basic_get(&basic_buf, &basic_len)) {
         fprintf(stderr, "Error: could not create BASIC loader, giving up\n");
         goto cleanup;
      }

      /* Write BASIC loader */
      if (write_program(basic_buf, basic_len, "Loader")) {
         goto cleanup;
      }

      /* Write SCREEN$ data */
      if (opt.scrfile) {
         if (write_code("Screen", scrfp, SCRLEN, SCRADDR)) {
            goto cleanup;
         }
      }
   }

   /* Write machine code from BIN-file */
   if (write_code(basenamez, binfp, binlen, opt.load_address)) {
      goto cleanup;
   }

   /* Success */

   printf("0 OK, 0:1 (%s)\n", opt.tapfile);

   ret = 0;

 cleanup:

   if (scrfp) fclose(scrfp);
   if (binfp) fclose(binfp);
   if (tapfp) fclose(tapfp);
   parse_cleanup();

   return ret;
}
Esempio n. 21
0
int GIF_LZW_compressor(DIB *srcimg,unsigned int numColors,FILE *handle,int interlace)
{
    int xdim,ydim,clear,EOI,code,bits,pre,suf,x,y,i,max,bits_color,done,rasterlen;
    static short int rasters[768];

    stat_bits = 0;
    code_in_progress = 0;
    LZWpos = 1;

    for (i = 0; i < hash; i++)
    {
		hashtree[i][0] = hashtree[i][1] = hashtree[i][2] = -1;
	}
    if (handle==NULL)
        return 0;
    xdim = srcimg->width;
    ydim = srcimg->height;
    bits_color = max_bits(numColors)-1;
    clear = (1 << (bits_color+1)); //powers2[bits_color+2]
    EOI = clear+1;
    code = EOI+1;
    bits = bits_color+2;
    max = (1 << bits); //powers2[bits+1]
    if (code==max)
    {
        clear = 4;
        EOI = 5;
        code = 6;
        bits++;
        max *= 2;
	}
    fputc(bits-1, handle);
    write_code(handle, bits, clear);
    rasterlen = 0;
    if (interlace)
    {
        for (int e=1; e<=5; e+=4)
        {
            for (int f=e; f<=ydim; f+=8)
            {
                rasters[rasterlen++] = f;
			}
		}
        for (int e=3; e<=ydim; e+=4)
        {
            rasters[rasterlen++] = e;
		}
        for (int e=2; e<=ydim; e+=2)
        {
            rasters[rasterlen++] = e;
	   }
   	}
    else
    {
        for (int e=1; e<=ydim; e++)
            rasters[rasterlen++] = e - 1;
	}
    pre = srcimg->bits[rasters[0] * xdim];
    x=1;     y=0;     done=0;
    if (x>=xdim)
    {
		y++;   x=0;
	}
    while (1)
    {
        while (1)
        {
            if (!done)
            {
                suf = srcimg->bits[rasters[y] * xdim + x];
                x++;
                if (x>=xdim)
                {
                    y++;
                    x=0;
                    if (y>=ydim)
                        done = 1;
				}
                i = find_hash(pre,suf);
                if (hashtree[i][0]==-1)
                    break;
                else
                    pre = hashtree[i][0];
			}
            else
            {
                write_code(handle,bits,pre);
                write_code(handle,bits,EOI);
                if (stat_bits)
                    write_code(handle,bits,0);
                LZW[0] = LZWpos - 1;
                fwrite(LZW, 1, LZWpos, handle);
                fputc(0, handle);
                return 1;
			}
		}
        write_code(handle,bits,pre);
        hashtree[i][0] = code; hashtree[i][1] = pre; hashtree[i][2] = suf;
        pre = suf;
        code++;
        if (code == max+1)
        {
            max *= 2;
            if (bits == 12)
            {
                write_code(handle,bits,clear);
                for (i = 0; i < hash; i++)
                {
					hashtree[i][0] = hashtree[i][1] = hashtree[i][2] = -1;
				}
                code = EOI+1;
                bits = bits_color+2;
                max = 1 << bits;
                if (bits == 2)
                {
                    clear = 4;
                    EOI = 5;
                    code = 6;
                    bits = 3;
                    max *= 2;
				}
            }
            else
                bits++;
		}
	}

	return 0;
}
Esempio n. 22
0
void ProcessIO(void)
{
	char oldPGDtris;
	char PIN;
	static byte counter=0;
	int nBytes;
	unsigned long address;
	unsigned char i;
	
	input_buffer[0]=UART1RX(); //USBGenRead((byte*)input_buffer,64);
//	if(nBytes>0)
//	{
		switch(input_buffer[0])
		{
			case CMD_ERASE:
				setLeds(LEDS_ON | LEDS_WR);
				getBytes(1,1);//get more data, #bytes, where to insert in input buffer array
				output_buffer[0]=bulk_erase(picfamily,pictype,input_buffer[1]);
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_READ_ID:
				setLeds(LEDS_ON | LEDS_RD);
				switch(picfamily)
				{
					case DSPIC30:
						read_code(picfamily,pictype,0xFF0000,(unsigned char*)output_buffer,2,3);
						break;
					case PIC18:
						read_code(picfamily,pictype,0x3FFFFE,(unsigned char*)output_buffer,2,3);  //devid is at location 0x3ffffe   for PIC18 devices
						break;
					case PIC16:
						set_vdd_vpp(picfamily, pictype, 0);
						read_code(picfamily,pictype,0x2006,(unsigned char*)output_buffer,2,3);  //devid is at location 0x2006  for PIC16 devices
						break;
				}
				counter=2;
				setLeds(LEDS_ON);
				break;
			case CMD_WRITE_CODE:
				setLeds(LEDS_ON | LEDS_WR);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				output_buffer[0]=write_code(picfamily,pictype,address, (unsigned char*)(input_buffer+6),input_buffer[1],input_buffer[5]);
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_READ_CODE:
				setLeds(LEDS_ON | LEDS_RD);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				read_code(picfamily,pictype,address,(unsigned char*)output_buffer,input_buffer[1],input_buffer[5]);
				counter=input_buffer[1];
				setLeds(LEDS_ON);
				break;
			case CMD_WRITE_DATA:
				setLeds(LEDS_ON | LEDS_WR);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				output_buffer[0]=write_data(picfamily,pictype,address, (unsigned char*)(input_buffer+6),input_buffer[1],input_buffer[5]); 
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_READ_DATA:
				setLeds(LEDS_ON | LEDS_RD);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				read_data(picfamily,pictype,address,(unsigned char*)output_buffer,input_buffer[1],input_buffer[5]); 
				counter=input_buffer[1];
				setLeds(LEDS_ON);
				break;
			case CMD_WRITE_CONFIG:
				setLeds(LEDS_ON | LEDS_WR);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				output_buffer[0]=write_config_bits(picfamily, pictype, address, (unsigned char*)(input_buffer+6),input_buffer[1],input_buffer[5]);
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_SET_PICTYPE:
				output_buffer[0]=set_pictype(input_buffer+1);
				//output_buffer[0]=1; //Ok
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_FIRMWARE_VERSION:
				for(counter=0; counter<18; counter++)output_buffer[counter]=upp_version[counter];
				counter=18;
				setLeds(LEDS_ON);
				break;
			case CMD_DEBUG:
				setLeds(LEDS_ON | LEDS_WR | LEDS_RD);
				switch(input_buffer[1])
				{
					case 0:
						set_vdd_vpp(dsP30F, DSPIC30, 1);
						output_buffer[0]=1;
						counter=1;	
						break;
					case 1:
						set_vdd_vpp(dsP30F, DSPIC30, 0);
						output_buffer[0]=1;
						counter=1;	
						break;
					case 2:
						dspic_send_24_bits(((unsigned long)input_buffer[2])|
								((unsigned long)input_buffer[3])<<8|
								((unsigned long)input_buffer[4])<<16);
						output_buffer[0]=1;
						counter=1;
						break;
					case 3:
						nBytes =  dspic_read_16_bits();
						output_buffer[0]=(unsigned char)nBytes;
						output_buffer[1]=(unsigned char)(nBytes>>8);
						counter=2;
						break;
						
				}
				break;
			case CMD_GET_PIN_STATUS:
				switch(input_buffer[1])
				{
					case SUBCMD_PIN_PGC:
						if((!TRISPGC_LOW)&&(!PGC_LOW)) //3.3V levels
						{
							if(PGC) output_buffer[0] = PIN_STATE_3_3V;
							else output_buffer[0] = PIN_STATE_0V;
						}
						else	//5V levels
						{
							if(PGC) output_buffer[0] = PIN_STATE_5V;
							else output_buffer[0] = PIN_STATE_0V;
						}
						counter=1;
						break;
					case SUBCMD_PIN_PGD:
						if(TRISPGD)//PGD is input
						{
							if(PGD_READ) output_buffer[0] = PIN_STATE_5V;
							else output_buffer[0] = PIN_STATE_0V;
						}
						else
						{							
							if((!TRISPGD_LOW)&&(!PGD_LOW)) //3.3V levels
							{
								if(PGD) output_buffer[0] = PIN_STATE_3_3V;
								else output_buffer[0] = PIN_STATE_0V;
							}
							else	//5V levels
							{
								if(PGD) output_buffer[0] = PIN_STATE_5V;
								else output_buffer[0] = PIN_STATE_0V;
							}
						}
						counter=1;
						break;
					case SUBCMD_PIN_VDD:
						//if(VDD) output_buffer[0] = PIN_STATE_FLOAT;
						//else output_buffer[0] = PIN_STATE_5V;
						output_buffer[0] = PIN_STATE_5V;
						counter = 1;
						break;
					case SUBCMD_PIN_VPP:
						counter=1;
						if(!VPP){output_buffer[0] = PIN_STATE_12V;break;}
						if(VPP_RST){output_buffer[0] = PIN_STATE_0V;break;}
						if(VPP_RUN){output_buffer[0] = PIN_STATE_5V;break;}
						output_buffer[0] = PIN_STATE_FLOAT;
						break;
					case SUBCMD_PIN_VPP_VOLTAGE:
						ReadAdc(output_buffer);
						counter=2;
						break;
					default:
						output_buffer[0]=3;
						counter=1;
						break;
				}
				break;
			case CMD_SET_PIN_STATUS:
				switch(input_buffer[1])
				{
					case SUBCMD_PIN_PGC:
						switch(input_buffer[2])
						{
							case PIN_STATE_0V:
								TRISPGC = 0;
								PGC = 0;
								TRISPGC_LOW = 1;
								PGC_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_3_3V:
								TRISPGC = 0;
								PGC = 1;
								TRISPGC_LOW = 0;
								PGC_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_5V:
								TRISPGC = 0;
								PGC = 1;
								TRISPGC_LOW = 1;
								PGC_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					case SUBCMD_PIN_PGD:
						switch(input_buffer[2])
						{
							case PIN_STATE_0V:
								TRISPGD = 0;
								PGD = 0;
								TRISPGD_LOW = 1;
								PGD_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_3_3V:
								TRISPGD = 0;
								PGD = 1;
								TRISPGD_LOW = 0;
								PGD_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_5V:
								TRISPGD = 0;
								PGD = 1;
								TRISPGD_LOW = 1;
								PGD_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_INPUT:
								TRISPGD_LOW = 1;
								TRISPGD = 1;
								output_buffer[0]=1;//ok
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					case SUBCMD_PIN_VDD:
						switch(input_buffer[2])
						{
							case PIN_STATE_5V:
								//VDD = 0;
								output_buffer[0]=1;
								break;
							case PIN_STATE_FLOAT:
								//VDD = 1;
								output_buffer[0]=1;
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					case SUBCMD_PIN_VPP:
						switch(input_buffer[2])
						{
							case PIN_STATE_0V:
								VPP = 1;
								VPP_RST = 1;
								VPP_RUN = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_5V:
								VPP = 1;
								VPP_RST = 0;
								VPP_RUN = 1;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_12V:
								VPP = 0;
								VPP_RST = 0;
								VPP_RUN = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_FLOAT:
								VPP = 1;
								VPP_RST = 0;
								VPP_RUN = 0;
								output_buffer[0]=1;//ok
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					default:
						output_buffer[0]=3;
				}
				counter=1;
				break;
		}
	//} //if nBytes>0
	if(counter != 0)
	{
		//if(!mUSBGenTxIsBusy())
		//USBGenWrite((byte*)&output_buffer,counter);
		for(i=0; i<counter; i++) UART1TX(output_buffer[i]);
		counter=0;
	}
}//end ProcessIO
/**
 * Determines the transaction code based on the enumeration value received
 *
 * @return buffer after transaction text line is composed and concatenated for file write
 **/
char* Transaction::write(char* dest){
	//prepare the code

	switch (this->code){
		case Transaction::Test:{
			//write code
			if( debug_transaction) printf("writing code\n");
			char* curr = write_code( dest, this->code);
			if( error) break;
			if( debug_transaction) printf("writing token\n");
			curr = write_token( curr);
			//write username
			if( debug_transaction) printf("writing username\n");
			curr = write_username( curr, this->username);
			if( error) break;
			if( debug_transaction) printf("writing token\n");
			curr = write_token( curr);
			//write buyer username
			if( debug_transaction) printf("writing buyer username\n");
			curr = write_username( curr, this->buyer);
			if( error) break;
			if( debug_transaction) printf("writing token\n");
			curr = write_token( curr);
			//write seller username
			if( debug_transaction) printf("writing seller username\n");
			curr = write_username( curr, this->seller);
			if( error) break;
			if( debug_transaction) printf("writing token\n");
			curr = write_token( curr);
			//write event name
			if( debug_transaction) printf("writing event name\n");
			curr = write_eventName( curr, this->eventName);
			if( error) break;
			if( debug_transaction) printf("writing token\n");
			curr = write_token( curr);
			//write type
			if( debug_transaction) printf("writing type\n");
			curr = write_type( curr, this->type);
			if( error) break;
			if( debug_transaction) printf("writing token\n");
			curr = write_token( curr);
			//write ticket amount
			if( debug_transaction) printf("writing ticket amount\n");
			curr = write_ticketAmount( curr, this->ticketAmount);
			if( error) break;
			if( debug_transaction) printf("writing token\n");
			curr = write_token( curr);
			//write ticket price
			if( debug_transaction) printf("writing ticket price\n");
			curr = write_ticketPrice( curr, this->ticketPrice);
			if( error) break;
			curr = write_token( curr);
			//write credit
			if( debug_transaction) printf("writing credit\n");
			curr = write_credit( curr, this->totalCredits);
			if( error) break;
			if( debug_transaction) printf("writing token\n");
			//good
			if( debug_transaction) printf("done\n");
			return dest;}

		//01-create, 02-delete, 06-addcredit, 00-end of session
		//(X field 2, U field 15, T field 2, C field 9, total 28 + 3 = 31)
		//XX_UUUUUUUUUUUUUUU_TT_CCCCCCCCC
		case Transaction::Create:
		case Transaction::Delete:
		case Transaction::AddCredit:{
			//write code
			char* curr = write_code( dest, this->code);
			if( error) break;
			curr = write_token( curr);

			//write username
			curr = write_username( curr, this->username);
			if( error) break;
			curr = write_token( curr);

			//write type
			curr = write_type( curr, this->type);
			if( error) break;
			curr = write_token( curr);

			//write credit
			curr = write_credit( curr, this->totalCredits);
			if( error) break;

			//done
			return dest;}

		//05-refund
		//(X field 2, U field 15, S field 15, C field 9, total 44)
		//XX_UUUUUUUUUUUUUUU_SSSSSSSSSSSSSSS_CCCCCCCCC
		case Transaction::Refund:{
			//write code
			char* curr = write_code( dest, this->code);
			if( error) break;
			curr = write_token( curr);

			//write buyer username
			curr = write_username( curr, this->buyer);
			if( error) break;
			curr = write_token( curr);

			//write seller username
			curr = write_username( curr, this->seller);
			if( error) break;
			curr = write_token( curr);

			//write credit
			curr = write_credit( curr, this->totalCredits);
			if( error) break;

			//done
			return dest;}

		//03-sell, 04-buy
		//(X field 2, E field 19, S field 15, T field 3, P field 6, total 45+4 = 49)
		//XX_EEEEEEEEEEEEEEEEEEE_SSSSSSSSSSSSSSS_TTT_PPPPPP
		case Transaction::Buy:
		case Transaction::Sell:{
			//write code
			char* curr = write_code( dest, this->code);
			if( error) break;
			curr = write_token( curr);

			//write seller username
			curr = write_username( curr, this->seller);
			if( error) break;
			curr = write_token( curr);

			//write ticket amount
			curr = write_ticketAmount( curr, this->ticketAmount);
			if( error) break;
			curr = write_token( curr);

			//write ticket price
			curr = write_ticketPrice( curr, this->ticketPrice);
			if( error) break;

			//done
			return dest;}

		//manage the error case
		default:{
			printf("%s\n", Error::TransactionInvalidCode);
			break;}}
	//handle the error case
	printf("%s\n", error_string);
	dest[0] = '\0';
	printf("transaction: {%s}\n", dest);
	return buffer;
}
Esempio n. 24
0
JNIEXPORT jint JNICALL Java_com_btdetector2_NativeWrapper_is_1synch_1proc_1switch
  (JNIEnv * je, jclass jc)
{
    // a function pointer to our test code
    test_func_t     test_func;

    // a pointer to some code that we will patch
    uint32_t *  patch;

    // a useful swap pointer
    uint32_t *  caret;

		int i=0;
		double sum=0;
		struct timespec tsi, tsf;
		double elaps_ns, elaps_s;


    // we need some memory for our run-time-generated function.
    // w+x rights in order to be able to patch the code
    // 16 * 4,  // Space for 16 instructions. (More than enough.)
    uint32_t *  code = mmap(
            NULL,
            16 * 4,  // Space for 64 instructions. (More than enough.)
            PROT_READ | PROT_WRITE | PROT_EXEC,
            MAP_PRIVATE | MAP_ANONYMOUS,
            -1,
            0);

    if (code == MAP_FAILED) {
        printf("Could not mmap a memory buffer with the proper permissions.\n");
        return -1;
    }

    // Set test_func to point to the writable code block
    test_func = (test_func_t) code;

    // initialize test_func with f1 code
		write_code(&caret, &code, &patch, &f2);

    // Synchronize the cache.
    // __clear_cache((char*)code, (char*)caret);

		sum=0;
		for (i=0; i<10; i++) {

			// patch code with f1, synch I-cache and run the function
			patch_code_other(&caret, &patch, &f1);
			test_func();

			// patch code with f2, synch I-cache and run the function
			patch_code_other(&caret, &patch, &f2);
			test_func();
		}

	if (strcmp(switch_str, expected) == 0) {
		// printf("\n is Emulator! \n");
		return 1;
	}
	else {
		// printf("\n is Device! \n");
		return 0;
	}
}
Esempio n. 25
0
void sccwriter::write_code( Expr* code, std::ostream& os, int ind, const char* retModStr, int opts )
{
  std::string retModString;
  std::string incString;
  if ( retModStr )
  {
    retModString = std::string( retModStr );
    retModString.append( " = " );
    incString = std::string( retModStr );
    incString.append( "->inc();" );
  }
  switch( code->getclass() )
  {
  case INT_EXPR:
    {
      indent( os, ind );
      os << retModString.c_str();
      os << "new IntExpr( " << mpz_get_si( ((IntExpr*)code)->n ) << " );" << std::endl;
      indent( os, ind );
      os << incString.c_str() << std::endl;
    }
    break;
  case RAT_EXPR:
    {
      mpz_t num, den;
      mpz_init(num);
      mpz_init(den);
      mpq_get_num( num, ((RatExpr*)code)->n );
      mpq_get_den( den, ((RatExpr*)code)->n );
      indent( os, ind );
      os << retModString.c_str();
      os << "new RatExpr( " << mpz_get_si( num ) << ", " << mpz_get_si( den ) << " );" << std::endl;
      indent( os, ind );
      os << incString.c_str() << std::endl;
    }
    break;
  case SYMS_EXPR:
    {
      //if it is a variable, simply write it to buffer
      if( is_var( ((SymSExpr*)code)->s ) )
      {
        indent( os, ind );
        os << retModString.c_str();
        write_variable( ((SymSExpr*)code)->s.c_str(), os );
        os << ";" << std::endl;  
      }
      else  //else must look at symbol lookup table
      {
        std::string var;
        get_var_name( ((SymSExpr*)code)->s, var );
        indent( os, ind );
        os << retModString.c_str() << "e_" << var.c_str() << ";" << std::endl;
        add_global_sym( var ); 
      }
      indent( os, ind );
      os << incString.c_str() << std::endl;
    }
    break;
  default:
    switch( code->getop() )
    {
    case APP:
      {
        //collect the arguments
        std::vector< Expr* > argVector;
        code->collect_args( argVector );
        //write the arguments
        std::vector< std::string > args;
        for( int a=0; a<(int)argVector.size(); a++ )
        {
          std::string expr;
          write_expr( argVector[a], os, ind, expr );
          args.push_back( expr );
        }
        //write_args( (CExpr*)code, os, ind, 1, args );
        Expr* hd = code->get_head();
        //map to a program in the case that it is a program
        if( hd->getop()==PROG && get_prog_index_by_expr( hd )!=-1 )
        {
          indent( os, ind );
          os << retModString << "f_" << progNames[ get_prog_index_by_expr( hd ) ].c_str() << "( ";
          for( int a=0; a<(int)args.size(); a++ )
          {
            os << args[a].c_str();
            if( a!=(int)( args.size()-1 ) ){
              os << ", ";
            }
          }
          os << " );" << std::endl;
          for( int a=0; a<(int)args.size(); a++ )
          {
            write_dec( args[a], os, ind );
          }
        }
        else
        {
#ifdef USE_FLAT_APP
          std::string expr;
          write_expr( hd, os, ind, expr );
          indent( os, ind );
          os << retModString << "new CExpr( APP, ";
          os << expr.c_str() << ", ";
          for( int a=0; a<(int)args.size(); a++ )
          {
            os << args[a].c_str();
            if( a!=(int)( args.size()-1 ) ){
              os << ", ";
            }
          }
          os << " );" << std::endl;
#else
          std::string expr;
          write_expr( hd, os, ind, expr );
          indent( os, ind );
          os << retModString;
          for( int a=0; a<(int)args.size(); a++ )
          {
            os << "new CExpr( APP, ";
          }
          os << expr.c_str() << ", ";
          for( int a=0; a<(int)args.size(); a++ )
          {
            os << args[a].c_str();
            os << " )";
            if( a!=(int)( args.size()-1 ) ){
              os << ", ";
            }
          }
          os << ";" << std::endl;
#endif
          //indent( os, ind );
          //os << expr.c_str() << "->dec();" << std::endl;
        }
      }
      break;
    case MATCH:
      {
        //calculate the value for the expression
        std::string expr;
        write_expr( ((CExpr*)code)->kids[0], os, ind, expr );
        //get the head
        std::ostringstream sshd;
        sshd << "e" << exprCount;
        exprCount++;
        indent( os, ind );
        os << "Expr* " << sshd.str().c_str() << " = " << expr.c_str() << "->followDefs()->get_head();" << std::endl;
        //write the arguments
        std::vector< std::string > args;
        write_args( (CExpr*)code, os, ind, 1, args );
        bool encounterDefault = false;
        //now make an if statement corresponding to the match 
        int a = 0;
        while( ((CExpr*)code)->kids[a+1] )
        {
          indent( os, ind );
          if( a!=0 ){
            os << "}else";
          }
          if( ((CExpr*)code)->kids[a+1]->getop()!=CASE ){
            encounterDefault = true;
            os << "{" << std::endl;
            //write the body of the case
            write_code( ((CExpr*)code)->kids[a+1], os, ind+1, retModStr ); 
            indent( os, ind );
            os << "}" << std::endl;
          }else{
            if( a!=0 )
              os << " ";
            os << "if( " << sshd.str().c_str() << "==" << args[a].c_str() << " ){" << std::endl;
            //collect args from the variable in the code
            std::ostringstream ssargs;
            ssargs << "args" << argsCount;
            argsCount++;
#ifndef USE_FLAT_APP
            indent( os, ind+1 );
            os << "std::vector< Expr* > " << ssargs.str().c_str() << ";" << std::endl;
            indent( os, ind+1 );
            os << expr.c_str() << "->followDefs()->collect_args( " << ssargs.str().c_str() << " );" << std::endl;
#endif
            //set the variables defined in the pattern equal to the arguments
            std::vector< Expr* > caseArgs;
            ((CExpr*)((CExpr*)code)->kids[a+1])->kids[0]->collect_args( caseArgs );
            for( int b=0; b<(int)caseArgs.size(); b++ )
            {
              indent( os, ind+1 );
              os << "Expr* ";
              write_variable( ((SymSExpr*)caseArgs[b])->s.c_str(), os );
#ifdef USE_FLAT_APP
              os << " = ((CExpr*)" << expr.c_str() << "->followDefs())->kids[" << b+1 << "];" << std::endl;
#else
              os << " = " << ssargs.str().c_str() << "[" << b << "];" << std::endl;
#endif
              vars.push_back( ((SymSExpr*)caseArgs[b])->s );
            }
            //write the body of the case
            write_code( ((CExpr*)code)->kids[a+1], os, ind+1, retModStr, opt_write_case_body ); 
          }
          a++;
        }
        if( !encounterDefault )
        {
          indent( os, ind );
          os << "}else{" << std::endl;
          indent( os, ind + 1 );
          os << "std::cout << \"Could not find match for expression in function f_";
          os << progNames[currProgram].c_str() << " \";" << std::endl;
          indent( os, ind + 1 );
          os << sshd.str().c_str() << "->print( std::cout );" << std::endl;
          indent( os, ind + 1 );
          os << "std::cout << std::endl;" << std::endl;
          indent( os, ind + 1 );
          os << "exit( 1 );" << std::endl;
          indent( os, ind );
          os << "}" << std::endl;
        }
        write_dec( expr, os, ind );
        for( int a=0; a<(int)args.size(); a++ )
        {
          write_dec( args[a], os, ind );
        }
      }
      break;
    case CASE:
      if( opts&opt_write_case_body )
      {
        write_code( ((CExpr*)code)->kids[1], os, ind, retModStr );
      }
      else
      {
        write_code( ((CExpr*)code)->kids[0]->get_head(), os, ind, retModStr );
      }
      break;
    case DO:
      {
        //write each of the children in sequence
        int counter = 0;
        while( ((CExpr*)code)->kids[counter] )
        {
          if( ((CExpr*)code)->kids[counter+1]==NULL )
          {
            write_code( ((CExpr*)code)->kids[counter], os, ind, retModStr );
          }
          else
          {
            std::string expr;
            write_expr( ((CExpr*)code)->kids[counter], os, ind, expr );
            //clean up memory
            write_dec( expr, os, ind );
          }
          counter++;
        }
      }
      break;
    case LET:
      {
        indent( os, ind );
        os << "Expr* ";
        write_variable( ((SymSExpr*)((CExpr*)code)->kids[0])->s, os );
        os << ";" << std::endl;
        std::ostringstream ss;
        write_variable( ((SymSExpr*)((CExpr*)code)->kids[0])->s, ss );
        write_code( ((CExpr*)code)->kids[1], os, ind, ss.str().c_str() );
        //add it to the variables
        vars.push_back( ((SymSExpr*)((CExpr*)code)->kids[0])->s );
        write_code( ((CExpr*)code)->kids[2], os, ind, retModStr );
        //clean up memory
        indent( os, ind );
        write_variable( ((SymSExpr*)((CExpr*)code)->kids[0])->s, os );
        os << "->dec();" << std::endl;
      }
      break;
    case FAIL:
      {
        indent( os, ind );
        os << retModString.c_str() << "NULL;" << std::endl;
      }
      break;
#ifndef MARKVAR_32
    case MARKVAR:
      {
        //calculate the value for the expression
        std::string expr;
        write_expr( ((CExpr*)code)->kids[0], os, ind, expr, opt_write_check_sym_expr );
        //set the mark on the expression
        indent( os, ind );
        os << "if (" << expr.c_str() << "->followDefs()->getmark())" << std::endl;
        indent( os, ind+1 );
        os << expr.c_str() << "->followDefs()->clearmark();" << std::endl;
        indent( os, ind );
        os << "else" << std::endl;
        indent( os, ind+1 );
        os << expr.c_str() << "->followDefs()->setmark();" << std::endl;
        //write the return if necessary
        if( retModStr!=NULL ){
          indent( os, ind );
          os << retModString.c_str() << expr.c_str() << ";" << std::endl;
          indent( os, ind );
          os << incString.c_str() << std::endl;
        }
        write_dec( expr, os, ind );
      }
      break;
    case IFMARKED:
      {
        //calculate the value for the expression
        std::string expr;
        write_expr( ((CExpr*)code)->kids[0], os, ind, expr, opt_write_check_sym_expr );
        //if mark is set, write code for kids[1]
        indent( os, ind );
        os << "if (" << expr.c_str() << "->followDefs()->getmark()){" << std::endl;
        write_code( ((CExpr*)code)->kids[1], os, ind+1, retModStr );
        //else write code for kids[2]
        indent( os, ind );
        os << "}else{" << std::endl;
        write_code( ((CExpr*)code)->kids[2], os, ind+1, retModStr );
        indent( os, ind );
        os << "}" << std::endl;
        //clean up memory
        write_dec( expr, os, ind );
      }
      break;
#else
    case MARKVAR:
      {
        //calculate the value for the expression
        std::string expr;
        write_expr( ((CExpr*)code)->kids[1], os, ind, expr, opt_write_check_sym_expr );
        //set the mark on the expression
        indent( os, ind );
        os << "if ( ((SymExpr*)" << expr.c_str() << "->followDefs())->getmark(";
        os << ((IntExpr*)((CExpr*)code)->kids[0])->get_num() << "))" << std::endl;
        indent( os, ind+1 );
        os << "((SymExpr*)" << expr.c_str() << "->followDefs())->clearmark(";
        os << ((IntExpr*)((CExpr*)code)->kids[0])->get_num() << ");" << std::endl;
        indent( os, ind );
        os << "else" << std::endl;
        indent( os, ind+1 );
        os << "((SymExpr*)" << expr.c_str() << "->followDefs())->setmark(";
        os << ((IntExpr*)((CExpr*)code)->kids[0])->get_num() << ");" << std::endl;
        //write the return if necessary
        if( retModStr!=NULL ){
          indent( os, ind );
          os << retModString.c_str() << expr.c_str() << ";" << std::endl;
          indent( os, ind );
          os << incString.c_str() << std::endl;
        }
        write_dec( expr, os, ind );
      }
      break;
    case COMPARE:
      {
        std::string expr1, expr2;
        write_expr( ((CExpr*)code)->kids[0], os, ind, expr1, opt_write_check_sym_expr );
        write_expr( ((CExpr*)code)->kids[1], os, ind, expr2, opt_write_check_sym_expr );
        indent( os, ind );
        os << "if( ((SymExpr*)" << expr1.c_str() << ")->followDefs() < ((SymExpr*)" << expr2.c_str() << ")->followDefs() ){" << std::endl;
        write_code( ((CExpr*)code)->kids[2], os, ind+1, retModStr );
        indent( os, ind );
        os << "}else{" << std::endl;
        write_code( ((CExpr*)code)->kids[3], os, ind+1, retModStr );
        indent( os, ind );
        os << "}" << std::endl;
        //clean up memory
        write_dec( expr1, os, ind );
        write_dec( expr2, os, ind );
      }
      break;
    case IFMARKED:
      {
        //calculate the value for the expression
        std::string expr;
        write_expr( ((CExpr*)code)->kids[1], os, ind, expr, opt_write_check_sym_expr );
        //if mark is set, write code for kids[1]
        indent( os, ind );
        os << "if ( ((SymExpr*)" << expr.c_str() << "->followDefs())->getmark(";
        os << ((IntExpr*)((CExpr*)code)->kids[0])->get_num() << ")){" << std::endl;
        write_code( ((CExpr*)code)->kids[2], os, ind+1, retModStr );
        //else write code for kids[2]
        indent( os, ind );
        os << "}else{" << std::endl;
        write_code( ((CExpr*)code)->kids[3], os, ind+1, retModStr );
        indent( os, ind );
        os << "}" << std::endl;
        //clean up memory
        write_dec( expr, os, ind );
      }
      break;
#endif
    case ADD:
    case MUL:
    case DIV:
      {
        //calculate the value for the first expression
        std::string expr1;
        write_expr( ((CExpr*)code)->kids[0], os, ind, expr1 );
        //calculate the value for the second expression
        std::string expr2;
        write_expr( ((CExpr*)code)->kids[1], os, ind, expr2 );
        std::ostringstream ss;
        ss << "rnum" << rnumCount;
        rnumCount++;
        indent( os, ind );
        os << "if( " << expr1.c_str() << "->followDefs()->getclass()==INT_EXPR ){" << std::endl;
        indent( os, ind+1 );
        os << "mpz_t " << ss.str().c_str() << ";" << std::endl;
        indent( os, ind+1 );
        os << "mpz_init(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind+1 );
        os << "mpz_";
        if( code->getop()==ADD )
          os << "add";
        else
          os << "mul";
        os << "( " << ss.str().c_str() << ", ((IntExpr*)" << expr1.c_str() << "->followDefs())->n, ((IntExpr*)" << expr2.c_str() << "->followDefs())->n);" << std::endl;
        indent( os, ind+1 );
        os << retModString.c_str() << "new IntExpr(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind );
        os << "}else if( " << expr1.c_str() << "->followDefs()->getclass()==RAT_EXPR ){" << std::endl;
        indent( os, ind+1 );
        os << "mpq_t " << ss.str().c_str() << ";" << std::endl;
        indent( os, ind+1 );
        os << "mpq_init(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind+1 );
        os << "mpq_";
        if( code->getop()==ADD )
          os << "add";
        else if( code->getop()==MUL )
          os << "mul";
        else
          os << "div";
        os << "( " << ss.str().c_str() << ", ((RatExpr*)" << expr1.c_str() << "->followDefs())->n, ((RatExpr*)" << expr2.c_str() << "->followDefs())->n);" << std::endl;
        indent( os, ind+1 );
        os << retModString.c_str() << "new RatExpr(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind );
        os << "}" << std::endl;
        //clean up memory
        write_dec( expr1, os, ind );
        write_dec( expr2, os, ind );
      }
      break;
    case NEG:
      {
        //calculate the value for the first expression
        std::string expr1;
        write_expr( ((CExpr*)code)->kids[0], os, ind, expr1 );
        std::ostringstream ss;
        ss << "rnum" << rnumCount;
        rnumCount++;
        indent( os, ind );
        os << "if( " << expr1.c_str() << "->followDefs()->getclass()==INT_EXPR ){" << std::endl;
        indent( os, ind+1 );
        os << "mpz_t " << ss.str().c_str() << ";" << std::endl;
        indent( os, ind+1 );
        os << "mpz_init(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind+1 );
        os << "mpz_neg( " << ss.str().c_str() << ", ((IntExpr*)" << expr1.c_str() << "->followDefs())->n );" << std::endl;
        indent( os, ind+1 );
        os << retModString.c_str() << "new IntExpr(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind );
        os << "}else if( " << expr1.c_str() << "->followDefs()->getclass()==RAT_EXPR ){" << std::endl;
        indent( os, ind+1 );
        os << "mpq_t " << ss.str().c_str() << ";" << std::endl;
        indent( os, ind+1 );
        os << "mpq_init(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind+1 );
        os << "mpq_neg( " << ss.str().c_str() << ", ((RatExpr*)" << expr1.c_str() << "->followDefs())->n );" << std::endl;
        indent( os, ind+1 );
        os << retModString.c_str() << "new RatExpr(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind );
        os << "}" << std::endl;
        //clean up memory
        write_dec( expr1, os, ind );
      }
      break;
    case IFNEG:
    case IFZERO:
      {
        std::string expr1;
        write_expr( ((CExpr*)code)->kids[0], os, ind, expr1 );
        indent( os, ind );
        os << "if( " << expr1.c_str() << "->followDefs()->getclass()==INT_EXPR ){" << std::endl;
        indent( os, ind+1 );
        os << "if( mpz_sgn( ((IntExpr *)" << expr1.c_str() << "->followDefs())->n ) ";
        if( code->getop()==IFNEG )
          os << "<";
        else
          os << "==";
        os << " 0 ){" << std::endl;
        write_code( ((CExpr*)code)->kids[1], os, ind+2, retModStr );
        indent( os, ind+1 );
        os << "}else{" << std::endl;
        write_code( ((CExpr*)code)->kids[2], os, ind+2, retModStr );
        indent( os, ind+1 );
        os << "}" << std::endl;
        indent( os, ind );
        os << "}else if( " << expr1.c_str() << "->followDefs()->getclass()==RAT_EXPR ){" << std::endl;
        indent( os, ind+1 );
        os << "if( mpq_sgn( ((RatExpr *)" << expr1.c_str() << "->followDefs())->n ) ";
        if( code->getop()==IFNEG )
          os << "<";
        else
          os << "==";
        os << " 0 ){" << std::endl;
        write_code( ((CExpr*)code)->kids[1], os, ind+2, retModStr );
        indent( os, ind+1 );
        os << "}else{" << std::endl;
        write_code( ((CExpr*)code)->kids[2], os, ind+2, retModStr );
        indent( os, ind+1 );
        os << "}" << std::endl;
        indent( os, ind );
        os << "}" << std::endl;
        //clean up memory
        write_dec( expr1, os, ind );
      }
      break;
    case RUN:/*?*/break;
    case PI:/*?*/break;
    case LAM:/*?*/break;
    case TYPE:/*?*/break;
    case KIND:/*?*/break;
    case ASCRIBE:/*?*/break;
    case MPZ:/*?*/break;
    case PROG:/*?*/break;
    case PROGVARS:/*?*/break;
    case PAT:/*?*/break;
    }
    break;
  }
}
Esempio n. 26
0
int
inject_code(int fd, inject_data_t *inject, char **err)
{
  elf_data_t elf;
  int ret;
  off_t align;
  size_t n;

  elf.fd = fd;
  elf.e  = NULL;

  if(elf_version(EV_CURRENT) == EV_NONE) {
    (*err) = "failed to initialize libelf";
    goto fail;
  }

  /* Use libelf to read the file, but do writes manually */
  elf.e = elf_begin(elf.fd, ELF_C_READ, NULL);
  if(!elf.e) {
    (*err) = "failed to open elf file";
    goto fail;
  }

  if(elf_kind(elf.e) != ELF_K_ELF) {
    (*err) = "not an elf executable";
    goto fail;
  }

  ret = gelf_getclass(elf.e);
  switch(ret) {
  case ELFCLASSNONE:
    (*err) = "unknown elf class";
    goto fail;
  case ELFCLASS32:
    elf.bits = 32;
    break;
  default:
    elf.bits = 64;
    break;
  }

  /* Get executable header */
  if(!gelf_getehdr(elf.e, &elf.ehdr)) {
    (*err) = "failed to get executable header";
    goto fail;
  }

  /* Find a rewritable program header */
  if(find_rewritable_segment(&elf, inject, err) < 0) {
    goto fail;
  }

  /* Write the injected code to the binary */
  if(write_code(&elf, inject, err) < 0) {
    goto fail;
  }

  if (inject->secaddr == 0)
	  find_injected_secaddr(&elf,inject);

  /* Fix alignment of code address */
  align = 0x1000;
  inject->secaddr = inject->secaddr - inject->len;
  n = (inject->off % align) - (inject->secaddr % align);
  if(n > 0) {
    inject->secaddr -= align;
  }
  inject->secaddr += n;
  fprintf(finfo,"Inject=%lx\n",inject->secaddr);

  /* Rewrite a section for the injected code */
  if(rewrite_code_section(&elf, inject, err) < 0) {
    goto fail;
  }

  /* Update the name of the rewritten section */
  if(rewrite_section_name(&elf, inject, err) < 0) {
    goto fail;
  }

  /* Rewrite a segment for the added code section */
  if(rewrite_code_segment(&elf, inject, err) < 0) {
    goto fail;
  }

  /* Rewrite entry point if requested */
  if(inject->entry >= 0) {
    if(rewrite_entry_point(&elf, inject, err) < 0) {
      goto fail;
    }
  }

  ret = 0;
  goto cleanup;

fail:
  ret = -1;

cleanup:
  if(elf.e) {
    elf_end(elf.e);
  }

  return ret;
}
Esempio n. 27
0
void ProcessIO(void)
{
	char oldPGDtris;
	char PIN;
	static byte counter=0;
	int nBytes;
	unsigned long address;
	
	// When the device is plugged in, the leds give the numbers 1, 2, 3, 4, 5. 
	//After configured state, the leds are controlled by the next lines in this function
	if((usb_device_state < CONFIGURED_STATE)||(UCONbits.SUSPND==1))
	{
		BlinkUSBStatus();
		return;
	}
	

	nBytes=USBGenRead((byte*)input_buffer,64);
	if(nBytes>0)
	{
		switch(input_buffer[0])
		{
			case CMD_ERASE:
				setLeds(LEDS_ON | LEDS_WR);
				output_buffer[0]=bulk_erase(picfamily,pictype,input_buffer[1]);
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_READ_ID:
				setLeds(LEDS_ON | LEDS_RD);
				switch(picfamily)
				{
					case PIC24:
					case dsPIC30:
						read_code(picfamily,pictype,0xFF0000,(unsigned char*)output_buffer,2,3);
						break;
					case PIC18:
					case PIC18J:
					case PIC18K:
						read_code(picfamily,pictype,0x3FFFFE,(unsigned char*)output_buffer,2,3);  //devid is at location 0x3ffffe   for PIC18 devices
						break;
					case PIC16:
						set_vdd_vpp(picfamily, pictype, 0);
						read_code(picfamily,pictype,0x2006,(unsigned char*)output_buffer,2,3);  //devid is at location 0x2006  for PIC16 devices
						break;
				}
				counter=2;
				setLeds(LEDS_ON);
				break;
			case CMD_WRITE_CODE:
				setLeds(LEDS_ON | LEDS_WR);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				output_buffer[0]=write_code(picfamily,pictype,address, (unsigned char*)(input_buffer+6),input_buffer[1],input_buffer[5]);
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_READ_CODE:
				setLeds(LEDS_ON | LEDS_RD);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				PIN=read_code(picfamily,pictype,address,(unsigned char*)output_buffer,input_buffer[1],input_buffer[5]);
				if(PIN==3)output_buffer[0]=0x3;
				counter=input_buffer[1];
				setLeds(LEDS_ON);
				break;
			case CMD_WRITE_DATA:
				setLeds(LEDS_ON | LEDS_WR);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				output_buffer[0]=write_data(picfamily,pictype,address, (unsigned char*)(input_buffer+6),input_buffer[1],input_buffer[5]); 
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_READ_DATA:
				setLeds(LEDS_ON | LEDS_RD);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				read_data(picfamily,pictype,address,(unsigned char*)output_buffer,input_buffer[1],input_buffer[5]); 
				counter=input_buffer[1];
				setLeds(LEDS_ON);
				break;
			case CMD_WRITE_CONFIG:
				setLeds(LEDS_ON | LEDS_WR);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				output_buffer[0]=write_config_bits(picfamily, pictype, address, (unsigned char*)(input_buffer+6),input_buffer[1],input_buffer[5]);
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_SET_PICTYPE:
				output_buffer[0]=set_pictype(input_buffer+1);
				//output_buffer[0]=1; //Ok
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_FIRMWARE_VERSION:
				strcpypgm2ram((char*)output_buffer,(const far rom char*)upp_version);
				counter=18;
				setLeds(LEDS_ON);

				break;
			case CMD_DEBUG:
				setLeds(LEDS_ON | LEDS_WR | LEDS_RD);
				switch(input_buffer[1])
				{
					case 0:
						set_vdd_vpp(dsP30F, dsPIC30, 1);
						output_buffer[0]=1;
						counter=1;	
						break;
					case 1:
						set_vdd_vpp(dsP30F, dsPIC30, 0);
						output_buffer[0]=1;
						counter=1;	
						break;
					case 2:
						dspic_send_24_bits(((unsigned long)input_buffer[2])|
								((unsigned long)input_buffer[3])<<8|
								((unsigned long)input_buffer[4])<<16);
						output_buffer[0]=1;
						counter=1;
						break;
					case 3:
						nBytes =  dspic_read_16_bits(1);
						output_buffer[0]=(unsigned char)nBytes;
						output_buffer[1]=(unsigned char)(nBytes>>8);
						counter=2;
						break;
						
				}
				break;
			case CMD_GET_PIN_STATUS:
				switch(input_buffer[1])
				{
					case SUBCMD_PIN_PGC:
						if((!TRISPGC_LOW)&&(!PGC_LOW)) //3.3V levels
						{
							if(PGC) output_buffer[0] = PIN_STATE_3_3V;
							else output_buffer[0] = PIN_STATE_0V;
						}
						else	//5V levels
						{
							if(PGC) output_buffer[0] = PIN_STATE_5V;
							else output_buffer[0] = PIN_STATE_0V;
						}
						counter=1;
						break;
					case SUBCMD_PIN_PGD:
						if(TRISPGD)//PGD is input
						{
							if(PGD_READ) output_buffer[0] = PIN_STATE_5V;
							else output_buffer[0] = PIN_STATE_0V;
						}
						else
						{							
							if((!TRISPGD_LOW)&&(!PGD_LOW)) //3.3V levels
							{
								if(PGD) output_buffer[0] = PIN_STATE_3_3V;
								else output_buffer[0] = PIN_STATE_0V;
							}
							else	//5V levels
							{
								if(PGD) output_buffer[0] = PIN_STATE_5V;
								else output_buffer[0] = PIN_STATE_0V;
							}
						}
						counter=1;
						break;
					case SUBCMD_PIN_VDD:
						if(VDD) output_buffer[0] = PIN_STATE_FLOAT;
						else output_buffer[0] = PIN_STATE_5V;
						counter = 1;
						break;
					case SUBCMD_PIN_VPP:
						counter=1;
						if(!VPP){output_buffer[0] = PIN_STATE_12V;break;}
						if(VPP_RST){output_buffer[0] = PIN_STATE_0V;break;}
						if(VPP_RUN){output_buffer[0] = PIN_STATE_5V;break;}
						output_buffer[0] = PIN_STATE_FLOAT;
						break;
					case SUBCMD_PIN_VPP_VOLTAGE:
						ReadAdc(output_buffer);
						counter=2;
						break;
					default:
						output_buffer[0]=3;
						counter=1;
						break;
				}
				break;
			case CMD_SET_PIN_STATUS:
				switch(input_buffer[1])
				{
					case SUBCMD_PIN_PGC:
						switch(input_buffer[2])
						{
							case PIN_STATE_0V:
								TRISPGC = 0;
								PGC = 0;
								TRISPGC_LOW = 1;
								PGC_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_3_3V:
								TRISPGC = 0;
								PGC = 1;
								TRISPGC_LOW = 0;
								PGC_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_5V:
								TRISPGC = 0;
								PGC = 1;
								TRISPGC_LOW = 1;
								PGC_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					case SUBCMD_PIN_PGD:
						switch(input_buffer[2])
						{
							case PIN_STATE_0V:
								TRISPGD = 0;
								PGD = 0;
								TRISPGD_LOW = 1;
								PGD_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_3_3V:
								TRISPGD = 0;
								PGD = 1;
								TRISPGD_LOW = 0;
								PGD_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_5V:
								TRISPGD = 0;
								PGD = 1;
								TRISPGD_LOW = 1;
								PGD_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_INPUT:
								TRISPGD_LOW = 1;
								TRISPGD = 1;
								output_buffer[0]=1;//ok
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					case SUBCMD_PIN_VDD:
						switch(input_buffer[2])
						{
							case PIN_STATE_5V:
								VDD = 0;
								output_buffer[0]=1;
								break;
							case PIN_STATE_FLOAT:
								VDD = 1;
								output_buffer[0]=1;
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					case SUBCMD_PIN_VPP:
						switch(input_buffer[2])
						{
							case PIN_STATE_0V:
								VPP = 1;
								VPP_RST = 1;
								VPP_RUN = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_5V:
								VPP = 1;
								VPP_RST = 0;
								VPP_RUN = 1;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_12V:
								VPP = 0;
								VPP_RST = 0;
								VPP_RUN = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_FLOAT:
								VPP = 1;
								VPP_RST = 0;
								VPP_RUN = 0;
								output_buffer[0]=1;//ok
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					default:
						output_buffer[0]=3;
				}
				counter=1;
				break;
		}
	}
	if(counter != 0)
	{
		if(!mUSBGenTxIsBusy())
		USBGenWrite((byte*)&output_buffer,counter);
		counter=0;
	}
}//end ProcessIO
void index_container_o2o_max_element(char *type) {
    write_code(index_container_file, "\n\nstatic inline %s index_container_o2o_max_element_%s(struct index_container_o2o_%s *ic) {\n", type, type, type, type);
    write_code(index_container_file, "    return ic->data[ic->header->num_keys - 1].key;\n");
    write_code(index_container_file, "};");
}
void index_container_o2o_exist(char *type) {
    write_code(index_container_file, "\n\nstatic inline int index_container_o2o_exist_%s(struct index_container_o2o_%s *ic, %s key) {\n", type, type, type);
    write_code(index_container_file, "    uint32_t loc;\n");
    write_code(index_container_file, "    return index_container_o2o_bsearch_%s(ic->data, ic->header->num_keys, key, &loc);\n", type);
    write_code(index_container_file, "};");
}
void index_container_o2o_init(char *type) {
    write_code(index_container_file, "\n\nstatic inline int index_container_o2o_init_%s(struct index_container_o2o_%s *ic, const char *filename) {\n", type, type);
    write_code(index_container_file, "    if (0 > file_mapper_init(&ic->fm, filename))\n");
    write_code(index_container_file, "        return -1;\n");
    write_code(index_container_file, "    if (file_mapper_size(&ic->fm) < sizeof(struct index_header_o2o))\n");
    write_code(index_container_file, "        return LOGGER_ERROR(\"invalid file size: %%s\", filename), file_mapper_free(&ic->fm), -1;\n");
    write_code(index_container_file, "    ic->header = file_mapper_data(&ic->fm);\n");
    write_code(index_container_file, "    ic->data = file_mapper_data(&ic->fm) + sizeof(struct index_header_o2o);\n");
    write_code(index_container_file, "    if (0 != memcmp(ic->header->signature, IDX_O2O_SIGNATURE, sizeof(ic->header->signature)))\n");
    write_code(index_container_file, "        return LOGGER_ERROR(\"corrupted file: %%s\", filename), file_mapper_free(&ic->fm), -1;\n");
    write_code(index_container_file, "    return 0;\n");
    write_code(index_container_file, "};");
}