Example #1
0
static BOOLEAN
LoadSisState (SIS_STATE *SSPtr, void *fp)
{
	if (
			read_32s (fp, &SSPtr->log_x) != 1 ||
			read_32s (fp, &SSPtr->log_y) != 1 ||
			read_32  (fp, &SSPtr->ResUnits) != 1 ||
			read_32  (fp, &SSPtr->FuelOnBoard) != 1 ||
			read_16  (fp, &SSPtr->CrewEnlisted) != 1 ||
			read_16  (fp, &SSPtr->TotalElementMass) != 1 ||
			read_16  (fp, &SSPtr->TotalBioMass) != 1 ||
			read_a8  (fp, SSPtr->ModuleSlots, NUM_MODULE_SLOTS) != 1 ||
			read_a8  (fp, SSPtr->DriveSlots, NUM_DRIVE_SLOTS) != 1 ||
			read_a8  (fp, SSPtr->JetSlots, NUM_JET_SLOTS) != 1 ||
			read_8   (fp, &SSPtr->NumLanders) != 1 ||
			read_a16 (fp, SSPtr->ElementAmounts, NUM_ELEMENT_CATEGORIES) != 1 ||

			read_str (fp, SSPtr->ShipName, SIS_NAME_SIZE) != 1 ||
			read_str (fp, SSPtr->CommanderName, SIS_NAME_SIZE) != 1 ||
			read_str (fp, SSPtr->PlanetName, SIS_NAME_SIZE) != 1 ||

			read_16  (fp, NULL) != 1 /* padding */
		)
		return FALSE;
	else
	{
		// JMS: Let's make savegames work even between different resolution modes.
		SSPtr->log_x <<= RESOLUTION_FACTOR;
		SSPtr->log_y <<= RESOLUTION_FACTOR;
		return TRUE;
	}
}
Example #2
0
static cdk_error_t
read_pubkey_enc (cdk_stream_t inp, size_t pktlen, cdk_pkt_pubkey_enc_t pke)
{
  size_t i, nenc;

  if (!inp || !pke)
    return CDK_Inv_Value;

  if (DEBUG_PKT)
    _cdk_log_debug ("read_pubkey_enc: %d octets\n", pktlen);

  if (pktlen < 12)
    return CDK_Inv_Packet;
  pke->version = cdk_stream_getc (inp);
  if (pke->version < 2 || pke->version > 3)
    return CDK_Inv_Packet;
  pke->keyid[0] = read_32 (inp);
  pke->keyid[1] = read_32 (inp);
  if (!pke->keyid[0] && !pke->keyid[1])
    pke->throw_keyid = 1;	/* RFC2440 "speculative" keyID */
  pke->pubkey_algo = _pgp_pub_algo_to_cdk (cdk_stream_getc (inp));
  nenc = cdk_pk_get_nenc (pke->pubkey_algo);
  if (!nenc)
    return CDK_Inv_Algo;
  for (i = 0; i < nenc; i++)
    {
      cdk_error_t rc = read_mpi (inp, &pke->mpi[i], 0);
      if (rc)
	return rc;
    }

  return 0;
}
static void stco_shift_offsets_inplace(unsigned char* stco, int offset)
{
  unsigned int entries = read_32(stco + 4);
  unsigned int* table = (unsigned int*)(stco + 8);
  unsigned int i;
  for(i = 0; i != entries; ++i)
    write_32((unsigned char*)&table[i], (read_32((unsigned char*)&table[i]) + offset));
}
Example #4
0
/* Read an old packet CTB and return the length of the body. */
static void
read_old_length (cdk_stream_t inp, int ctb, size_t * r_len, size_t * r_size)
{
  int llen = ctb & 0x03;

  if (llen == 0)
    {
      *r_len = cdk_stream_getc (inp);
      (*r_size)++;
    }
  else if (llen == 1)
    {
      *r_len = read_16 (inp);
      (*r_size) += 2;
    }
  else if (llen == 2)
    {
      *r_len = read_32 (inp);
      (*r_size) += 4;
    }
  else
    {
      *r_len = 0;
      *r_size = 0;
    }
}
Example #5
0
/* Read a new CTB and decode the body length. */
static void
read_new_length (cdk_stream_t inp,
		 size_t * r_len, size_t * r_size, size_t * r_partial)
{
  int c, c1;

  c = cdk_stream_getc (inp);
  (*r_size)++;
  if (c < 192)
    *r_len = c;
  else if (c >= 192 && c <= 223)
    {
      c1 = cdk_stream_getc (inp);
      (*r_size)++;
      *r_len = ((c - 192) << 8) + c1 + 192;
    }
  else if (c == 255)
    {
      *r_len = read_32 (inp);
      (*r_size) += 4;
    }
  else
    {
      *r_len = 1 << (c & 0x1f);
      *r_partial = 1;
    }
}
bool VerilatorTbUtils::loadBin(char *fileName) {
  uint8_t *bin_data;
  int size;
  FILE *bin_file = fopen(fileName, "rb");

  printf("Loading %s\n", fileName);

  if (bin_file == NULL) {
    printf("Error opening bin file\n");
    return false;
  }
  fseek(bin_file, 0, SEEK_END);
  size = ftell(bin_file);
  rewind(bin_file);
  bin_data = (uint8_t *)malloc(size);
  if (fread(bin_data, 1, size, bin_file) != size) {
    printf("Error reading bin file\n");
    return false;
  }

  for (int i=0; i < size; i+=4)
    this->mem[i/4] = read_32(bin_data, i);

  free(bin_data);

  return true;
}
Example #7
0
int bg_f_chunk_read(bg_f_io_t * io, bg_f_chunk_t * ch)
  {
  ch->start = io->ftell_callback(io->data);
  if(!read_32(io, &ch->type) ||
     !read_64(io, &ch->size))
    return 0;
  return 1;
  }
