Пример #1
0
int xilinx_read_bit_file(struct xilinx_bit_file *bit_file, const char *filename)
{
	FILE *input_file;
	struct stat input_stat;
	int read_count;

	if (!filename || !bit_file)
		return ERROR_COMMAND_SYNTAX_ERROR;

	if (stat(filename, &input_stat) == -1)
	{
		LOG_ERROR("couldn't stat() %s: %s", filename, strerror(errno));
		return ERROR_PLD_FILE_LOAD_FAILED;
	}

	if (S_ISDIR(input_stat.st_mode))
	{
		LOG_ERROR("%s is a directory", filename);
		return ERROR_PLD_FILE_LOAD_FAILED;
	}

	if (input_stat.st_size == 0) {
		LOG_ERROR("Empty file %s", filename);
		return ERROR_PLD_FILE_LOAD_FAILED;
	}

	if (!(input_file = fopen(filename, "rb")))
	{
		LOG_ERROR("couldn't open %s: %s", filename, strerror(errno));
		return ERROR_PLD_FILE_LOAD_FAILED;
	}

	if ((read_count = fread(bit_file->unknown_header, 1, 13, input_file)) != 13)
	{
		LOG_ERROR("couldn't read unknown_header from file '%s'", filename);
		return ERROR_PLD_FILE_LOAD_FAILED;
	}

	if (read_section(input_file, 2, 'a', NULL, &bit_file->source_file) != ERROR_OK)
		return ERROR_PLD_FILE_LOAD_FAILED;

	if (read_section(input_file, 2, 'b', NULL, &bit_file->part_name) != ERROR_OK)
		return ERROR_PLD_FILE_LOAD_FAILED;

	if (read_section(input_file, 2, 'c', NULL, &bit_file->date) != ERROR_OK)
		return ERROR_PLD_FILE_LOAD_FAILED;

	if (read_section(input_file, 2, 'd', NULL, &bit_file->time) != ERROR_OK)
		return ERROR_PLD_FILE_LOAD_FAILED;

	if (read_section(input_file, 4, 'e', &bit_file->length, &bit_file->data) != ERROR_OK)
		return ERROR_PLD_FILE_LOAD_FAILED;

	LOG_DEBUG("bit_file: %s %s %s,%s %" PRIi32 "", bit_file->source_file, bit_file->part_name,
		bit_file->date, bit_file->time, bit_file->length);

	fclose(input_file);

	return ERROR_OK;
}
Пример #2
0
char *ini_read_string_section(FFILE f, const char *p_section,
                              const char *p_template, char *p_out,
                              int max_len, const char *p_default)
{
  char line[MAX_TOKEN_LEN];
  char section[MAX_TOKEN_LEN];
  bool section_found = FALSE;

  fseek(f, 0, SEEK_SET);
  while (fgets(line, MAX_TOKEN_LEN, f)) {
    if(!section_found) {
      section_found = (bool)read_section(line, section, MAX_TOKEN_LEN);
      if(section_found) {
        section_found = !strncasecmp(p_section, section, MAX_TOKEN_LEN);
      }
      if(section_found)
        continue;
    }
    
    if(section_found && is_section(line)) {
      // we hit next section - so it's not found
      break;
    }
  
    if(section_found) {
      int len = is_token(line, p_template);
      char *p_rest;
      if (len && (p_rest = ini_skip_separator(line + len))) {
        return (ini_read_param(p_rest, p_out, max_len));
      }
    }
  }

  return p_default ? (strcpy(p_out, p_default)) : NULL;
}
Пример #3
0
void disassemble(int32_t fd, Elf32_Ehdr eh, Elf32_Shdr* sh_table)
{
	int32_t i;
	char* sh_str;   /* section-header string-table is also a section. */
	char* buf;      /* buffer to hold contents of the .text section */

	/* Read section-header string-table */
	debug("eh.e_shstrndx = 0x%x\n", eh.e_shstrndx);
	sh_str = read_section(fd, sh_table[eh.e_shstrndx]);

	for(i=0; i<eh.e_shnum; i++) {
		if(!strcmp(".text", (sh_str + sh_table[i].sh_name))) {
			printf("Found section\t\".text\"\n");
			printf("at offset\t0x%08x\n", sh_table[i].sh_offset);
			printf("of size\t\t0x%08x\n", sh_table[i].sh_size);
			break;
		}
	}

	assert(lseek(fd, sh_table[i].sh_offset, SEEK_SET)==sh_table[i].sh_offset);
	buf = malloc(sh_table[i].sh_size);
	if(!buf) {
		printf("Failed to allocate %dbytes!!\n", sh_table[i].sh_size);
		printf("Failed to disassemble!!\n");
		return;
	}
	assert(read(fd, buf, sh_table[i].sh_size)==sh_table[i].sh_size);


	/* Now buf contains the instructions (4bytes each) */

}
Пример #4
0
static void read_sections(void)
{
	struct self_sec s[MAX_SECTIONS];
	struct elf_phdr p;
	u32 i;
	u32 j;
	u32 n_secs;
	u32 self_offset, elf_offset;

	memset(s, 0, sizeof s);
	for (i = 0, j = 0; i < ehdr.e_phnum; i++) {
		read_section(i, &s[j]);
		if (s[j].compressed)
			j++;
	}

	n_secs = j;
	qsort(s, n_secs, sizeof(*s), qsort_compare);

	elf_offset = 0;
	self_offset = header_len;
	j = 0;
	i = 0;
	while (elf_offset < filesize) {
		if (i == n_secs) {
			self_sections[j].offset = self_offset;
			self_sections[j].size = filesize - elf_offset;
			self_sections[j].compressed = 0;
			self_sections[j].size_uncompressed = filesize - elf_offset;
			self_sections[j].elf_offset = elf_offset;
			elf_offset = filesize;
		} else if (self_offset == s[i].offset) {
			self_sections[j].offset = self_offset;
			self_sections[j].size = s[i].size;
			self_sections[j].compressed = 1;
			elf_read_phdr(arch64, elf + phdr_offset +
					(ehdr.e_phentsize * s[i].idx), &p);
			self_sections[j].size_uncompressed = p.p_filesz;
			self_sections[j].elf_offset = p.p_off;

			elf_offset = p.p_off + p.p_filesz;
			self_offset = s[i].next;
			i++;
		} else {
			elf_read_phdr(arch64, elf + phdr_offset +
					(ehdr.e_phentsize * s[i].idx), &p);
			self_sections[j].offset = self_offset;
			self_sections[j].size = p.p_off - elf_offset;
			self_sections[j].compressed = 0;
			self_sections[j].size_uncompressed = self_sections[j].size;
			self_sections[j].elf_offset = elf_offset;

			elf_offset += self_sections[j].size;
			self_offset += s[i].offset - self_offset;
		}
		j++;
	}

	n_sections = j;
}
Пример #5
0
inline BinaryPtr Section::read_binary( const std::string &name )
{
	SectionPtr section = read_section( name );
	if ( !section ) {
		return BinaryPtr();
	}
	return section->as_binary();
}
Пример #6
0
inline const std::string Section::read_string( const std::string &name )
{
	SectionPtr section = read_section( name );
	if ( !section ) {
		return "";
	}
	return section->as_string();
}
Пример #7
0
inline Matrix Section::read_matrix( const std::string &name )
{
	SectionPtr section = read_section( name );
	if ( !section ) {
		return Matrix::identity;
	}
	return section->as_matrix();
}
Пример #8
0
inline Vector Section::read_vector( const std::string &name )
{
	SectionPtr section = read_section( name );
	if ( !section ) {
		return Vector::zero;
	}
	return section->as_vector();
}
Пример #9
0
inline Point Section::read_point( const std::string &name )
{
	SectionPtr section = read_section( name );
	if ( !section ) {
		return Point( 0, 0 );
	}
	return section->as_point();
}
Пример #10
0
inline float Section::read_float( const std::string &name )
{
	SectionPtr section = read_section( name );
	if ( !section ) {
		return 0;
	}
	return section->as_float();
}
Пример #11
0
bool ini_find_string_section(FFILE f, const char *p_section,
                             const char *p_template,
                             long *p_file_start, long *p_file_end)
{
  char line[MAX_TOKEN_LEN];
  char section[MAX_TOKEN_LEN];
  bool section_found = FALSE;
  long file_pos;
  long file_last_line_start = 0;
  long file_last_line_end = 0;

  file_pos = 0;
  fseek(f, 0, SEEK_SET);
  while (fgets(line, MAX_TOKEN_LEN, f)) {
    if(!section_found) {
      section_found = (bool)read_section(line, section, MAX_TOKEN_LEN);
      if(section_found) {
        section_found = !strncasecmp(p_section, section, MAX_TOKEN_LEN);
      }
      if(section_found) {
        file_pos = ftell(f);
        continue;
      }
    }
    
    // Cache last non-section line from recent section
    if(section_found && !is_section(line) && !is_empty(line)) {
      file_last_line_start = file_pos;
      file_last_line_end = ftell(f);
    }
  
    if(section_found && is_section(line)) {
      // we hit next section - so it's not found,
      // create a new entry
      *p_file_start = file_last_line_start;
      *p_file_end = file_last_line_end;
      return(TRUE);
    }
  
    // Replace this line
    if(section_found && is_token(line, p_template)) {
      *p_file_start = file_pos;
      *p_file_end = ftell(f);
      return(TRUE);
    }
    
    file_pos = ftell(f);
  }

  // no section -> create a new one
  return(FALSE);
}
Пример #12
0
/**************************************************************************
* Function:     get_private_profile_int()
* Arguments:    <char *> section - the name of the section to search for
*               <char *> entry - the name of the entry to find the value of
*               <int> def - the default value in the event of a failed read
*               <char *> file_name - the name of the .ini file to read from
* Returns:      the value located at entry
***************************************************************************/
int get_private_profile_int(char *section,
    char *entry, int def, char *file_name)
{   
    FILE *fp = fopen(file_name,"r");
    char buff[MAX_LINE_LENGTH];
    
    if( !fp ) return def; /* Return default value if file does not exist */
    if (!read_section (fp, section)) goto err;
    if (!read_entry (fp, entry, buff, MAX_LINE_LENGTH)) goto err;
	def = read_int_value (buff, def);
err:
	fclose (fp);
	return def;
}
Пример #13
0
int get_private_profile_string(char *section, char *entry, char *def,
    char *buffer, int buffer_len, char *file_name)
{   
    FILE *fp = fopen (file_name,"r");
    char buff[MAX_LINE_LENGTH];
    char *val;
    
    if( !fp ) goto err; /* Return default value if file does not exist */
    if (!read_section (fp, section)) goto err;
    if (!read_entry (fp, entry, buff, MAX_LINE_LENGTH)) goto err;
	val = read_value (buff);
    if(val) def = val;

err:
	if (fp) fclose (fp);
	if (def) {
		strncpy (buffer, def, buffer_len - 1);
		buffer[buffer_len] = '\0';
	}
	else buffer[buffer_len] = '\0';
	return strlen (buffer);
}
Пример #14
0
static int vobjdump(void)
{
  p = vobj;

  if (vlen>4 && p[0]==0x56 && p[1]==0x4f && p[2]==0x42 && p[3]==0x4a) {
    int endian,nsecs,nsyms,i;
    const char *cpu_name;
    struct vobj_symbol *vsymbols = NULL;
    struct vobj_section *vsect = NULL;

    p += 4;	/* skip ID */
    endian = (int)*p++;  /* endianess */
    if (endian<1 || endian>2) {
      fprintf(stderr,"Wrong endianess: %d\n",endian);
      return 1;
    }

    bpb = (int)read_number(0);  /* bits per byte */
    if (bpb != 8) {
      fprintf(stderr,"%d bits per byte not supported!\n",bpb);
      return 1;
    }

    bpt = (int)read_number(0);  /* bytes per taddr */
    if (bpt > sizeof(taddr)) {
      fprintf(stderr,"%d bytes per taddr not supported!\n",bpt);
      return 1;
    }
    bptmask = makemask(bpt*bpb);

    cpu_name = p;
    skip_string();  /* skip cpu-string */
    nsecs = (int)read_number(0);  /* number of sections */
    nsyms = (int)read_number(0);  /* number of symbols */

    /* print header */
    print_sep();
    printf("VOBJ %s (%s endian), %d bits per byte, %d bytes per word.\n"
           "%d symbol%s.\n%d section%s.\n",
           cpu_name,endian_name[endian-1],bpb,bpt,
           nsyms,nsyms==1?emptystr:sstr,nsecs,nsecs==1?emptystr:sstr);

    /* read symbols */
    if (nsyms) {
      if (vsymbols = malloc(nsyms * sizeof(struct vobj_symbol))) {
        for (i=0; i<nsyms; i++)
          read_symbol(&vsymbols[i]);
      }
      else {
        fprintf(stderr,"Cannot allocate %ld bytes for symbols!\n",
                (long)(nsyms * sizeof(struct vobj_symbol)));
        return 1;
      }
    }

    /* read and print sections */
    if (vsect = malloc(nsecs * sizeof(struct vobj_section))) {
      for (i=0; i<nsecs; i++)
        read_section(&vsect[i],vsymbols,nsyms);
    }
    else {
      fprintf(stderr,"Cannot allocate %ld bytes for sections!\n",
              (long)(nsecs * sizeof(struct vobj_section)));
      return 1;
    }

    /* print symbols */
    for (i=0; i<nsyms; i++) {
      struct vobj_symbol *vs = &vsymbols[i];

      if (i == 0) {
        printf("\n");
        print_sep();
        printf("SYMBOL TABLE\n"
               "file offs bind size     type def      value    name\n");
      }
      if (!strncmp(vs->name," *current pc",12))
        continue;
      printf("%08llx: %-4s %08x %-4s %8.8s %8llx %s\n",
             BPTMASK(vs->offs),bind_name(vs->flags),(unsigned)vs->size,
             type_name[TYPE(vs)],def_name(vs,vsect,nsecs),
             BPTMASK(vs->val),vs->name);
    }
  }
  else {
    fprintf(stderr,"Not a VOBJ file!\n");
    return 1;
  }

  return 0;
}
void initialize_library(const char *uGensPluginPath)
{
	gCmdLib     = new HashTable<SC_LibCmd, Malloc>(&gMalloc, 64, true);
	gUnitDefLib = new HashTable<UnitDef, Malloc>(&gMalloc, 512, true);
	gBufGenLib  = new HashTable<BufGen, Malloc>(&gMalloc, 512, true);
	gPlugInCmds = new HashTable<PlugInCmd, Malloc>(&gMalloc, 64, true);

	initMiscCommands();

#ifdef STATIC_PLUGINS
	IO_Load(&gInterfaceTable);
	Osc_Load(&gInterfaceTable);
	Delay_Load(&gInterfaceTable);
	BinaryOp_Load(&gInterfaceTable);
	Filter_Load(&gInterfaceTable);
	Gendyn_Load(&gInterfaceTable);
	LF_Load(&gInterfaceTable);
	Noise_Load(&gInterfaceTable);
	MulAdd_Load(&gInterfaceTable);
	Grain_Load(&gInterfaceTable);
	Pan_Load(&gInterfaceTable);
	Reverb_Load(&gInterfaceTable);
	Trigger_Load(&gInterfaceTable);
	UnaryOp_Load(&gInterfaceTable);
	DiskIO_Load(&gInterfaceTable);
	PhysicalModeling_Load(&gInterfaceTable);
	Test_Load(&gInterfaceTable);
	Demand_Load(&gInterfaceTable);
	DynNoise_Load(&gInterfaceTable);
#if defined(SC_IPHONE) && !TARGET_IPHONE_SIMULATOR
	iPhone_Load(&gInterfaceTable);
#endif
	return;
#endif

	// If uGensPluginPath is supplied, it is exclusive.
	bool loadUGensExtDirs = true;
	if(uGensPluginPath){
		loadUGensExtDirs = false;
		SC_StringParser sp(uGensPluginPath, SC_STRPARSE_PATHDELIMITER);
		while (!sp.AtEnd()) {
			PlugIn_LoadDir(const_cast<char *>(sp.NextToken()), true);
		}
	}

	if(loadUGensExtDirs) {
#ifdef SC_PLUGIN_DIR
		// load globally installed plugins
		if (sc_DirectoryExists(SC_PLUGIN_DIR)) {
			PlugIn_LoadDir(SC_PLUGIN_DIR, true);
		}
#endif

		// load default plugin directory
		char pluginDir[MAXPATHLEN];
		sc_GetResourceDirectory(pluginDir, MAXPATHLEN);
		sc_AppendToPath(pluginDir, SC_PLUGIN_DIR_NAME);

		if (sc_DirectoryExists(pluginDir)) {
			PlugIn_LoadDir(pluginDir, true);
		}
	}

	// get extension directories
	char extensionDir[MAXPATHLEN];
	if (!sc_IsStandAlone() && loadUGensExtDirs) {
		// load system extension plugins
		sc_GetSystemExtensionDirectory(extensionDir, MAXPATHLEN);
		PlugIn_LoadDir(extensionDir, false);

		// load user extension plugins
		sc_GetUserExtensionDirectory(extensionDir, MAXPATHLEN);
		PlugIn_LoadDir(extensionDir, false);

		// load user plugin directories
		SC_StringParser sp(getenv("SC_PLUGIN_PATH"), SC_STRPARSE_PATHDELIMITER);
		while (!sp.AtEnd()) {
			PlugIn_LoadDir(const_cast<char *>(sp.NextToken()), true);
		}
	}
#ifdef SC_DARWIN
	/* on darwin plugins are lazily loaded (dlopen uses mmap internally), which can produce audible
		glitches when UGens have to be paged-in. to work around this we preload all the plugins by
		iterating through their memory space. */

	unsigned long images = _dyld_image_count();
	for(unsigned long i = 0; i < images; i++) {
		const mach_header	*hdr = _dyld_get_image_header(i);
		unsigned long slide = _dyld_get_image_vmaddr_slide(i);
		const char *name = _dyld_get_image_name(i);
		uint32_t	size;
		char *sect;

		if(!strcmp(name + (strlen(name) - 4), ".scx")) {
			read_section(hdr, slide, "__TEXT", "__text");
			read_section(hdr, slide, "__TEXT", "__const");
			read_section(hdr, slide, "__TEXT", "__cstring");
			read_section(hdr, slide, "__TEXT", "__picsymbol_stub");
			read_section(hdr, slide, "__TEXT", "__symbol_stub");
			read_section(hdr, slide, "__TEXT", "__const");
			read_section(hdr, slide, "__TEXT", "__literal4");
			read_section(hdr, slide, "__TEXT", "__literal8");

			read_section(hdr, slide, "__DATA", "__data");
			read_section(hdr, slide, "__DATA", "__la_symbol_ptr");
			read_section(hdr, slide, "__DATA", "__nl_symbol_ptr");
			read_section(hdr, slide, "__DATA", "__dyld");
			read_section(hdr, slide, "__DATA", "__const");
			read_section(hdr, slide, "__DATA", "__mod_init_func");
			read_section(hdr, slide, "__DATA", "__bss");
			read_section(hdr, slide, "__DATA", "__common");

			read_section(hdr, slide, "__IMPORT", "__jump_table");
			read_section(hdr, slide, "__IMPORT", "__pointers");
		}
	}
#endif
}
Пример #16
0
Файл: rtm.c Проект: 8l/linoleum
/* the program */
int main(int argc, char **argv, char **env)
{
	int i, toAdd, parameterLen;
	proc_t isokernelP;

	environment = env;

	/* initialize IParagraph */
	IParagraph = (struct LNLMINIT *) &ipData[8];
	/* check the size of the application name */
	if (strlen(argv[0]) >= 32768)
		programError("ERROR: Application name too long.");
	/* read application name into: dmsStockFilename */
	/* translate the references to a real path */
	realpath(argv[0], dmsStockFilename);

	/* - reads commandline parameters into: dmsParameters */
	dmsParameters[0] = '\0';
	parameterLen = 0;
	for (i = 1; i < argc; i++) {
		/* check if there are spaces in the current entry */
		if (strchr(argv[i], ' ') == NULL) {
			/* just insert string */
			toAdd = strlen(argv[i]);
			if ((parameterLen + toAdd + 1) >= 32768)
				programError
				    ("ERROR: Too many commandline parameters.");

			strcpy(&dmsParameters[parameterLen], argv[i]);
			parameterLen += toAdd;
			strcpy(&dmsParameters[parameterLen], " ");
			parameterLen++;
		} else {
			/* surround string by quotes */
			toAdd = strlen(argv[i]);
			if ((parameterLen + toAdd + 3) >= 32768)
				programError
				    ("ERROR: Too many commandline parameters.");

			strcat(&dmsParameters[parameterLen], "\"");
			parameterLen++;
			strcat(&dmsParameters[parameterLen], argv[i]);
			parameterLen += toAdd;
			strcat(&dmsParameters[parameterLen], "\" ");
			parameterLen++;
		}
	}
	/* terminate the parameter string if necessary */
	if (parameterLen > 0)
		dmsParameters[--parameterLen] = '\0';

	/* allocate and initialize L.IN.OLEUM code area */
	init_section(&pCode, IParagraph->app_code_size, "code");
	/* allocate and initialize application workspace */
	init_section(&pWorkspace, IParagraph->default_ramtop, "workspace");
	current_ramtop = IParagraph->default_ramtop;

	/* open stockfile for reading */
	openFile = fopen(dmsStockFilename, "r");
	if (!openFile)
		programError("ERROR: Failed to open Stockfile");

	/* read the initialised workspace */
	read_section(&pWorkspace,
		     IParagraph->physwsentry,
		     IParagraph->app_ws_size, "workspace");
	/* set pointer to uninitialized workspace */
	pUIWorkspace = &pWorkspace[IParagraph->app_ws_size];
	/* read the code section */
	read_section(&pCode,
		     (IParagraph->app_ws_size * sizeof(unit)) +
		     IParagraph->physwsentry, IParagraph->app_code_size,
		     "code");
	/* set pointer to application start address */
	pCodeEntry = (proc_t) (unit) & pCode[IParagraph->app_code_entry];

	/* close file handle */
	fclose(openFile);

	/* transfer commandline parameters */
	btrsstring(&pUIWorkspace[mm_ProcessCommandLine], dmsParameters);

	/* initialize rest of workspace */
	isokernelP = isokernel;
	pWorkspace[mm_ProcessOrigin] = (unit) pCode;
	pUIWorkspace[mm_ProcessISOcall] = ((unit) isokernelP - (unit) pCode);
	pUIWorkspace[mm_ProcessRAMtop] = IParagraph->default_ramtop;
	pUIWorkspace[mm_ProcessPriority] = IParagraph->app_code_pri;

	/* setup isokernel */
	PRINT("initializing ISOKERNEL...\n");
	assert(lino_display_init(IParagraph->lfb_x_atstartup,
				 IParagraph->lfb_y_atstartup,
				 IParagraph->lfb_w_atstartup,
				 IParagraph->lfb_h_atstartup, NULL));
	assert(initPointerCommand());
	assert(initNetCommand());

	PRINT1("%s: run main linoleum program.\n", __func__);

	linoleum();
	if (xAtExit == FAIL) {
		int size = 256, n, result;
		char *arguments = malloc(size);
		while (1) {
			n = snprintf(arguments,
				     size,
				     "xmessage -center \"%s\n\nRegisters after execution.\nA: %d\nB: %d\nC: %d\nD: %d\nE: %d\nX: %d\n\"",
				     dmsStockFilename,
				     (int) aAtExit,
				     (int) bAtExit,
				     (int) cAtExit,
				     (int) dAtExit,
				     (int) eAtExit, (int) xAtExit);
			if (n > -1 && n < size)
				break;
			if (n > -1)
				size = n + 1;
			else
				size *= 2;

			arguments = realloc(arguments, size);
		}
		result = system(arguments);
		free(arguments);
		if (result != 0) {
			printf(dmsStockFilename);
			printf("Registers after execution.\n");
			printf("A: %d\n", (int) aAtExit);
			printf("B: %d\n", (int) bAtExit);
			printf("C: %d\n", (int) cAtExit);
			printf("D: %d\n", (int) dAtExit);
			printf("E: %d\n", (int) eAtExit);
			printf("X: %d\n", (int) xAtExit);
		}
	}

	/* break down isokernel */
	PRINT("Clear remaining isokernel stuff\n");
	lino_display_close();

	/* free allocated memory */
	free(pCode);
	free(pWorkspace);

	/* terminate program */
	return (0);
}
Пример #17
0
static void vobj_read(struct GlobalVars *gv,struct LinkFile *lf,uint8_t *data)
{
  struct ObjectUnit *u;
  int bpb,bpt,nsecs,nsyms,i;
  struct vobj_symbol *vsymbols = NULL;

  if (lf->type == ID_LIBARCH) {  /* check ar-member for correct format */
    vobj_check_ar_type(fff[lf->format],lf->pathname,data);
  }
  p = data + 5;  /* skip ID and endianess */
  bpb = (int)read_number();  /* bits per byte */
  if (bpb != 8) {
    /* bits per byte are not supported */
    error(113,lf->pathname,fff[lf->format]->tname,bpb);
  }
  bpt = (int)read_number();  /* bytes per taddr */
  if (bpt > sizeof(taddr)) {
    /* n bytes per target-address are not supported */
    error(114,lf->pathname,fff[lf->format]->tname,bpt);
  }
  skip_string();  /* skip cpu-string */

  u = create_objunit(gv,lf,lf->objname);
  nsecs = (int)read_number();  /* number of sections */
  nsyms = (int)read_number();  /* number of symbols */

  if (nsyms) {
    vsymbols = alloc(nsyms * sizeof(struct vobj_symbol));
    for (i=0; i<nsyms; i++)
      read_symbol(&vsymbols[i]);
  }

  for (i=1; i<=nsecs; i++)
    read_section(gv,u,(uint32_t)i,vsymbols,nsyms);

  /* add relocatable and absolute symbols, ignore unknown symbol-refs */
  for (i=0; i<nsyms; i++) {
    struct vobj_symbol *vs = &vsymbols[i];
    struct Section *s = NULL;
    uint8_t type,bind,info;

    if (vs->flags & WEAK)
      bind = SYMB_WEAK;
    else if (vs->flags & EXPORT)
      bind = SYMB_GLOBAL;
    else
      bind = SYMB_LOCAL;

    if (vs->flags & COMMON) {
      type = SYM_COMMON;
      s = common_section(gv,u);
    }
    else if (vs->type == EXPRESSION) {
      type = SYM_ABS;
      s = abs_section(u);
    }
    else if (vs->type == LABSYM) {
      type = SYM_RELOC;
      if (!(s = find_sect_id(u,vs->sec))) {
        /* a section with this index doesn't exist! */
        error(53,lf->pathname,vs->name,lf->objname,vs->sec);
      }
    }
    else if (vs->type == IMPORT) {
      type = 0;  /* ignore unknown symbols */
    }
    else {
      /* illegal symbol type */
      error(116,getobjname(u),fff[lf->format]->tname,
            vs->type,vs->name,lf->objname);
      type = 0;
    }

    switch (TYPE(vs)) {
      case TYPE_UNKNOWN: info = SYMI_NOTYPE; break;
      case TYPE_OBJECT: info = SYMI_OBJECT; break;
      case TYPE_FUNCTION: info = SYMI_FUNC; break;
      case TYPE_SECTION: type = 0; break;  /* ignore SECTION symbols */
      case TYPE_FILE: info = SYMI_FILE; break;
      default:
        error(54,lf->pathname,TYPE(vs),vs->name,lf->objname);
        type = 0;
        break;
    }

    if (type) {
      if (bind == SYMB_LOCAL)
        addlocsymbol(gv,s,vs->name,NULL,(lword)vs->val,type,0,info,vs->size);
      else
        addsymbol(gv,s,vs->name,NULL,(lword)vs->val,
                  type,0,info,bind,vs->size,TRUE);
    }
  }
  if (nsyms)
    free(vsymbols);

  add_objunit(gv,u,TRUE);  /* add object unit and fix relocations */
}
CAMLexport void caml_main(char **argv)
{
  int fd, pos;
  struct exec_trailer trail;
  struct channel * chan;
  value res;
  char * shared_lib_path, * shared_libs, * req_prims;
  char * exe_name;
#ifdef __linux__
  static char proc_self_exe[256];
#endif

  /* Machine-dependent initialization of the floating-point hardware
     so that it behaves as much as possible as specified in IEEE */
  caml_init_ieee_floats();
#ifdef _MSC_VER
  caml_install_invalid_parameter_handler();
#endif
  caml_init_custom_operations();
  caml_ext_table_init(&caml_shared_libs_path, 8);
  caml_external_raise = NULL;
  /* Determine options and position of bytecode file */
#ifdef DEBUG
  caml_verb_gc = 0xBF;
#endif
  parse_camlrunparam();
  pos = 0;
  exe_name = argv[0];
#ifdef __linux__
  if (caml_executable_name(proc_self_exe, sizeof(proc_self_exe)) == 0)
    exe_name = proc_self_exe;
#endif
  fd = caml_attempt_open(&exe_name, &trail, 0);
  if (fd < 0) {
    pos = parse_command_line(argv);
    if (argv[pos] == 0)
      caml_fatal_error("No bytecode file specified.\n");
    exe_name = argv[pos];
    fd = caml_attempt_open(&exe_name, &trail, 1);
    switch(fd) {
    case FILE_NOT_FOUND:
      caml_fatal_error_arg("Fatal error: cannot find file '%s'\n", argv[pos]);
      break;
    case BAD_BYTECODE:
      caml_fatal_error_arg(
        "Fatal error: the file '%s' is not a bytecode executable file\n",
        exe_name);
      break;
    }
  }
  /* Read the table of contents (section descriptors) */
  caml_read_section_descriptors(fd, &trail);
  /* Initialize the abstract machine */
  caml_init_gc (minor_heap_init, heap_size_init, heap_chunk_init,
                percent_free_init, max_percent_free_init);
  caml_init_stack (max_stack_init);
  init_atoms();
  /* Initialize the interpreter */
  caml_interprete(NULL, 0);
  /* Initialize the debugger, if needed */
  caml_debugger_init();
  /* Load the code */
  caml_code_size = caml_seek_section(fd, &trail, "CODE");
  caml_load_code(fd, caml_code_size);
  /* Build the table of primitives */
  shared_lib_path = read_section(fd, &trail, "DLPT");
  shared_libs = read_section(fd, &trail, "DLLS");
  req_prims = read_section(fd, &trail, "PRIM");
  if (req_prims == NULL) caml_fatal_error("Fatal error: no PRIM section\n");
  caml_build_primitive_table(shared_lib_path, shared_libs, req_prims);
  caml_stat_free(shared_lib_path);
  caml_stat_free(shared_libs);
  caml_stat_free(req_prims);
  /* Load the globals */
  caml_seek_section(fd, &trail, "DATA");
  chan = caml_open_descriptor_in(fd);
  caml_global_data = caml_input_val(chan);
  caml_close_channel(chan); /* this also closes fd */
  caml_stat_free(trail.section);
  /* Ensure that the globals are in the major heap. */
  caml_oldify_one (caml_global_data, &caml_global_data);
  caml_oldify_mopup ();
  /* Initialize system libraries */
  caml_init_exceptions();
  caml_sys_init(exe_name, argv + pos);
#ifdef _WIN32
  /* Start a thread to handle signals */
  if (getenv("CAMLSIGPIPE"))
    _beginthread(caml_signal_thread, 4096, NULL);
#endif
  /* Execute the program */
  caml_debugger(PROGRAM_START);
  res = caml_interprete(caml_start_code, caml_code_size);
  if (Is_exception_result(res)) {
    caml_exn_bucket = Extract_exception(res);
    if (caml_debugger_in_use) {
      caml_extern_sp = &caml_exn_bucket; /* The debugger needs the
                                            exception value.*/
      caml_debugger(UNCAUGHT_EXC);
    }
    caml_fatal_uncaught_exception(caml_exn_bucket);
  }
}
Пример #19
0
int main(int argc, char* argv[]) {

    if (argc != 3) {
        printf("usage:\n");
        printf("    elf2tinyapp elf_file app_file\n");
        return -1;
    }

    const char *elf_file = argv[1];
    const char *app_file = argv[2];

    printf("elf file: %s\n", elf_file);
    printf("app file: %s\n", app_file);

    struct ELF_SECTION text, rodata, data, bss;
    memset(&text, 0, sizeof(struct ELF_SECTION));
    memset(&rodata, 0, sizeof(struct ELF_SECTION));
    memset(&data, 0, sizeof(struct ELF_SECTION));
    memset(&bss, 0, sizeof(struct ELF_SECTION));

    text.name = ".text";
    rodata.name = ".rodata";
    data.name = ".data";
    bss.name = ".bss";

    read_section(elf_file, &text);
    read_section(elf_file, &rodata);
    read_section(elf_file, &data);
    read_section(elf_file, &bss);

    printf("text size: %d\n", text.size);
    printf("rodata size: %d\n", rodata.size);
    printf("data size: %d\n", data.size);
    printf("bss size: %d\n", bss.size);

    assert(text.size > 0);
    assert(rodata.size >= 0);
    assert(data.size >= 0);
    assert(bss.size >= 0);

    // app header
    struct APP_HEADER header;
    assert(sizeof(header) == 36);

    int inital_data_size = 0;
    if (rodata.size > 0) {
        inital_data_size = rodata.VMA + rodata.size - 0x310000;
    }
    if (data.size > 0) {
        inital_data_size = data.VMA + data.size - 0x310000;
    }
    if (bss.size > 0) {
        inital_data_size = bss.VMA + bss.size - 0x310000;
    }
    assert(inital_data_size >= rodata.size + data.size + bss.size);

    header.total_size = 0x311000;
    memcpy(header.sign, "tiny", 4);
    header.mmarea_size = 0;
    header.data_addr = 0x310000;
    header.data_size = inital_data_size;
    header.inital_data_pos = 0;
    header.opcode = 0xe9000000;
    header.entry_addr = (unsigned int)get_start_address(elf_file) - 0x20;
    header.heap_addr = (header.data_addr + inital_data_size + 3) / 4 * 4;

    // generate tinyapp file
    FILE *app_fp = fopen(app_file, "wb");
    assert(app_fp != 0);

    write_header(app_fp, &header);
    write_section(app_fp, &header, &text);

    write_align4(app_fp);
    header.inital_data_pos = ftell(app_fp);

    write_section(app_fp, &header, &rodata);
    write_section(app_fp, &header, &data);
    write_section(app_fp, &header, &bss);

    // update tinyapp header
    write_header(app_fp, &header);
    fclose(app_fp);

    return 0;
}