Example #1
0
static _Bool cut_file(char const   *file ) 
{ FILE *stream ;
  int *tmp ;
  int tmp___0 ;
  int *tmp___1 ;
  int tmp___2 ;
  int *tmp___3 ;
  int tmp___4 ;
  int tmp___5 ;

  {
  tmp___0 = strcmp(file, "-");
  if (tmp___0 == 0) {
    have_read_stdin = (_Bool)1;
    stream = stdin;
  } else {
    stream = fopen((char const   */* __restrict  */)file, (char const   */* __restrict  */)"r");
    if ((unsigned long )stream == (unsigned long )((void *)0)) {
      tmp = __errno_location();
      error(0, *tmp, "%s", file);
      return ((_Bool)0);
    } else {

    }
  }
  fadvise(stream, (enum __anonenum_fadvice_t_62 )2);
  cut_stream(stream);
  tmp___2 = ferror_unlocked(stream);
  if (tmp___2) {
    tmp___1 = __errno_location();
    error(0, *tmp___1, "%s", file);
    return ((_Bool)0);
  } else {

  }
  tmp___5 = strcmp(file, "-");
  if (tmp___5 == 0) {
    clearerr_unlocked(stream);
  } else {
    tmp___4 = fclose(stream);
    if (tmp___4 == -1) {
      tmp___3 = __errno_location();
      error(0, *tmp___3, "%s", file);
      return ((_Bool)0);
    } else {

    }
  }
  return ((_Bool)1);
}
}
Example #2
0
bool read_whole_file(FILE *fp, std::string *ret, size_t estimated_size) {
	if (estimated_size < 128) {
		estimated_size = 128;
	}

	ret->clear();
	std::unique_ptr<char[]> buf{new char[estimated_size]};

	size_t l;
	while ((l = fread_unlocked(buf.get(), 1, estimated_size, fp)) != 0) {
		ret->append(buf.get(), l);
	}
	if (ferror_unlocked(fp)) {
		return false;
	}
	return true;
}
Example #3
0
static int
token()
{
	char *cp;
	int c;
	int i;

	if (feof_unlocked(cfile) || ferror_unlocked(cfile))
		return (0);
	while ((c = getc_unlocked(cfile)) != EOF &&
	    (c == '\n' || c == '\t' || c == ' ' || c == ','))
		continue;
	if (c == EOF)
		return (0);
	cp = tokval;
	if (c == '"') {
		while ((c = getc_unlocked(cfile)) != EOF && c != '"') {
			if (c == '\\')
				c = getc_unlocked(cfile);
			*cp++ = c;
		}
	} else {
		*cp++ = c;
		while ((c = getc_unlocked(cfile)) != EOF
		    && c != '\n' && c != '\t' && c != ' ' && c != ',') {
			if (c == '\\')
				c = getc_unlocked(cfile);
			*cp++ = c;
		}
	}
	*cp = 0;
	if (tokval[0] == 0)
		return (0);
	for (i = 0; i < (int) (sizeof (toktab) / sizeof (toktab[0])); ++i)
		if (!strcmp(&tokstr[toktab[i].tokstr_off], tokval))
			return toktab[i].tval;
	return (ID);
}
Example #4
0
static int
proc_maps_report (Dwfl *dwfl, FILE *f, GElf_Addr sysinfo_ehdr, pid_t pid)
{
  unsigned int last_dmajor = -1, last_dminor = -1;
  uint64_t last_ino = -1;
  char *last_file = NULL;
  Dwarf_Addr low = 0, high = 0;

  inline bool report (void)
    {
      if (last_file != NULL)
	{
	  Dwfl_Module *mod = INTUSE(dwfl_report_module) (dwfl, last_file,
							 low, high);
	  free (last_file);
	  last_file = NULL;
	  if (unlikely (mod == NULL))
	    return true;
	}
      return false;
    }

  char *line = NULL;
  size_t linesz;
  ssize_t len;
  while ((len = getline (&line, &linesz, f)) > 0)
    {
      if (line[len - 1] == '\n')
	line[len - 1] = '\0';

      Dwarf_Addr start, end, offset;
      unsigned int dmajor, dminor;
      uint64_t ino;
      int nread = -1;
      if (sscanf (line, "%" PRIx64 "-%" PRIx64 " %*s %" PRIx64
		  " %x:%x %" PRIi64 " %n",
		  &start, &end, &offset, &dmajor, &dminor, &ino, &nread) < 6
	  || nread <= 0)
	{
	  free (line);
	  return ENOEXEC;
	}

      /* If this is the special mapping AT_SYSINFO_EHDR pointed us at,
	 report the last one and then this special one.  */
      if (start == sysinfo_ehdr && start != 0)
	{
	  if (report ())
	    {
	    bad_report:
	      free (line);
	      return -1;
	    }

	  low = start;
	  high = end;
	  if (asprintf (&last_file, "[vdso: %d]", (int) pid) < 0
	      || report ())
	    goto bad_report;
	}

      char *file = line + nread + strspn (line + nread, " \t");
      if (file[0] != '/' || (ino == 0 && dmajor == 0 && dminor == 0))
	/* This line doesn't indicate a file mapping.  */
	continue;

      if (last_file != NULL
	  && ino == last_ino && dmajor == last_dmajor && dminor == last_dminor)
	{
	  /* This is another portion of the same file's mapping.  */
	  if (strcmp (last_file, file) != 0)
	    goto bad_report;
	  high = end;
	}
      else
	{
	  /* This is a different file mapping.  Report the last one.  */
	  if (report ())
	    goto bad_report;
	  low = start;
	  high = end;
	  last_file = strdup (file);
	  last_ino = ino;
	  last_dmajor = dmajor;
	  last_dminor = dminor;
	}
    }
  free (line);

  int result = ferror_unlocked (f) ? errno : feof_unlocked (f) ? 0 : ENOEXEC;

  /* Report the final one.  */
  bool lose = report ();

  return result != 0 ? result : lose ? -1 : 0;
}
Example #5
0
static int comment_43_compress(FILE *infp, FILE *outfp, size_t block_size)
{
  const size_t max_raw_data_len = 32 * 1024; /* maximum data length */
  const size_t max_compressed_data_len = snappy_max_compressed_length(max_raw_data_len); /* maximum compressed length */
  size_t raw_data_len;
  size_t compressed_data_len;
  char *raw_data = malloc(max_raw_data_len);
  char *compressed_data = malloc(max_compressed_data_len);
  int err = 1;

  if (raw_data == NULL || compressed_data == NULL) {
    print_error("out of memory\n");
    goto cleanup;
  }

  putc_unlocked(HEADER_TYPE_CODE, outfp);
  putc_unlocked(MAGIC_LEN, outfp);
  putc_unlocked(MAGIC_LEN >> 8, outfp);
  fwrite_unlocked(MAGIC, MAGIC_LEN, 1, outfp);

  /* write file body */
  while ((raw_data_len = fread_unlocked(raw_data, 1, max_raw_data_len, infp)) > 0) {
    unsigned int crc32c = masked_crc32c(raw_data, raw_data_len);
    char type_code;
    size_t write_len;
    const char *write_data;

    /* compress the block. */
    compressed_data_len = max_compressed_data_len;
    snappy_compress(raw_data, raw_data_len, compressed_data, &compressed_data_len);

    if (compressed_data_len >= (raw_data_len - (raw_data_len / 8))) {
      /* write uncompressed data */
      type_code = UNCOMPRESSED_TYPE_CODE;
      write_len = raw_data_len;
      write_data = raw_data;
    } else {
      /* write compressed data */
      type_code = COMPRESSED_TYPE_CODE;
      write_len = compressed_data_len;
      write_data = compressed_data;
    }

    /* block type */
    putc_unlocked(type_code, outfp);
    /* data length */
    putc_unlocked(((write_len + 4) >> 0), outfp);
    putc_unlocked(((write_len + 4) >> 8), outfp);
    /* data */
    putc_unlocked((crc32c >>  0), outfp);
    putc_unlocked((crc32c >>  8), outfp);
    putc_unlocked((crc32c >> 16), outfp);
    putc_unlocked((crc32c >> 24), outfp);
    if (fwrite_unlocked(write_data, write_len, 1, outfp) != 1) {
      print_error("Failed to write a file: %s\n", strerror(errno));
      goto cleanup;
    }
  }
  if (!feof_unlocked(infp)) {
    /* fread_unlocked() failed. */
    print_error("Failed to read a file: %s\n", strerror(errno));
    goto cleanup;
  }
  putc_unlocked(END_OF_STREAM_TYPE_CODE, outfp);
  putc_unlocked(0, outfp);
  putc_unlocked(0, outfp);
  if (ferror_unlocked(outfp)) {
    print_error("Failed to write a file: %s\n", strerror(errno));
    goto cleanup;
  }
  err = 0;
 cleanup:
  free(raw_data);
  free(compressed_data);
  return err;
}
Example #6
0
static int framing_format_compress(FILE *infp, FILE *outfp, size_t block_size)
{
  const size_t max_uncompressed_data_len = MAX_UNCOMPRESSED_DATA_LEN;
  const size_t max_compressed_data_len = snappy_max_compressed_length(max_uncompressed_data_len);
  size_t uncompressed_data_len;
  size_t compressed_data_len;
  char *uncompressed_data = malloc(max_uncompressed_data_len);
  char *compressed_data = malloc(max_compressed_data_len);
  int err = 1;

  if (uncompressed_data == NULL || compressed_data == NULL) {
    print_error("out of memory\n");
    goto cleanup;
  }

  /* write the steam header */
  fwrite_unlocked(stream_header, sizeof(stream_header), 1, outfp);

  /* write file body */
  while ((uncompressed_data_len = fread_unlocked(uncompressed_data, 1, max_uncompressed_data_len, infp)) > 0) {
    unsigned int crc32c = masked_crc32c(uncompressed_data, uncompressed_data_len);
    char type_code;
    size_t write_len;
    const char *write_data;

    /* compress the block. */
    compressed_data_len = max_compressed_data_len;
    snappy_compress(uncompressed_data, uncompressed_data_len, compressed_data, &compressed_data_len);

    if (compressed_data_len >= (uncompressed_data_len - (uncompressed_data_len / 8))) {
      /* uncompressed data */
      type_code = UNCOMPRESSED_DATA_IDENTIFIER;
      write_len = uncompressed_data_len;
      write_data = uncompressed_data;
    } else {
      /* compressed data */
      type_code = COMPRESSED_DATA_IDENTIFIER;
      write_len = compressed_data_len;
      write_data = compressed_data;
    }

    /* write block type */
    putc_unlocked(type_code, outfp);
    /* write data length */
    putc_unlocked(((write_len + 4) >> 0), outfp);
    putc_unlocked(((write_len + 4) >> 8), outfp);
    /* write checksum */
    putc_unlocked((crc32c >>  0), outfp);
    putc_unlocked((crc32c >>  8), outfp);
    putc_unlocked((crc32c >> 16), outfp);
    putc_unlocked((crc32c >> 24), outfp);
    /* write data */
    if (fwrite_unlocked(write_data, write_len, 1, outfp) != 1) {
      print_error("Failed to write a file: %s\n", strerror(errno));
      goto cleanup;
    }
  }
  /* check stream errors */
  if (ferror_unlocked(infp)) {
    print_error("Failed to read a file: %s\n", strerror(errno));
    goto cleanup;
  }
  if (ferror_unlocked(outfp)) {
    print_error("Failed to write a file: %s\n", strerror(errno));
    goto cleanup;
  }
  err = 0;
 cleanup:
  free(uncompressed_data);
  free(compressed_data);
  return err;
}
Example #7
0
static int framing_format_uncompress(FILE *infp, FILE *outfp, int skip_magic)
{
  const size_t max_data_len = MAX_DATA_LEN;
  const size_t max_uncompressed_data_len = MAX_UNCOMPRESSED_DATA_LEN;
  size_t data_len;
  size_t uncompressed_data_len;
  char *data = malloc(max_data_len);
  char *uncompressed_data = malloc(max_uncompressed_data_len);
  int err = 1;

  if (data == NULL || uncompressed_data == NULL) {
    print_error("out of memory\n");
    goto cleanup;
  }

  if (!skip_magic) {
    /* read the steam header */
    if (read_data(data, sizeof(stream_header), infp) != 0) {
      goto cleanup;
    }
    if (memcmp(data, stream_header, sizeof(stream_header)) != 0) {
      print_error("Invalid stream identfier\n");
      goto cleanup;
    }
  }

  for (;;) {
    int id = getc_unlocked(infp);
    if (id == EOF) {
      break;
    }
    data_len = getc_unlocked(infp);
    data_len |= getc_unlocked(infp) << 8;
    if (data_len == (size_t)EOF) {
      print_error("Unexpected end of file\n");
      goto cleanup;
    }
    if (id == COMPRESSED_DATA_IDENTIFIER) {
      /* 4.2. Compressed data (chunk type 0x00) */
      if (data_len < 4) {
        print_error("too short data length %lu\n", data_len);
        goto cleanup;
      }
      if (read_data(data, data_len, infp) != 0) {
        goto cleanup;
      }
      uncompressed_data_len = max_uncompressed_data_len;
      if (snappy_uncompress(data + 4, data_len - 4, uncompressed_data, &uncompressed_data_len)) {
        print_error("Invalid data: snappy_uncompress failed\n");
        goto cleanup;
      }
      if (check_crc32c(uncompressed_data, uncompressed_data_len, data) != 0) {
        goto cleanup;
      }
      if (fwrite_unlocked(uncompressed_data, uncompressed_data_len, 1, outfp) != 1) {
        break;
      }
    } else if (id == UNCOMPRESSED_DATA_IDENTIFIER) {
      /* 4.3. Uncompressed data (chunk type 0x01) */
      if (data_len < 4) {
        print_error("too short data length %lu\n", data_len);
        goto cleanup;
      }
      if (read_data(data, data_len, infp) != 0) {
        goto cleanup;
      }
      if (check_crc32c(data + 4, data_len - 4, data) != 0) {
        goto cleanup;
      }
      if (fwrite_unlocked(data + 4, data_len - 4, 1, outfp) != 1) {
        break;
      }
    } else if (id < 0x80) {
      /* 4.4. Reserved unskippable chunks (chunk types 0x02-0x7f) */
      print_error("Unsupported identifier 0x%02x\n", id);
      goto cleanup;
    } else {
      /* 4.5. Reserved skippable chunks (chunk types 0x80-0xfe) */
      fseek(infp, data_len, SEEK_CUR);
    }
  }
  /* check stream errors */
  if (ferror_unlocked(infp)) {
    print_error("Failed to read a file: %s\n", strerror(errno));
    goto cleanup;
  }
  if (ferror_unlocked(outfp)) {
    print_error("Failed to write a file: %s\n", strerror(errno));
    goto cleanup;
  }
  err = 0;
 cleanup:
  free(data);
  free(uncompressed_data);
  return err;
}
Example #8
0
/**
 * Internal write API, stream lock already held.
 *
 * @returns IPRT status code.
 * @param   pStream             The stream.
 * @param   pvBuf               What to write.
 * @param   cbWrite             How much to write.
 * @param   pcbWritten          Where to optionally return the number of bytes
 *                              written.
 * @param   fSureIsText         Set if we're sure this is UTF-8 text already.
 */