Example #8
0
static cdk_error_t
read_subpkt (cdk_stream_t inp, cdk_subpkt_t * r_ctx, size_t * r_nbytes)
{
  byte c, c1;
  size_t size, nread, n;
  cdk_subpkt_t node;
  cdk_error_t rc;

  if (!inp || !r_nbytes)
    return CDK_Inv_Value;

  if (DEBUG_PKT)
    _cdk_log_debug ("read_subpkt:\n");

  n = 0;
  *r_nbytes = 0;
  c = cdk_stream_getc (inp);
  n++;
  if (c == 255)
    {
      size = read_32 (inp);
      n += 4;
    }
  else if (c >= 192 && c < 255)
    {
      c1 = cdk_stream_getc (inp);
      n++;
      if (c1 == 0)
	return 0;
      size = ((c - 192) << 8) + c1 + 192;
    }
  else if (c < 192)
    size = c;
  else
    return CDK_Inv_Packet;

  node = cdk_subpkt_new (size);
  if (!node)
    return CDK_Out_Of_Core;
  node->size = size;
  node->type = cdk_stream_getc (inp);
  if (DEBUG_PKT)
    _cdk_log_debug (" %d octets %d type\n", node->size, node->type);
  n++;
  node->size--;
  rc = stream_read (inp, node->d, node->size, &nread);
  n += nread;
  if (rc)
    return rc;
  *r_nbytes = n;
  if (!*r_ctx)
    *r_ctx = node;
  else
    cdk_subpkt_add (*r_ctx, node);
  return rc;
}
Example #9
0
static inline COUNT
read_32s (void *fp, SDWORD *v)
{
	DWORD t;
	COUNT ret;
	// value was converted to unsigned when saved
	ret = read_32 (fp, &t);
	// unsigned to signed conversion
	if (v)
		*v = t;
	return ret;
}
Example #10
0
static cdk_error_t
read_onepass_sig (cdk_stream_t inp, size_t pktlen, cdk_pkt_onepass_sig_t sig)
{
  if (!inp || !sig)
    return CDK_Inv_Value;

  if (DEBUG_PKT)
    _cdk_log_debug ("read_onepass_sig: %d octets\n", pktlen);

  if (pktlen != 13)
    return CDK_Inv_Packet;
  sig->version = cdk_stream_getc (inp);
  if (sig->version != 3)
    return CDK_Inv_Packet_Ver;
  sig->sig_class = cdk_stream_getc (inp);
  sig->digest_algo = _pgp_hash_algo_to_gnutls (cdk_stream_getc (inp));
  sig->pubkey_algo = _pgp_pub_algo_to_cdk (cdk_stream_getc (inp));
  sig->keyid[0] = read_32 (inp);
  sig->keyid[1] = read_32 (inp);
  sig->last = cdk_stream_getc (inp);
  return 0;
}
Example #11
0
static cdk_error_t
read_public_key (cdk_stream_t inp, size_t pktlen, cdk_pkt_pubkey_t pk)
{
  size_t i, ndays, npkey;

  if (!inp || !pk)
    return CDK_Inv_Value;

  if (DEBUG_PKT)
    _cdk_log_debug ("read_public_key: %d octets\n", pktlen);

  pk->is_invalid = 1;		/* default to detect missing self signatures */
  pk->is_revoked = 0;
  pk->has_expired = 0;

  pk->version = cdk_stream_getc (inp);
  if (pk->version < 2 || pk->version > 4)
    return CDK_Inv_Packet_Ver;
  pk->timestamp = read_32 (inp);
  if (pk->version < 4)
    {
      ndays = read_16 (inp);
      if (ndays)
	pk->expiredate = pk->timestamp + ndays * 86400L;
    }

  pk->pubkey_algo = _pgp_pub_algo_to_cdk (cdk_stream_getc (inp));
  npkey = cdk_pk_get_npkey (pk->pubkey_algo);
  if (!npkey)
    {
      gnutls_assert ();
      _cdk_log_debug ("invalid public key algorithm %d\n", pk->pubkey_algo);
      return CDK_Inv_Algo;
    }
  for (i = 0; i < npkey; i++)
    {
      cdk_error_t rc = read_mpi (inp, &pk->mpi[i], 0);
      if (rc)
	return rc;
    }

  /* This value is just for the first run and will be
     replaced with the actual key flags from the self signature. */
  pk->pubkey_usage = 0;
  return 0;
}
bool VerilatorTbUtils::loadElf(char *fileName) {
  uint8_t *bin_data;
  int size;

  printf("Loading %s\n", fileName);
  bin_data = load_elf_file(fileName, &size);
  if (bin_data == NULL) {
    printf("Error loading elf file\n");
    return false;
  }

  for (int i = 0; i < size; i += 4)
    this->mem[i/4] = read_32(bin_data, i);

  free(bin_data);

  return true;
}
Example #13
0
static cdk_error_t
read_literal (cdk_stream_t inp, size_t pktlen,
	      cdk_pkt_literal_t * ret_pt, int is_partial)
{
  cdk_pkt_literal_t pt = *ret_pt;
  size_t nread;
  cdk_error_t rc;

  if (!inp || !pt)
    return CDK_Inv_Value;

  if (DEBUG_PKT)
    _cdk_log_debug ("read_literal: %d octets\n", pktlen);

  pt->mode = cdk_stream_getc (inp);
  if (pt->mode != 0x62 && pt->mode != 0x74 && pt->mode != 0x75)
    return CDK_Inv_Packet;
  if (cdk_stream_eof (inp))
    return CDK_Inv_Packet;

  pt->namelen = cdk_stream_getc (inp);
  if (pt->namelen > 0)
    {
      *ret_pt = pt = cdk_realloc (pt, sizeof *pt + pt->namelen + 2);
      if (!pt)
	return CDK_Out_Of_Core;
      pt->name = (char*)pt + sizeof(*pt);
      rc = stream_read (inp, pt->name, pt->namelen, &nread);
      if (rc)
	return rc;
      if ((int) nread != pt->namelen)
	return CDK_Inv_Packet;
      pt->name[pt->namelen] = '\0';
    }
  pt->timestamp = read_32 (inp);
  pktlen = pktlen - 6 - pt->namelen;
  if (is_partial)
    _cdk_stream_set_blockmode (inp, pktlen);
  pt->buf = inp;
  pt->len = pktlen;
  return 0;
}
Example #14
0
static gboolean
handle_dwarf2_section (DebuginfoData *data, GHashTable *files, GError **error)
{
  Elf_Data *e_data;
  int i;
  debug_section_t *debug_sections;

  ptr_size = 0;

  if (data->ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
    {
      do_read_16 = buf_read_ule16;
      do_read_32 = buf_read_ule32;
    }
  else if (data->ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
    {
      do_read_16 = buf_read_ube16;
      do_read_32 = buf_read_ube32;
    }
  else
    {
      return flatpak_fail (error, "%s: Wrong ELF data encoding", data->filename);
    }

  debug_sections = data->debug_sections;

  if (debug_sections[DEBUG_INFO].data != NULL)
    {
      unsigned char *ptr, *endcu, *endsec;
      uint32_t value;
      struct abbrev_tag *t;
      g_autofree REL *relbuf = NULL;

      if (debug_sections[DEBUG_INFO].relsec)
        {
          Elf_Scn *scn;
          int ndx, maxndx;
          GElf_Rel rel;
          GElf_Rela rela;
          GElf_Sym sym;
          GElf_Addr base = data->shdr[debug_sections[DEBUG_INFO].sec].sh_addr;
          Elf_Data *symdata = NULL;
          int rtype;

          i = debug_sections[DEBUG_INFO].relsec;
          scn = data->scns[i];
          e_data = elf_getdata (scn, NULL);
          g_assert (e_data != NULL && e_data->d_buf != NULL);
          g_assert (elf_getdata (scn, e_data) == NULL);
          g_assert (e_data->d_off == 0);
          g_assert (e_data->d_size == data->shdr[i].sh_size);
          maxndx = data->shdr[i].sh_size / data->shdr[i].sh_entsize;
          relbuf = g_malloc (maxndx * sizeof (REL));
          reltype = data->shdr[i].sh_type;

          symdata = elf_getdata (data->scns[data->shdr[i].sh_link], NULL);
          g_assert (symdata != NULL && symdata->d_buf != NULL);
          g_assert (elf_getdata (data->scns[data->shdr[i].sh_link], symdata) == NULL);
          g_assert (symdata->d_off == 0);
          g_assert (symdata->d_size == data->shdr[data->shdr[i].sh_link].sh_size);

          for (ndx = 0, relend = relbuf; ndx < maxndx; ++ndx)
            {
              if (data->shdr[i].sh_type == SHT_REL)
                {
                  gelf_getrel (e_data, ndx, &rel);
                  rela.r_offset = rel.r_offset;
                  rela.r_info = rel.r_info;
                  rela.r_addend = 0;
                }
              else
                {
                  gelf_getrela (e_data, ndx, &rela);
                }
              gelf_getsym (symdata, ELF64_R_SYM (rela.r_info), &sym);
              /* Relocations against section symbols are uninteresting
                 in REL.  */
              if (data->shdr[i].sh_type == SHT_REL && sym.st_value == 0)
                continue;
              /* Only consider relocations against .debug_str, .debug_line
                 and .debug_abbrev.  */
              if (sym.st_shndx != debug_sections[DEBUG_STR].sec &&
                  sym.st_shndx != debug_sections[DEBUG_LINE].sec &&
                  sym.st_shndx != debug_sections[DEBUG_ABBREV].sec)
                continue;
              rela.r_addend += sym.st_value;
              rtype = ELF64_R_TYPE (rela.r_info);
              switch (data->ehdr.e_machine)
                {
                case EM_SPARC:
                case EM_SPARC32PLUS:
                case EM_SPARCV9:
                  if (rtype != R_SPARC_32 && rtype != R_SPARC_UA32)
                    goto fail;
                  break;

                case EM_386:
                  if (rtype != R_386_32)
                    goto fail;
                  break;

                case EM_PPC:
                case EM_PPC64:
                  if (rtype != R_PPC_ADDR32 && rtype != R_PPC_UADDR32)
                    goto fail;
                  break;

                case EM_S390:
                  if (rtype != R_390_32)
                    goto fail;
                  break;

                case EM_IA_64:
                  if (rtype != R_IA64_SECREL32LSB)
                    goto fail;
                  break;

                case EM_X86_64:
                  if (rtype != R_X86_64_32)
                    goto fail;
                  break;

                case EM_ALPHA:
                  if (rtype != R_ALPHA_REFLONG)
                    goto fail;
                  break;

#if defined(EM_AARCH64) && defined(R_AARCH64_ABS32)
                case EM_AARCH64:
                  if (rtype != R_AARCH64_ABS32)
                    goto fail;
                  break;

#endif
                case EM_68K:
                  if (rtype != R_68K_32)
                    goto fail;
                  break;

                default:
fail:
                  return flatpak_fail (error, "%s: Unhandled relocation %d in .debug_info section",
                                       data->filename, rtype);
                }
              relend->ptr = debug_sections[DEBUG_INFO].data
                            + (rela.r_offset - base);
              relend->addend = rela.r_addend;
              ++relend;
            }
          if (relbuf == relend)
            {
              g_free (relbuf);
              relbuf = NULL;
              relend = NULL;
            }
          else
            {
              qsort (relbuf, relend - relbuf, sizeof (REL), rel_cmp);
            }
        }

      ptr = debug_sections[DEBUG_INFO].data;
      relptr = relbuf;
      endsec = ptr + debug_sections[DEBUG_INFO].size;
      while (ptr != NULL && ptr < endsec)
        {
          g_autoptr(GHashTable) abbrev = NULL;

          if (ptr + 11 > endsec)
            return flatpak_fail (error, "%s: .debug_info CU header too small", data->filename);

          endcu = ptr + 4;
          endcu += read_32 (ptr);
          if (endcu == ptr + 0xffffffff)
            return flatpak_fail (error, "%s: 64-bit DWARF not supported", data->filename);

          if (endcu > endsec)
            return flatpak_fail (error, "%s: .debug_info too small", data->filename);

          cu_version = read_16 (ptr);
          if (cu_version != 2 && cu_version != 3 && cu_version != 4)
            return flatpak_fail (error, "%s: DWARF version %d unhandled", data->filename, cu_version);

          value = read_32_relocated (ptr);
          if (value >= debug_sections[DEBUG_ABBREV].size)
            {
              if (debug_sections[DEBUG_ABBREV].data == NULL)
                return flatpak_fail (error, "%s: .debug_abbrev not present", data->filename);
              else
                return flatpak_fail (error, "%s: DWARF CU abbrev offset too large", data->filename);
            }

          if (ptr_size == 0)
            {
              ptr_size = read_1 (ptr);
              if (ptr_size != 4 && ptr_size != 8)
                return flatpak_fail (error, "%s: Invalid DWARF pointer size %d", data->filename, ptr_size);
            }
          else if (read_1 (ptr) != ptr_size)
            {
              return flatpak_fail (error, "%s: DWARF pointer size differs between CUs", data->filename);
            }

          abbrev = read_abbrev (data,
                                debug_sections[DEBUG_ABBREV].data + value);

          while (ptr < endcu)
            {
              guint entry = read_uleb128 (ptr);
              if (entry == 0)
                continue;
              t = g_hash_table_lookup (abbrev, GINT_TO_POINTER (entry));
              if (t == NULL)
                {
                  g_warning ("%s: Could not find DWARF abbreviation %d", data->filename, entry);
                }
              else
                {
                  ptr = handle_attributes (data, ptr, t, files, error);
                  if (ptr == NULL)
                    return FALSE;
                }
            }
        }
    }

  return TRUE;
}
Example #15
0
static unsigned char *
handle_attributes (DebuginfoData *data, unsigned char *ptr, struct abbrev_tag *t, GHashTable *files, GError **error)
{
  int i;
  uint32_t list_offs;
  int found_list_offs;
  g_autofree char *comp_dir = NULL;

  comp_dir = NULL;
  list_offs = 0;
  found_list_offs = 0;
  for (i = 0; i < t->nattr; ++i)
    {
      uint32_t form = t->attr[i].form;
      size_t len = 0;

      while (1)
        {
          if (t->attr[i].attr == DW_AT_stmt_list)
            {
              if (form == DW_FORM_data4 ||
                  form == DW_FORM_sec_offset)
                {
                  list_offs = do_read_32_relocated (ptr);
                  found_list_offs = 1;
                }
            }

          if (t->attr[i].attr == DW_AT_comp_dir)
            {
              if (form == DW_FORM_string)
                {
                  g_free (comp_dir);
                  comp_dir = g_strdup ((char *) ptr);
                }
              else if (form == DW_FORM_strp &&
                       data->debug_sections[DEBUG_STR].data)
                {
                  char *dir;

                  dir = (char *) data->debug_sections[DEBUG_STR].data
                        + do_read_32_relocated (ptr);

                  g_free (comp_dir);
                  comp_dir = g_strdup (dir);
                }
            }
          else if ((t->tag == DW_TAG_compile_unit ||
                    t->tag == DW_TAG_partial_unit) &&
                   t->attr[i].attr == DW_AT_name &&
                   form == DW_FORM_strp &&
                   data->debug_sections[DEBUG_STR].data)
            {
              char *name;

              name = (char *) data->debug_sections[DEBUG_STR].data
                     + do_read_32_relocated (ptr);
              if (*name == '/' && comp_dir == NULL)
                {
                  char *enddir = strrchr (name, '/');

                  if (enddir != name)
                    {
                      comp_dir = g_malloc (enddir - name + 1);
                      memcpy (comp_dir, name, enddir - name);
                      comp_dir[enddir - name] = '\0';
                    }
                  else
                    {
                      comp_dir = g_strdup ("/");
                    }
                }

            }

          switch (form)
            {
            case DW_FORM_ref_addr:
              if (cu_version == 2)
                ptr += ptr_size;
              else
                ptr += 4;
              break;

            case DW_FORM_flag_present:
              break;

            case DW_FORM_addr:
              ptr += ptr_size;
              break;

            case DW_FORM_ref1:
            case DW_FORM_flag:
            case DW_FORM_data1:
              ++ptr;
              break;

            case DW_FORM_ref2:
            case DW_FORM_data2:
              ptr += 2;
              break;

            case DW_FORM_ref4:
            case DW_FORM_data4:
            case DW_FORM_sec_offset:
              ptr += 4;
              break;

            case DW_FORM_ref8:
            case DW_FORM_data8:
            case DW_FORM_ref_sig8:
              ptr += 8;
              break;

            case DW_FORM_sdata:
            case DW_FORM_ref_udata:
            case DW_FORM_udata:
              (void) read_uleb128 (ptr);
              break;

            case DW_FORM_strp:
              ptr += 4;
              break;

            case DW_FORM_string:
              ptr = (unsigned char *) strchr ((char *) ptr, '\0') + 1;
              break;

            case DW_FORM_indirect:
              form = read_uleb128 (ptr);
              continue;

            case DW_FORM_block1:
              len = *ptr++;
              break;

            case DW_FORM_block2:
              len = read_16 (ptr);
              form = DW_FORM_block1;
              break;

            case DW_FORM_block4:
              len = read_32 (ptr);
              form = DW_FORM_block1;
              break;

            case DW_FORM_block:
            case DW_FORM_exprloc:
              len = read_uleb128 (ptr);
              form = DW_FORM_block1;
              g_assert (len < UINT_MAX);
              break;

            default:
              g_warning ("%s: Unknown DWARF DW_FORM_%d", data->filename, form);
              return NULL;
            }

          if (form == DW_FORM_block1)
            ptr += len;

          break;
        }
    }

  /* Ensure the CU current directory will exist even if only empty.  Source
     filenames possibly located in its parent directories refer relatively to
     it and the debugger (GDB) cannot safely optimize out the missing
     CU current dir subdirectories.  */
  if (comp_dir)
    g_hash_table_insert (files, g_strdup (comp_dir), NULL);

  if (found_list_offs &&
      !handle_dwarf2_line (data, list_offs, comp_dir, files, error))
    return NULL;

  return ptr;
}
Example #16
0
static gboolean
handle_dwarf2_line (DebuginfoData *data, uint32_t off, char *comp_dir, GHashTable *files, GError **error)
{
  unsigned char *ptr = data->debug_sections[DEBUG_LINE].data, *dir;
  unsigned char **dirt;
  unsigned char *endsec = ptr + data->debug_sections[DEBUG_LINE].size;
  unsigned char *endcu, *endprol;
  unsigned char opcode_base;
  uint32_t value, dirt_cnt;
  size_t comp_dir_len = !comp_dir ? 0 : strlen (comp_dir);


  /* XXX: RhBug:929365, should we error out instead of ignoring? */
  if (ptr == NULL)
    return TRUE;

  ptr += off;

  endcu = ptr + 4;
  endcu += read_32 (ptr);
  if (endcu == ptr + 0xffffffff)
    return flatpak_fail (error, "%s: 64-bit DWARF not supported", data->filename);

  if (endcu > endsec)
    return flatpak_fail (error, "%s: .debug_line CU does not fit into section", data->filename);

  value = read_16 (ptr);
  if (value != 2 && value != 3 && value != 4)
    return flatpak_fail (error, "%s: DWARF version %d unhandled", data->filename, value);

  endprol = ptr + 4;
  endprol += read_32 (ptr);
  if (endprol > endcu)
    return flatpak_fail (error, "%s: .debug_line CU prologue does not fit into CU", data->filename);

  opcode_base = ptr[4 + (value >= 4)];
  ptr = dir = ptr + 4 + (value >= 4) + opcode_base;

  /* dir table: */
  value = 1;
  while (*ptr != 0)
    {
      ptr = (unsigned char *) strchr ((char *) ptr, 0) + 1;
      ++value;
    }

  dirt = (unsigned char **) alloca (value * sizeof (unsigned char *));
  dirt[0] = (unsigned char *) ".";
  dirt_cnt = 1;
  ptr = dir;
  while (*ptr != 0)
    {
      dirt[dirt_cnt++] = ptr;
      ptr = (unsigned char *) strchr ((char *) ptr, 0) + 1;
    }
  ptr++;

  /* file table: */
  while (*ptr != 0)
    {
      char *s, *file;
      size_t file_len, dir_len;

      file = (char *) ptr;
      ptr = (unsigned char *) strchr ((char *) ptr, 0) + 1;
      value = read_uleb128 (ptr);

      if (value >= dirt_cnt)
        return flatpak_fail (error, "%s: Wrong directory table index %u",  data->filename, value);

      file_len = strlen (file);
      dir_len = strlen ((char *) dirt[value]);
      s = g_malloc (comp_dir_len + 1 + file_len + 1 + dir_len + 1);
      if (*file == '/')
        {
          memcpy (s, file, file_len + 1);
        }
      else if (*dirt[value] == '/')
        {
          memcpy (s, dirt[value], dir_len);
          s[dir_len] = '/';
          memcpy (s + dir_len + 1, file, file_len + 1);
        }
      else
        {
          char *p = s;
          if (comp_dir_len != 0)
            {
              memcpy (s, comp_dir, comp_dir_len);
              s[comp_dir_len] = '/';
              p += comp_dir_len + 1;
            }
          memcpy (p, dirt[value], dir_len);
          p[dir_len] = '/';
          memcpy (p + dir_len + 1, file, file_len + 1);
        }
      canonicalize_path (s, s);

      if (s)
        g_hash_table_insert (files, s, NULL);

      (void) read_uleb128 (ptr);
      (void) read_uleb128 (ptr);
    }
  ++ptr;

  return TRUE;
}
Example #17
0
int bg_f_signature_read(bg_f_io_t * io, bg_f_chunk_t * ch, bg_f_signature_t * sig)
  {
  if(!read_32(io, &sig->type))
    return 0;
  return 1;
  }
extern int output_mp4(struct mp4_context_t* mp4_context,
                      unsigned int const* trak_sample_start,
                      unsigned int const* trak_sample_end,
                      struct bucket_t** buckets,
                      struct mp4_split_options_t* options)
{
  unsigned int i;

  uint64_t mdat_start = mp4_context->mdat_atom.start_;
  uint64_t mdat_size = mp4_context->mdat_atom.size_;
  int64_t offset;

  struct moov_t* moov = mp4_context->moov;
//  unsigned char* moov_data = mp4_context->moov_data;
  unsigned char* moov_data = (unsigned char*)
    malloc((size_t)mp4_context->moov_atom.size_ + ATOM_PREAMBLE_SIZE + 1024);

  uint64_t moov_size;

  long moov_time_scale = moov->mvhd_->timescale_;
  uint64_t skip_from_start = UINT64_MAX;
  uint64_t end_offset = 0;

  uint64_t moov_duration = 0;

#if 1
  uint64_t new_mdat_start = 0;
  {
    static char const free_data[] = {
      0x0, 0x0, 0x0,  42, 'f', 'r', 'e', 'e',
      'v', 'i', 'd', 'e', 'o', ' ', 's', 'e',
      'r', 'v', 'e', 'd', ' ', 'b', 'y', ' ',
      'm', 'o', 'd', '_', 'h', '2', '6', '4',
      '_', 's', 't', 'r', 'e', 'a', 'm', 'i',
      'n', 'g'
    };
    uint32_t size_of_header = (uint32_t)mp4_context->ftyp_atom.size_ +
                              sizeof(free_data);
    unsigned char* buffer = (unsigned char*)malloc(size_of_header);

    if(mp4_context->ftyp_atom.size_)
    {
      fseeko(mp4_context->infile, mp4_context->ftyp_atom.start_, SEEK_SET);
      if(fread(buffer, (off_t)mp4_context->ftyp_atom.size_, 1, mp4_context->infile) != 1)
      {
        MP4_ERROR("%s", "Error reading ftyp atom\n");
        free(buffer);
        return 0;
      }
    }

    // copy free data
    memcpy(buffer + mp4_context->ftyp_atom.size_, free_data,
           sizeof(free_data));

    if(options->output_format == OUTPUT_FORMAT_MP4)
    {
      bucket_t* bucket = bucket_init_memory(buffer, size_of_header);
      bucket_insert_tail(buckets, bucket);
    }
    free(buffer);

    new_mdat_start += size_of_header;
  }

//  new_mdat_start += mp4_context->moov_atom.size_;
#endif

  offset = new_mdat_start - mp4_context->mdat_atom.start_;
  // subtract old moov size
//  offset -= mp4_context->moov_atom.size_;

  for(i = 0; i != moov->tracks_; ++i)
  {
    struct trak_t* trak = moov->traks_[i];
    struct stbl_t* stbl = trak->mdia_->minf_->stbl_;

    unsigned int start_sample = trak_sample_start[i];
    unsigned int end_sample = trak_sample_end[i];


    if (options->exact)
      trak_fast_forward_first_partial_GOP(mp4_context, options, trak, start_sample);

    trak_update_index(mp4_context, trak, start_sample, end_sample);

    if(trak->samples_size_ == 0)
    {
      MP4_WARNING("Trak %u contains no samples. Maybe a fragmented file?", i);
      return 1;
    }

    {
      uint64_t skip =
        trak->samples_[start_sample].pos_ - trak->samples_[0].pos_;
      if(skip < skip_from_start)
        skip_from_start = skip;
      MP4_INFO("Trak can skip %"PRIu64" bytes\n", skip);

      if(end_sample != trak->samples_size_)
      {
        uint64_t end_pos = trak->samples_[end_sample].pos_;
        if(end_pos > end_offset)
          end_offset = end_pos;
        MP4_INFO("New endpos=%"PRIu64"\n", end_pos);
        MP4_INFO("Trak can skip %"PRIu64" bytes at end\n",
               mdat_start + mdat_size - end_offset);
      }
    }

    {
      // fixup trak (duration)
      uint64_t trak_duration = stts_get_duration(stbl->stts_);
      long trak_time_scale = trak->mdia_->mdhd_->timescale_;
      {
        uint64_t duration = trak_time_to_moov_time(trak_duration,
          moov_time_scale, trak_time_scale);
        trak->mdia_->mdhd_->duration_= trak_duration;
        trak->tkhd_->duration_ = duration;
        MP4_INFO("trak: new_duration=%"PRIu64"\n", duration);

        if(duration > moov_duration)
          moov_duration = duration;
      }
    }

//      MP4_INFO("stco.size=%d, ", read_int32(stbl->stco_ + 4));
//      MP4_INFO("stts.size=%d samples=%d\n", read_int32(stbl->stts_ + 4), stts_get_samples(stbl->stts_));
//      MP4_INFO("stsz.size=%d\n", read_int32(stbl->stsz_ + 8));
//      MP4_INFO("stsc.samples=%d\n", stsc_get_samples(stbl->stsc_));
  }
  moov->mvhd_->duration_ = moov_duration;
  MP4_INFO("moov: new_duration=%.2f seconds\n", moov_duration / (float)moov_time_scale);

  // subtract bytes we skip at the front of the mdat atom
  offset -= skip_from_start;

  MP4_INFO("%s", "moov: writing header\n");

  moov_write(moov, moov_data);
  moov_size = read_32(moov_data);

  // add new moov size
  offset += moov_size;

  MP4_INFO("shifting offsets by %"PRId64"\n", offset);
  moov_shift_offsets_inplace(moov, offset);

  // traffic shaping: create offsets for each second
  create_traffic_shaping(moov,
                         trak_sample_start,
                         trak_sample_end,
                         offset,
                         options);

#ifdef COMPRESS_MOOV_ATOM
  if(!options->client_is_flash)
  {
    compress_moov(mp4_context, moov, moov_data, &moov_size);
  }
#endif

  if(end_offset != 0)
  {
    MP4_INFO("mdat_size=%"PRId64" end_offset=%"PRId64"\n",
             mdat_size, end_offset);
    mdat_size = end_offset - mdat_start;
  }
  mdat_start += skip_from_start;
  mdat_size -= skip_from_start;

  MP4_INFO("mdat_bucket(%"PRId64", %"PRId64")\n", mdat_start, mdat_size);

  bucket_insert_tail(buckets, bucket_init_memory(moov_data, moov_size));
  free(moov_data);

  {
    struct mp4_atom_t mdat_atom;
    mdat_atom.type_ = FOURCC('m', 'd', 'a', 't');
    mdat_atom.short_size_ = 0; // TODO: use original small/wide mdat box

    if(options->adaptive)
    {
      // empty mdat atom
      mdat_atom.size_ = ATOM_PREAMBLE_SIZE;
    }
    else
    {
      mdat_atom.size_ = mdat_size;
    }

    {
      unsigned char buffer[32];
      int mdat_header_size = mp4_atom_write_header(buffer, &mdat_atom);
      bucket_insert_tail(buckets,
        bucket_init_memory(buffer, mdat_header_size));

      if(mdat_atom.size_ - mdat_header_size)
      {
        bucket_insert_tail(buckets,
          bucket_init_file(mdat_start + mdat_header_size,
                           mdat_atom.size_ - mdat_header_size));
      }
    }
  }

  return 1;
}
Example #19
0
static cdk_error_t
read_signature (cdk_stream_t inp, size_t pktlen, cdk_pkt_signature_t sig)
{
  size_t nbytes;
  size_t i, size, nsig;
  cdk_error_t rc;

  if (!inp || !sig)
    return CDK_Inv_Value;

  if (DEBUG_PKT)
    _cdk_log_debug ("read_signature: %d octets\n", pktlen);

  if (pktlen < 16)
    return CDK_Inv_Packet;
  sig->version = cdk_stream_getc (inp);
  if (sig->version < 2 || sig->version > 4)
    return CDK_Inv_Packet_Ver;

  sig->flags.exportable = 1;
  sig->flags.revocable = 1;

  if (sig->version < 4)
    {
      if (cdk_stream_getc (inp) != 5)
	return CDK_Inv_Packet;
      sig->sig_class = cdk_stream_getc (inp);
      sig->timestamp = read_32 (inp);
      sig->keyid[0] = read_32 (inp);
      sig->keyid[1] = read_32 (inp);
      sig->pubkey_algo = _pgp_pub_algo_to_cdk (cdk_stream_getc (inp));
      sig->digest_algo = _pgp_hash_algo_to_gnutls (cdk_stream_getc (inp));
      sig->digest_start[0] = cdk_stream_getc (inp);
      sig->digest_start[1] = cdk_stream_getc (inp);
      nsig = cdk_pk_get_nsig (sig->pubkey_algo);
      if (!nsig)
	return CDK_Inv_Algo;
      for (i = 0; i < nsig; i++)
	{
	  rc = read_mpi (inp, &sig->mpi[i], 0);
	  if (rc)
	    return rc;
	}
    }
  else
    {
      sig->sig_class = cdk_stream_getc (inp);
      sig->pubkey_algo = _pgp_pub_algo_to_cdk (cdk_stream_getc (inp));
      sig->digest_algo = _pgp_hash_algo_to_gnutls (cdk_stream_getc (inp));
      sig->hashed_size = read_16 (inp);
      size = sig->hashed_size;
      sig->hashed = NULL;
      while (size > 0)
	{
	  rc = read_subpkt (inp, &sig->hashed, &nbytes);
	  if (rc)
	    return rc;
	  size -= nbytes;
	}
      sig->unhashed_size = read_16 (inp);
      size = sig->unhashed_size;
      sig->unhashed = NULL;
      while (size > 0)
	{
	  rc = read_subpkt (inp, &sig->unhashed, &nbytes);
	  if (rc)
	    return rc;
	  size -= nbytes;
	}

      rc = parse_sig_subpackets (sig);
      if (rc)
	return rc;

      sig->digest_start[0] = cdk_stream_getc (inp);
      sig->digest_start[1] = cdk_stream_getc (inp);
      nsig = cdk_pk_get_nsig (sig->pubkey_algo);
      if (!nsig)
	return CDK_Inv_Algo;
      for (i = 0; i < nsig; i++)
	{
	  rc = read_mpi (inp, &sig->mpi[i], 0);
	  if (rc)
	    return rc;
	}
    }

  return 0;
}
Example #20
0
Buffer::ConstPointer
Buffer::read(uint32_t &out_value) const throw(KafkaError) {
    out_value = *reinterpret_cast<const uint32_t *>(read_32());
    return shared_from_this();
}
Example #21
0
File: erq.c Project: amotzkau/ldmud
/*-------------------------------------------------------------------------*/
int
main(int argc, char *argv[])

/* The main program and -loop of the ERQ.
 */

{
    int num;

    master_pid = getpid();

    /* Print information about this daemon to help debugging */
    {
        fprintf(stderr, "%s XERQ %s: Path '%s', debuglevel %d\n"
                      , time_stamp(), __DATE__, argv[0], ERQ_DEBUG
                );
    }

    /* Quick and dirty commandline parser */
    {
        int is_forked = 0;
        int i;

        for (i = 1; i < argc; i++)
        {
            if (!strcmp(argv[i], "--forked"))
                is_forked = 1;
            else if (!strcmp(argv[i], "--execdir"))
            {
                if (i+1 >= argc)
                {
                    fprintf(stderr, "%s Missing value for --execdir.\n"
                                  , time_stamp());
                    die();
                }
                erq_dir = argv[i+1];
                i++;
            }
            else
            {
                fprintf(stderr, "%s Unknown argument '%s'.\n"
                              , time_stamp(), argv[i]);
                die();
            }
        }
        /* Check if we have been forked off the driver */
        if (is_forked)
        {
            write(1, "1", 1); /* indicate sucessful fork/execl */
            fprintf(stderr, "%s Demon started\n", time_stamp() );
        }
        else
        {
            fprintf(stderr, "%s Dynamic attachment unimplemented\n"
                          , time_stamp());
            die();
        }
    }

    /* Initialize */
    
    in_select = 0;
    pending_sig = 0;

    signal(SIGCLD, sig_child);
    signal(SIGPIPE, SIG_IGN);

    sockets = NULL;
    childs = NULL;
    retries = NULL;
    stdout_queue = NULL;
    
    randomize(time(0));
    seq_number = get_ticket();
    seq_interval = get_ticket() | 1; /* make sure it is odd */

#ifdef DETACH
    /* Detach from console */
    num = open("/dev/tty", O_RDWR);
    if (num >= 0) {
        ioctl(num, TIOCNOTTY, 0);
        close(num);
    }
#endif

    /* The main loop */
    
    while(1)
    {
        fd_set read_fds, write_fds;
        int num_fds;
        child_t *chp;
        retry_t *rtp, **rtpp;
        socket_t *sp;
        struct timeval timeout;

        /* Clean up the list of children (may close some sockets) */
        
        for (chp = childs; chp;)
        {
            child_t *this = chp;

            chp = chp->next;

            /* If there is a pending SIG_CLD for this child, handle it.
             * This is to be expected for CHILD_FORK children.
             */
            if (pending_sig && this->pid == pending_pid)
            {
                if (this->type != CHILD_FORK)
                    fprintf(stderr, "%s Pending SIG_CLD for pid %d delivered.\n"
                                  , time_stamp(), pending_pid);
                this->status = pending_status;
                this->pid = pending_pid;
                pending_sig = 0;
            }

            if (this->status == CHILD_EXITED)
            {
                XPRINTF((stderr, "%s Child %p exited.\n", time_stamp(), this));
                remove_child(this); /* will also unlink it from the list */
            }
        }

        /* look for sockets to select on */

        FD_ZERO(&read_fds);
        FD_ZERO(&write_fds);

        FD_SET(0, &read_fds);
        if (stdout_queue)
            FD_SET(1, &write_fds);

        num_fds = 2;
        for (sp = sockets; sp; sp = sp->next)
        {
            switch(sp->type)
            {
            case SOCKET_WAIT_CONNECT:
            case SOCKET_WAIT_AUTH:
                FD_SET(sp->fd, &write_fds);
                FD_SET(sp->fd, &read_fds);
                if (sp->fd >= num_fds)
                    num_fds=sp->fd+1;
                break;

            default:
                FD_SET(sp->fd, &read_fds);
                if (sp->fd >= num_fds)
                    num_fds=sp->fd+1;
                break;

            case SOCKET_WAIT_ACCEPT:
                /* do nothing */;
                /* Without the ; above, Metrowerks Codewarrior reports
                 * an error :-( */
            }

            if (sp->queue)
                FD_SET(sp->fd, &write_fds);
        } /* for (sockets) */

        /* Scan the list of pending retries for the soonest one.
         * Put the time till then into timeout.
         * (If the list is empty, select() will receive NULL for timeout).
         */
        if (retries)
        {
            time_t t;

            t = retries->time;
            for (rtp = retries; rtp; rtp = rtp->next)
            {
                if (rtp->time < t)
                    t = rtp->time;
            }
            timeout.tv_sec = t - time(NULL);
            timeout.tv_usec = 0;
            XPRINTF((stderr, "%s Soonest retry_t: in %ld seconds.\n"
                           , time_stamp(), (long)timeout.tv_sec));
			   
            if (timeout.tv_sec < 0)
                timeout.tv_sec = 0;
        }

#if ERQ_DEBUG > 1
        fprintf(stderr, "%s select()\n", time_stamp());
#endif
        in_select = 1; /* so sig_child() can write reply directly */
        num = select(num_fds, &read_fds, &write_fds, 0, retries ? &timeout : 0);
        in_select = 0; /* don't want sig_child() writing now */

#if ERQ_DEBUG > 1
        {
            int myerrno = errno;
            fprintf(stderr, "%s select() returns %d, time() %ld\n"
                          , time_stamp(), num, (long)time(NULL));
            errno = myerrno;
        }
#endif

#if ERQ_DEBUG > 0
        if (num < 0)
	/* Give an error now, but don't abort this loop,
	 * because the retries have to be handled first.
	 */
        {
            int myerrno = errno;
            fprintf(stderr, "%s select() errno = %d", time_stamp(), errno);
            errno = myerrno;
            perror(" ");
        }
#endif
	
        /* Is stdout ready to write? Then flush the queue. */
        if (num >= 0 && FD_ISSET(1, &write_fds))
        {
            XPRINTF((stderr, "%s stdout_queue ready for flush.\n", time_stamp()));
            flush_queue(&stdout_queue, 1, 0);
        }

        /* Check for retries */
        for (rtpp = &retries; *rtpp; )
        {
            rtp = *rtpp;
            if (rtp->time <= time(NULL))
            {
                XPRINTF((stderr, "%s Call retry %p (time %ld)\n"
                               , time_stamp(), rtp, (long)rtp->time));
                (*(rtp->func))(rtp->mesg, read_32(rtp->mesg));
                *rtpp = rtp->next;
                free(rtp);
            }
            else
            {
                rtpp = &rtp->next;
            }
        }
	
        /* Error in select */
        if (num < 0)
            continue;

        /* check for input from driver */
        if (FD_ISSET(0, &read_fds))
        {
            XPRINTF((stderr, "%s New command from driver.\n", time_stamp()));
            erq_cmd();
        }

        /* Handle the ready sockets.
         * Remember that read_socket() may close the socket.
         */

        for (sp = sockets; sp; )
        {
            socket_t *this = sp;
            int rc;

            sp = sp->next;

            rc = 0;

            if (FD_ISSET(this->fd, &read_fds))
            {
                XPRINTF((stderr, "%s Socket %p (%d) ready for reading.\n"
                               , time_stamp(), this, this->fd));
                rc = read_socket(this, 0);
            }

            if (!rc && FD_ISSET(this->fd, &write_fds))
            {
                XPRINTF((stderr, "%s Socket %p (%d) ready for writing.\n"
                               , time_stamp(), this, this->fd));
                (void)read_socket(this, 1);
            }
        }
    } /* while(1) */

    /* NOTREACHED */
    
    return 0;
} /* main() */
Example #22
0
static inline COUNT
read_ptr (void *fp)
{
	DWORD t;
	return read_32 (fp, &t); /* ptrs are useless in saves */
}
Example #23
0
File: erq.c Project: amotzkau/ldmud
/*-------------------------------------------------------------------------*/
void
erq_cmd (void)

/* There is data ready from the driver - read and execute it when complete.
 * The function maintains a static buffer for the data read - incomplete
 * messages are buffered until they are complete.
 */

{
    static char buf[ERQ_MAX_SEND];
    static int pos = 0;
      /* Position in buf[]. If it extends beyond the end of buf,
       * it is because the message is too long and the function
       * is in the process of skipping the extraneous characters.
       */

    int len, mesg_len;
    char request;

    /* Clear the buffer so that errors can be detected more easily */
    memset(buf, 0, sizeof(buf));

    /* Read the message header */
    if (pos < 9)
    {
        len = read(0, buf+pos, 9-pos);
        if (len <= 0)
        {
            perror("[xerq] read");
            die();
        }
        XPRINTF((stderr, "%s Read %d of the missing %d header bytes.\n"
                       , time_stamp(), len, 9-pos));
        pos += len;
        if (pos < 9)
            return;
    }

    mesg_len = read_32(buf);
    if (mesg_len > sizeof(buf))
    {
        /* This doesn't happen in a functioning system */
        fprintf(stderr
               , "%s Received too long packet: %d bytes.\n"
               , time_stamp(), mesg_len);
        die();
    }

    /* Get the rest of the message */

    if (pos < mesg_len)
    {
        len = read(0, buf+pos, mesg_len-pos);
        if (len <= 0)
        {
            perror("read");
            die();
        }
        XPRINTF((stderr, "%s Read %d of the missing %d message bytes.\n"
                       , time_stamp(), len, mesg_len-pos));
        pos += len;
        if (pos < mesg_len)
            return;
    }

    XPRINTF((stderr, "%s Message complete.\n", time_stamp()));
    pos = 0; /* Message complete */

    /* Branch on the request */
    request = buf[8];
    if (request <= ERQ_REQUEST_MAX)
    {
#if ERQ_DEBUG > 0
        char *mesg, *mesgs[]={
            "rlookup","execute","fork","auth","spawn","send","kill",
            "open_udp","open_tcp","listen","accept","lookup", "rlookupv6"};
        mesg=mesgs[(int)request];
        fprintf(stderr, "%s command: %s\n", time_stamp(), mesg);
#endif
        (*erq_table[(int)request])(buf, mesg_len);
    }
    else
        bad_request(buf);
} /* erq_cmd() */