static int rtStrmWriteLocked(PRTSTREAM pStream, const void *pvBuf, size_t cbWrite, size_t *pcbWritten,
                              bool fSureIsText)
{
    int rc = pStream->i32Error;
    if (RT_FAILURE(rc))
        return rc;
    if (pStream->fRecheckMode)
        rtStreamRecheckMode(pStream);

#ifdef RT_OS_WINDOWS
    /*
     * Use the unicode console API when possible in order to avoid stuff
     * getting lost in unnecessary code page translations.
     */
    HANDLE hCon;
    if (rtStrmIsConsoleUnlocked(pStream, &hCon))
    {
# ifdef HAVE_FWRITE_UNLOCKED
        if (!fflush_unlocked(pStream->pFile))
# else
        if (!fflush(pStream->pFile))
# endif
        {
            /** @todo Consider buffering later. For now, we'd rather correct output than
             *        fast output. */
            DWORD    cwcWritten = 0;
            PRTUTF16 pwszSrc = NULL;
            size_t   cwcSrc = 0;
            rc = RTStrToUtf16Ex((const char *)pvBuf, cbWrite, &pwszSrc, 0, &cwcSrc);
            if (RT_SUCCESS(rc))
            {
                if (!WriteConsoleW(hCon, pwszSrc, (DWORD)cwcSrc, &cwcWritten, NULL))
                {
                    /* try write char-by-char to avoid heap problem. */
                    cwcWritten = 0;
                    while (cwcWritten != cwcSrc)
                    {
                        DWORD cwcThis;
                        if (!WriteConsoleW(hCon, &pwszSrc[cwcWritten], 1, &cwcThis, NULL))
                        {
                            if (!pcbWritten || cwcWritten == 0)
                                rc = RTErrConvertFromErrno(GetLastError());
                            break;
                        }
                        if (cwcThis != 1) /* Unable to write current char (amount)? */
                            break;
                        cwcWritten++;
                    }
                }
                if (RT_SUCCESS(rc))
                {
                    if (cwcWritten == cwcSrc)
                    {
                        if (pcbWritten)
                            *pcbWritten = cbWrite;
                    }
                    else if (pcbWritten)
                    {
                        PCRTUTF16   pwszCur = pwszSrc;
                        const char *pszCur  = (const char *)pvBuf;
                        while ((uintptr_t)(pwszCur - pwszSrc) < cwcWritten)
                        {
                            RTUNICP CpIgnored;
                            RTUtf16GetCpEx(&pwszCur, &CpIgnored);
                            RTStrGetCpEx(&pszCur, &CpIgnored);
                        }
                        *pcbWritten = pszCur - (const char *)pvBuf;
                    }
                    else
                        rc = VERR_WRITE_ERROR;
                }
                RTUtf16Free(pwszSrc);
            }
        }
        else
            rc = RTErrConvertFromErrno(errno);
        if (RT_FAILURE(rc))
            ASMAtomicWriteS32(&pStream->i32Error, rc);
        return rc;
    }
#endif /* RT_OS_WINDOWS */

    /*
     * If we're sure it's text output, convert it from UTF-8 to the current
     * code page before printing it.
     *
     * Note! Partial writes are not supported in this scenario because we
     *       cannot easily report back a written length matching the input.
     */
    /** @todo Skip this if the current code set is UTF-8. */
    if (   pStream->fCurrentCodeSet
        && !pStream->fBinary
        && (   fSureIsText
            || rtStrmIsUtf8Text(pvBuf, cbWrite))
       )
    {
        char       *pszSrcFree = NULL;
        const char *pszSrc     = (const char *)pvBuf;
        if (pszSrc[cbWrite])
        {
            pszSrc = pszSrcFree = RTStrDupN(pszSrc, cbWrite);
            if (pszSrc == NULL)
                rc = VERR_NO_STR_MEMORY;
        }
        if (RT_SUCCESS(rc))
        {
            char *pszSrcCurCP;
            rc = RTStrUtf8ToCurrentCP(&pszSrcCurCP, pszSrc);
            if (RT_SUCCESS(rc))
            {
                size_t  cchSrcCurCP = strlen(pszSrcCurCP);
                IPRT_ALIGNMENT_CHECKS_DISABLE(); /* glibc / mempcpy again */
#ifdef HAVE_FWRITE_UNLOCKED
                ssize_t cbWritten = fwrite_unlocked(pszSrcCurCP, cchSrcCurCP, 1, pStream->pFile);
#else
                ssize_t cbWritten = fwrite(pszSrcCurCP, cchSrcCurCP, 1, pStream->pFile);
#endif
                IPRT_ALIGNMENT_CHECKS_ENABLE();
                if (cbWritten == 1)
                {
                    if (pcbWritten)
                        *pcbWritten = cbWrite;
                }
#ifdef HAVE_FWRITE_UNLOCKED
                else if (!ferror_unlocked(pStream->pFile))
#else
                else if (!ferror(pStream->pFile))
#endif
                {
                    if (pcbWritten)
                        *pcbWritten = 0;
                }
                else
                    rc = VERR_WRITE_ERROR;
                RTStrFree(pszSrcCurCP);
            }
            RTStrFree(pszSrcFree);
        }

        if (RT_FAILURE(rc))
            ASMAtomicWriteS32(&pStream->i32Error, rc);
        return rc;
    }
static int snappy_in_java_uncompress(FILE *infp, FILE *outfp, int skip_magic)
{
  snappy_in_java_header_t header;
  work_buffer_t wb;
  int err = 1;
  int outfd;

  wb.c = NULL;
  wb.uc = NULL;

  if (!skip_magic) {
    /* read header */
    if (fread_unlocked(&header, sizeof(header), 1, infp) != 1) {
      print_error("Failed to read a file: %s\n", strerror(errno));
      goto cleanup;
    }

    /* check header */
    if (memcmp(header.magic, SNAPPY_IN_JAVA_MAGIC, SNAPPY_IN_JAVA_MAGIC_LEN) != 0) {
      print_error("This is not a snappy-java file.\n");
      goto cleanup;
    }
  }

  /* Use a file descriptor 'outfd' instead of the stdio file pointer 'outfp'
   * to reduce the number of write system calls.
   */
  fflush(outfp);
  outfd = fileno(outfp);

  /* read body */
  work_buffer_init(&wb, MAX_BLOCK_SIZE);
  for (;;) {
    int compressed_flag;
    size_t length = 0;
    unsigned int crc32c = 0;

    /* read compressed flag */
    compressed_flag = getc_unlocked(infp);
    switch (compressed_flag) {
    case EOF:
      /* read all blocks */
      err = 0;
      goto cleanup;
    case COMPRESSED_FLAG:
    case UNCOMPRESSED_FLAG:
      /* pass */
      break;
    default:
      print_error("Unknown compressed flag 0x%02x\n", compressed_flag);
      goto cleanup;
    }

    /* read data length. */
    length |= (getc_unlocked(infp) << 8);
    length |= (getc_unlocked(infp) << 0);

    /* read crc32c. */
    crc32c |= (getc_unlocked(infp) << 24);
    crc32c |= (getc_unlocked(infp) << 16);
    crc32c |= (getc_unlocked(infp) <<  8);
    crc32c |= (getc_unlocked(infp) <<  0);

    /* check read error */
    if (feof_unlocked(infp)) {
      print_error("Unexpected end of file.\n");
      goto cleanup;
    } else if (ferror_unlocked(infp)) {
      print_error("Failed to read a file: %s\n", strerror(errno));
      goto cleanup;
    }

    /* read data */
    if (fread_unlocked(wb.c, length, 1, infp) != 1) {
      if (feof_unlocked(infp)) {
        print_error("Unexpected end of file\n");
      } else {
        print_error("Failed to read a file: %s\n", strerror(errno));
      }
      goto cleanup;
    }
    trace("read %ld bytes.\n", (long)(length));

    if (compressed_flag == COMPRESSED_FLAG) {
      /* check the uncompressed length */
      size_t uncompressed_length;
      err = snappy_uncompressed_length(wb.c, length, &uncompressed_length);
      if (err != 0) {
        print_error("Invalid data: GetUncompressedLength failed %d\n", err);
        goto cleanup;
      }
      err = 1;
      if (uncompressed_length > wb.uclen) {
        print_error("Invalid data: too long uncompressed length\n");
        goto cleanup;
      }

      /* uncompress and write */
      if (snappy_uncompress(wb.c, length, wb.uc, &uncompressed_length)) {
        print_error("Invalid data: RawUncompress failed\n");
        goto cleanup;
      }
      if (check_and_write_block(outfd, wb.uc, uncompressed_length, 1, crc32c)) {
        goto cleanup;
      }
    } else {
      if (check_and_write_block(outfd, wb.c, length, 1, crc32c)) {
        goto cleanup;
      }
    }
  }
 cleanup:
  work_buffer_free(&wb);
  return err;
}
Example #10
0
static void cut_fields(FILE *stream ) 
{ int c ;
  size_t field_idx ;
  _Bool found_any_selected_field ;
  _Bool buffer_first_field ;
  _Bool tmp ;
  int tmp___0 ;
  ssize_t len ;
  size_t n_bytes ;
  int tmp___1 ;
  int tmp___2 ;
  unsigned char tmp___3 ;
  _Bool tmp___4 ;
  _Bool tmp___5 ;

  {
  field_idx = 1UL;
  found_any_selected_field = (_Bool)0;
  c = getc_unlocked(stream);
  if (c == -1) {
    return;
  } else {

  }
  ungetc(c, stream);
  tmp = print_kth(1UL, (_Bool *)((void *)0));
  if (tmp) {
    tmp___0 = 0;
  } else {
    tmp___0 = 1;
  }
  buffer_first_field = (_Bool )((int )suppress_non_delimited ^ tmp___0);
  while (1) {
    if (field_idx == 1UL) {
      if (buffer_first_field) {
        len = getndelim2(& field_1_buffer, & field_1_bufsize, 0UL, 4294967295UL, (int )delim, '\n', stream);
        if (len < 0L) {
          free((void *)field_1_buffer);
          field_1_buffer = (char *)((void *)0);
          tmp___1 = ferror_unlocked(stream);
          if (tmp___1) {
            break;
          } else {
            tmp___2 = feof_unlocked(stream);
            if (tmp___2) {
              break;
            } else {

            }
          }
          xalloc_die();
        } else {

        }
        n_bytes = (unsigned long )len;
        if (! (n_bytes != 0UL)) {
          __assert_fail("n_bytes != 0", "cut.c", 626U, "cut_fields");
        } else {

        }
        tmp___3 = to_uchar(*(field_1_buffer + (n_bytes - 1UL)));
        if ((int )tmp___3 != (int )delim) {
          if (! suppress_non_delimited) {
            fwrite_unlocked((void const   */* __restrict  */)field_1_buffer, sizeof(char ), n_bytes, (FILE */* __restrict  */)stdout);
            if ((int )*(field_1_buffer + (n_bytes - 1UL)) != 10) {
              putchar_unlocked('\n');
            } else {

            }
          } else {

          }
          continue;
        } else {

        }
        tmp___4 = print_kth(1UL, (_Bool *)((void *)0));
        if (tmp___4) {
          fwrite_unlocked((void const   */* __restrict  */)field_1_buffer, sizeof(char ), n_bytes - 1UL, (FILE */* __restrict  */)stdout);
          found_any_selected_field = (_Bool)1;
        } else {

        }
        field_idx ++;
      } else {

      }
    } else {

    }
    if (c != -1) {
      tmp___5 = print_kth(field_idx, (_Bool *)((void *)0));
      if (tmp___5) {
        if (found_any_selected_field) {
          fwrite_unlocked((void const   */* __restrict  */)output_delimiter_string, sizeof(char ), output_delimiter_length, (FILE */* __restrict  */)stdout);
        } else {

        }
        found_any_selected_field = (_Bool)1;
        while (1) {
          c = getc_unlocked(stream);
          if (c != (int )delim) {
            if (c != 10) {
              if (! (c != -1)) {
                break;
              } else {

              }
            } else {
              break;
            }
          } else {
            break;
          }
          putchar_unlocked(c);
        }
      } else {
        while (1) {
          c = getc_unlocked(stream);
          if (c != (int )delim) {
            if (c != 10) {
              if (! (c != -1)) {
                break;
              } else {

              }
            } else {
              break;
            }
          } else {
            break;
          }
        }
      }
    } else {

    }
    if (c == 10) {
      c = getc_unlocked(stream);
      if (c != -1) {
        ungetc(c, stream);
        c = '\n';
      } else {

      }
    } else {

    }
    if (c == (int )delim) {
      field_idx ++;
    } else {
      if (c == 10) {
        goto _L;
      } else {
        if (c == -1) {
          _L: 
          if (found_any_selected_field) {
            putchar_unlocked('\n');
          } else {
            if (suppress_non_delimited) {
              if (! (field_idx == 1UL)) {
                putchar_unlocked('\n');
              } else {

              }
            } else {
              putchar_unlocked('\n');
            }
          }
          if (c == -1) {
            break;
          } else {

          }
          field_idx = 1UL;
          found_any_selected_field = (_Bool)0;
        } else {

        }
      }
    }
  }
  return;
}
}
Example #11
0
void
checker_read_file_by_line_ex(
        FILE *f,
        checker_error_func_t error_func,
        const char *name,
        char ***out_lines,
        size_t *out_lines_num)
{
  unsigned char **lines = 0, **new_l = 0;
  size_t lines_u = 0, lines_a = 0, new_a = 0;
  unsigned char *buf = 0;
  size_t buf_u = 0, buf_a = 0;
  int c;

  *out_lines = 0;
  *out_lines_num = 0;
  if (!name) name = "";

  while ((c = getc_unlocked(f)) != EOF) {
    if (!isspace(c) && c < ' ') {
      error_func(_("%s: invalid control character with code %d"), name, c);
    }
    if (buf_u == buf_a) {
      if (!buf_a) buf_a = 16;
      buf = xrealloc(buf, buf_a *= 2);
    }
    buf[buf_u++] = c;
    if (c == '\n') {
      if (buf_u == buf_a) {
      if (!buf_a) buf_a = 16;
        buf = xrealloc(buf, buf_a *= 2);
      }
      buf[buf_u] = 0;
      if (lines_u == lines_a) {
        if(!(new_a = lines_a * 2)) new_a = 16;
        XCALLOC(new_l, new_a);
        if (lines_a > 0) {
          memcpy(new_l, lines, lines_a * sizeof(new_l[0]));
        }
        free(lines);
        lines_a = new_a;
        lines = new_l;
      }
      lines[lines_u++] = xstrdup(buf);
      buf_u = 0;
    }
  }

  if (ferror_unlocked(f)) {
    fatal_CF(_("%s: input error"), name);
  }
  if (buf_u > 0) {
    if (buf_u == buf_a) {
      buf = xrealloc(buf, buf_a *= 2);
    }
    buf[buf_u] = 0;

    if (lines_u == lines_a) {
      if(!(new_a = lines_a * 2)) new_a = 16;
      XCALLOC(new_l, new_a);
      if (lines_a > 0) {
        memcpy(new_l, lines, lines_a * sizeof(new_l[0]));
      }
      free(lines);
      lines_a = new_a;
      lines = new_l;
    }
    lines[lines_u++] = buf;
    buf = 0; buf_u = buf_a = 0;
  }

  *out_lines = (char**) lines;
  *out_lines_num = lines_u;
}
Example #12
0
int ferror(FILE* file) {
    flockfile(file);
    int result = ferror_unlocked(file);
    funlockfile(file);
    return result;
}
Example #13
0
File: intercept.c Project: 8l/ekam
static const char* remap_file(const char* syscall_name, const char* pathname,
                              char* buffer, usage_t usage) {
  char* pos;
  int debug = EKAM_DEBUG;

  /* Ad-hoc debugging can be accomplished by setting debug = 1 when a particular file pattern
   * is matched. */

  if (debug) {
    fprintf(stderr, "remap for %s (%s): %s\n",
            syscall_name, (usage == READ ? "read" : "write"), pathname);
  }

  init_streams();

  if (strlen(pathname) >= PATH_MAX) {
    /* Too long. */
    if (debug) fprintf(stderr, "  name too long\n");
    errno = ENAMETOOLONG;
    return NULL;
  }

  if (get_cached_result(pathname, buffer, usage)) {
    if (debug) fprintf(stderr, "  cached: %s\n", buffer);
    return buffer;
  }

  flockfile(ekam_call_stream);

  if (strncmp(pathname, TAG_PROVIDER_PREFIX, strlen(TAG_PROVIDER_PREFIX)) == 0) {
    /* A tag reference.  Construct the tag name in |buffer|. */
    strcpy(buffer, pathname + strlen(TAG_PROVIDER_PREFIX));

    if (usage == READ) {
      /* Change first slash to a colon to form a tag.  E.g. "header/foo.h" becomes
       * "header:foo.h". */
      pos = strchr(buffer, '/');
      if (pos == NULL) {
        /* This appears to be a tag type without a name, so it should look like a directory.
         * We can use the current directory.  TODO:  Return some fake empty directory instead. */
        funlockfile(ekam_call_stream);
        strcpy(buffer, ".");
        if (debug) fprintf(stderr, "  is directory\n");
        return buffer;
      }
      *pos = ':';
      canonicalizePath(pos + 1);

      if (strcmp(buffer, "canonical:.") == 0) {
        /* HACK:  Don't try to remap top directory. */
        funlockfile(ekam_call_stream);
        if (debug) fprintf(stderr, "  current directory\n");
        return "src";
      }
    }

    /* Ask ekam to remap the file name. */
    fputs(usage == READ ? "findProvider " : "newProvider ", ekam_call_stream);
    fputs(buffer, ekam_call_stream);
    fputs("\n", ekam_call_stream);
  } else if (strcmp(pathname, TMP) == 0 ||
             strcmp(pathname, VAR_TMP) == 0 ||
             strncmp(pathname, TMP_PREFIX, strlen(TMP_PREFIX)) == 0 ||
             strncmp(pathname, VAR_TMP_PREFIX, strlen(VAR_TMP_PREFIX)) == 0) {
    /* Temp file.  Ignore. */
    funlockfile(ekam_call_stream);
    if (debug) fprintf(stderr, "  temp file: %s\n", pathname);
    return pathname;
  } else {
    if (strncmp(pathname, current_dir, strlen(current_dir)) == 0) {
      /* The app is trying to open files in the current directory by absolute path.  Treat it
       * exactly as if it had used a relative path. */
      pathname = pathname + strlen(current_dir);
    } else if (pathname[0] == '/') {
      /* Absolute path.  Note the access but don't remap. */
      if (usage == WRITE) {
        /* Cannot write to absolute paths. */
        funlockfile(ekam_call_stream);
        errno = EACCES;
        if (debug) fprintf(stderr, "  absolute path, can't write\n");
        return NULL;
      }

      fputs("noteInput ", ekam_call_stream);
      fputs(pathname, ekam_call_stream);
      fputs("\n", ekam_call_stream);
      fflush(ekam_call_stream);
      if (ferror_unlocked(ekam_call_stream)) {
        funlockfile(ekam_call_stream);
        fprintf(stderr, "error: Ekam call stream broken.\n");
        abort();
      }
      cache_result(pathname, pathname, usage);
      funlockfile(ekam_call_stream);
      if (debug) fprintf(stderr, "  absolute path: %s\n", pathname);
      return pathname;
    }

    /* Path in current directory. */
    strcpy(buffer, pathname);
    canonicalizePath(buffer);
    if (strcmp(buffer, ".") == 0) {
      /* HACK:  Don't try to remap current directory. */
      funlockfile(ekam_call_stream);
      if (debug) fprintf(stderr, "  current directory\n");
      return "src";
    } else {
      /* Ask ekam to remap the file name. */
      fputs(usage == READ ? "findInput " : "newOutput ", ekam_call_stream);
      fputs(buffer, ekam_call_stream);
      fputs("\n", ekam_call_stream);
    }
  }

  fflush(ekam_call_stream);
  if (ferror_unlocked(ekam_call_stream)) {
    funlockfile(ekam_call_stream);
    fprintf(stderr, "error: Ekam call stream broken.\n");
    abort();
  }

  /* Carefully lock the return stream then unlock the call stream, so that we know that
   * responses will be received in the correct order. */
  flockfile(ekam_return_stream);
  funlockfile(ekam_call_stream);

  /* Read response from Ekam. */
  if (fgets(buffer, PATH_MAX, ekam_return_stream) == NULL) {
    funlockfile(ekam_return_stream);
    fprintf(stderr, "error: Ekam return stream broken.\n");
    abort();
  }

  /* Done reading. */
  funlockfile(ekam_return_stream);

  /* Remove the trailing newline. */
  pos = strchr(buffer, '\n');
  if (pos == NULL) {
    fprintf(stderr, "error: Path returned from Ekam was too long.\n");
    abort();
  }
  *pos = '\0';

  if (*buffer == '\0') {
    /* Not found. */
    errno = ENOENT;
    if (debug) fprintf(stderr, "  ekam says no such file\n");
    return NULL;
  }

  cache_result(pathname, buffer, usage);

  if (debug) fprintf(stderr, "  remapped to: %s\n", buffer);
  return buffer;
}
Example #14
0
int
__getdate_r (const char *string, struct tm *tp)
{
  FILE *fp;
  char *line;
  size_t len;
  char *datemsk;
  char *result = NULL;
  time_t timer;
  struct tm tm;
  struct stat64 st;
  int mday_ok = 0;

  datemsk = getenv ("DATEMSK");
  if (datemsk == NULL || *datemsk == '\0')
    return 1;

  if (stat64 (datemsk, &st) < 0)
    return 3;

  if (!S_ISREG (st.st_mode))
    return 4;

  if (__access (datemsk, R_OK) < 0)
    return 2;

  /* Open the template file.  */
  fp = fopen (datemsk, "rce");
  if (fp == NULL)
    return 2;

  /* No threads reading this stream.  */
  __fsetlocking (fp, FSETLOCKING_BYCALLER);

  line = NULL;
  len = 0;
  do
    {
      ssize_t n;

      n = __getline (&line, &len, fp);
      if (n < 0)
	break;
      if (line[n - 1] == '\n')
	line[n - 1] = '\0';

      /* Do the conversion.  */
      tp->tm_year = tp->tm_mon = tp->tm_mday = tp->tm_wday = INT_MIN;
      tp->tm_hour = tp->tm_sec = tp->tm_min = INT_MIN;
      tp->tm_isdst = -1;
      tp->tm_gmtoff = 0;
      tp->tm_zone = NULL;
      result = strptime (string, line, tp);
      if (result && *result == '\0')
	break;
    }
  while (!feof_unlocked (fp));

  /* Free the buffer.  */
  free (line);

  /* Check for errors. */
  if (ferror_unlocked (fp))
    {
      fclose (fp);
      return 5;
    }

  /* Close template file.  */
  fclose (fp);

  if (result == NULL || *result != '\0')
    return 7;

  /* Get current time.  */
  time (&timer);
  __localtime_r (&timer, &tm);

  /* If only the weekday is given, today is assumed if the given day
     is equal to the current day and next week if it is less.  */
  if (tp->tm_wday >= 0 && tp->tm_wday <= 6 && tp->tm_year == INT_MIN
      && tp->tm_mon == INT_MIN && tp->tm_mday == INT_MIN)
    {
      tp->tm_year = tm.tm_year;
      tp->tm_mon = tm.tm_mon;
      tp->tm_mday = tm.tm_mday + (tp->tm_wday - tm.tm_wday + 7) % 7;
      mday_ok = 1;
    }

  /* If only the month is given, the current month is assumed if the
     given month is equal to the current month and next year if it is
     less and no year is given (the first day of month is assumed if
     no day is given.  */
  if (tp->tm_mon >= 0 && tp->tm_mon <= 11 && tp->tm_mday == INT_MIN)
    {
      if (tp->tm_year == INT_MIN)
	tp->tm_year = tm.tm_year + (((tp->tm_mon - tm.tm_mon) < 0) ? 1 : 0);
      tp->tm_mday = first_wday (tp->tm_year, tp->tm_mon, tp->tm_wday);
      mday_ok = 1;
    }

  /* If no hour, minute and second are given the current hour, minute
     and second are assumed.  */
  if (tp->tm_hour == INT_MIN && tp->tm_min == INT_MIN && tp->tm_sec == INT_MIN)
    {
      tp->tm_hour = tm.tm_hour;
      tp->tm_min = tm.tm_min;
      tp->tm_sec = tm.tm_sec;
    }

  /* Fill in the gaps.  */
  if (tp->tm_hour == INT_MIN)
    tp->tm_hour = 0;
  if (tp->tm_min == INT_MIN)
    tp->tm_min = 0;
  if (tp->tm_sec == INT_MIN)
    tp->tm_sec = 0;

  /* If no date is given, today is assumed if the given hour is
     greater than the current hour and tomorrow is assumed if
     it is less.  */
  if (tp->tm_hour >= 0 && tp->tm_hour <= 23
      && tp->tm_mon == INT_MIN
      && tp->tm_mday == INT_MIN && tp->tm_wday == INT_MIN)
    {
      tp->tm_mon = tm.tm_mon;
      tp->tm_mday = tm.tm_mday + ((tp->tm_hour - tm.tm_hour) < 0 ? 1 : 0);
      mday_ok = 1;
    }

  /* More fillers.  */
  if (tp->tm_year == INT_MIN)
    tp->tm_year = tm.tm_year;
  if (tp->tm_mon == INT_MIN)
    tp->tm_mon = tm.tm_mon;

  /* Check if the day of month is within range, and if the time can be
     represented in a time_t.  We make use of the fact that the mktime
     call normalizes the struct tm.  */
  if ((!mday_ok && !check_mday (TM_YEAR_BASE + tp->tm_year, tp->tm_mon,
				tp->tm_mday))
      || mktime (tp) == (time_t) -1)
    return 8;

  return 0;
}