Esempio n. 1
0
int
main (void)
{
  FILE *fp;

  mtrace ();

  setlocale (LC_ALL, "de_DE.UTF-8");

  fp = fopen (inputfile, "r,ccs=ISO-8859-1");
  if (fp == NULL)
    {
      printf ("cannot open \"%s\": %s\n", inputfile, strerror (errno));
      exit (1);
    }

  while (! feof_unlocked (fp))
    {
      wchar_t buf[200];

      if (fgetws_unlocked (buf, sizeof (buf) / sizeof (buf[0]), fp) == NULL)
	break;

      fputws (buf, stdout);
    }

  fclose (fp);

  return 0;
}
Esempio n. 2
0
static int snappy_java_compress(FILE *infp, FILE *outfp, size_t block_size)
{
  snappy_java_header_t header;
  work_buffer_t wb;
  size_t uncompressed_length;
  int err = 1;

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

  if (block_size == 0) {
    block_size = DEFAULT_BLOCK_SIZE;
  }

  /* write the file header */
  memcpy(header.magic, SNAPPY_JAVA_MAGIC, SNAPPY_JAVA_MAGIC_LEN);
  header.version = htonl(SNAPPY_JAVA_FILE_VERSION);
  header.compatible_version = htonl(SNAPPY_JAVA_FILE_VERSION);

  if (fwrite_unlocked(&header, sizeof(header), 1, outfp) != 1) {
    print_error("Failed to write a file: %s\n", strerror(errno));
    goto cleanup;
  }

  /* write file body */
  work_buffer_init(&wb, block_size);
  while ((uncompressed_length = fread_unlocked(wb.uc, 1, wb.uclen, infp)) > 0) {
    size_t compressed_length = wb.clen;

    trace("read %lu bytes.\n", (unsigned long)uncompressed_length);

    /* compress the block. */
    snappy_compress(wb.uc, uncompressed_length, wb.c, &compressed_length);
    trace("compressed_legnth is %lu.\n", (unsigned long)compressed_length);

    /* write the compressed length. */
    putc_unlocked((compressed_length >> 24), outfp);
    putc_unlocked((compressed_length >> 16), outfp);
    putc_unlocked((compressed_length >>  8), outfp);
    putc_unlocked((compressed_length >>  0), outfp);
    trace("write 4 bytes for compressed data length.\n");

    /* write the compressed data. */
    if (fwrite_unlocked(wb.c, compressed_length, 1, outfp) != 1) {
      print_error("Failed to write a file: %s\n", strerror(errno));
      goto cleanup;
    }
    trace("write %ld bytes for compressed data.\n", (long)compressed_length);
  }
  if (!feof_unlocked(infp)) {
    /* fread_unlocked() failed. */
    print_error("Failed to read a file: %s\n", strerror(errno));
    goto cleanup;
  }
  err = 0;
 cleanup:
  work_buffer_free(&wb);
  return err;
}
Esempio n. 3
0
static int feof_lock(FILE* f)
{
#if HAVE_FEOF_UNLOCKED
	return feof_unlocked(f);
#else
	return feof(f);
#endif
}
Esempio n. 4
0
static int snappy_in_java_compress(FILE *infp, FILE *outfp, size_t block_size)
{
  work_buffer_t wb;
  size_t uncompressed_length;
  int err = 1;

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

  if (block_size == 0) {
    block_size = DEFAULT_BLOCK_SIZE;
  }
  if (block_size > MAX_BLOCK_SIZE) {
    print_error("Too large block size: %lu. (default: %d, max: %d)\n",
                (unsigned long)block_size, DEFAULT_BLOCK_SIZE, MAX_BLOCK_SIZE);
    goto cleanup;
  }

  if (fwrite_unlocked(&snappy_in_java_header, sizeof(snappy_in_java_header), 1, outfp) != 1) {
    print_error("Failed to write a file: %s\n", strerror(errno));
    goto cleanup;
  }

  /* write file body */
  work_buffer_init(&wb, block_size);
  while ((uncompressed_length = fread_unlocked(wb.uc, 1, wb.uclen, infp)) > 0) {
    size_t compressed_length = wb.clen;
    unsigned int crc32c = masked_crc32c(wb.uc, uncompressed_length);

    trace("read %lu bytes.\n", (unsigned long)uncompressed_length);

    /* compress the block. */
    snappy_compress(wb.uc, uncompressed_length, wb.c, &compressed_length);
    trace("compressed_legnth is %lu.\n", (unsigned long)compressed_length);

    if (compressed_length >= (uncompressed_length - (uncompressed_length / 8))) {
      trace("write uncompressed data\n");
      if (write_block(outfp, wb.uc, uncompressed_length, FALSE, crc32c) != 0) {
        goto cleanup;
      }
    } else {
      trace("write compressed data\n");
      if (write_block(outfp, wb.c, compressed_length, TRUE, crc32c) != 0) {
        goto cleanup;
      }
    }
  }
  if (!feof_unlocked(infp)) {
    /* fread_unlocked() failed. */
    print_error("Failed to read a file: %s\n", strerror(errno));
    goto cleanup;
  }
  err = 0;
 cleanup:
  work_buffer_free(&wb);
  return err;
}
Esempio n. 5
0
int
main (int argc, char *argv[])
{
  int remaining;

  /* Set locale.  */
  (void) setlocale (LC_ALL, "");

  Dwfl *dwfl = NULL;
  (void) argp_parse (dwfl_standard_argp (), argc, argv, 0, &remaining, &dwfl);
  assert (dwfl != NULL);

  int result = 0;

  /* Now handle the addresses.  In case none are given on the command
     line, read from stdin.  */
  if (remaining == argc)
    {
      /* We use no threads here which can interfere with handling a stream.  */
      (void) __fsetlocking (stdin, FSETLOCKING_BYCALLER);

      char *buf = NULL;
      size_t len = 0;
      while (!feof_unlocked (stdin))
	{
	  if (getline (&buf, &len, stdin) < 0)
	    break;

	  char *endp;
	  uintmax_t addr = strtoumax (buf, &endp, 0);
	  if (endp != buf)
	    result |= handle_address (addr, dwfl);
	  else
	    result = 1;
	}

      free (buf);
    }
  else
    {
      do
	{
	  char *endp;
	  uintmax_t addr = strtoumax (argv[remaining], &endp, 0);
	  if (endp != argv[remaining])
	    result |= handle_address (addr, dwfl);
	  else
	    result = 1;
	}
      while (++remaining < argc);
    }

  dwfl_end (dwfl);

  return result;
}
Esempio n. 6
0
static int read_data(char *buf, size_t buflen, FILE *fp)
{
  if (fread_unlocked(buf, buflen, 1, fp) != 1) {
    if (feof_unlocked(fp)) {
      print_error("Unexpected end of file\n");
    } else {
      print_error("Failed to read a file: %s\n", strerror(errno));
    }
    return -1;
  }
  return 0;
}
Esempio n. 7
0
/*
 * This function returns a malloc'd buffer of the next record in the audit
 * logs. It returns 0 on success, 1 on eof, -1 on error. 
 */
static int get_record(llist **l)
{
	char *rc;
	char *buff = NULL;

	*l = get_ready_event(&lo);
	if (*l)
		return 0;

	while (1) {
		if (!buff) {
			buff = malloc(MAX_AUDIT_MESSAGE_LENGTH);
			if (!buff)
				return -1;
		}
		rc = fgets_unlocked(buff, MAX_AUDIT_MESSAGE_LENGTH,
					log_fd);
		if (rc) {
			if (lol_add_record(&lo, buff)) {
				*l = get_ready_event(&lo);
				if (*l)
					break;
			}
		} else {
			free(buff);
			if (feof_unlocked(log_fd)) {
				// Only mark all events complete if this is
				// the last file.
				if (files_to_process == 0) {
					terminate_all_events(&lo);
				}
				*l = get_ready_event(&lo);
				if (*l)
					return 0;
				else
					return 1;
			} else 
				return -1;
		}
	}
	free(buff);
	return 0;
}
Esempio n. 8
0
/* Read one shadow entry from the given stream.  */
int
__fgetsgent_r (FILE *stream, struct sgrp *resbuf, char *buffer, size_t buflen,
	       struct sgrp **result)
{
  char *p;

  _IO_flockfile (stream);
  do
    {
      buffer[buflen - 1] = '\xff';
      p = fgets_unlocked (buffer, buflen, stream);
      if (p == NULL && feof_unlocked (stream))
	{
	  _IO_funlockfile (stream);
	  *result = NULL;
	  __set_errno (ENOENT);
	  return errno;
	}
      if (p == NULL || buffer[buflen - 1] != '\xff')
	{
	  _IO_funlockfile (stream);
	  *result = NULL;
	  __set_errno (ERANGE);
	  return errno;
	}

      /* Skip leading blanks.  */
      while (isspace (*p))
	++p;
    } while (*p == '\0' || *p == '#' ||	/* Ignore empty and comment lines.  */
	     /* Parse the line.  If it is invalid, loop to
		get the next line of the file to parse.  */
	     ! parse_line (buffer, (void *) resbuf, (void *) buffer, buflen,
			   &errno));

  _IO_funlockfile (stream);

  *result = resbuf;
  return 0;
}
Esempio n. 9
0
static int find_default_type(FILE * fp, const char *role, char **type)
{
	char buf[250];
	char *ptr = "", *end, *t;
	size_t len;
	int found = 0;

	len = strlen(role);
	while (!feof_unlocked(fp)) {
		if (!fgets_unlocked(buf, sizeof buf, fp))
			return -1;
		if (buf[strlen(buf) - 1])
			buf[strlen(buf) - 1] = 0;

		ptr = buf;
		while (*ptr && isspace(*ptr))
			ptr++;
		if (!(*ptr))
			continue;

		if (!strncmp(role, ptr, len)) {
			end = ptr + len;
			if (*end == ':') {
				found = 1;
				ptr = ++end;
				break;
			}
		}
	}

	if (!found)
		return -1;

	t = malloc(strlen(buf) - len);
	if (!t)
		return -1;
	strcpy(t, ptr);
	*type = t;
	return 0;
}
Esempio n. 10
0
/*
 * This function returns a malloc'd buffer of the next record in the audit
 * logs. It returns 0 on success, 1 on eof, -1 on error. 
 */
static int get_record(llist **l)
{
	char *rc;
	char *buff = NULL;

	*l = get_ready_event(&lo);
	if (*l)
		return 0;

	while (1) {
		if (!buff) {
			buff = malloc(MAX_AUDIT_MESSAGE_LENGTH);
			if (!buff)
				return -1;
		}
		rc = fgets_unlocked(buff, MAX_AUDIT_MESSAGE_LENGTH,
					log_fd);
		if (rc) {
			if (lol_add_record(&lo, buff)) {
				*l = get_ready_event(&lo);
				if (*l)
					break;
			}
		} else {
			free(buff);
			if (feof_unlocked(log_fd)) {
				terminate_all_events(&lo);
				*l = get_ready_event(&lo);
				if (*l)
					return 0;
				else
					return 1;
			} else 
				return -1;
		}
	}
	free(buff);
	return 0;
}
Esempio n. 11
0
int fgetc_unlocked(FILE *stream) {
  unsigned char c;
  if (!(stream->flags&CANREAD)) goto kaputt;

  if (stream->ungotten) {
    stream->ungotten=0;
    return stream->ungetbuf;
  }

  log_msg("fgetc fd %d, mb %d, bs %d\n", stream->fd, stream->bm, stream->bs);
  /* common case first */
  if (stream->bm<stream->bs)
  {
    log_msg("fgetc fd %d, %c\n", stream->fd, stream->buf[stream->bm]);
    return (unsigned char)stream->buf[stream->bm++];
  }

  if (feof_unlocked(stream))
    return EOF;
  
  if (__fflush4(stream,BUFINPUT)) return EOF;
  if (stream->bm>=stream->bs) {
    ssize_t len= read(stream->fd,stream->buf,stream->buflen);
    if (len==0) {
      stream->flags|=EOFINDICATOR;
      return EOF;
    } else if (len<0) {
kaputt:
      stream->flags|=ERRORINDICATOR;
      return EOF;
    }
    stream->bm=0;
    stream->bs=len;
  }
  c=stream->buf[stream->bm];
  ++stream->bm;
  return c;
}
Esempio n. 12
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);
}
Esempio n. 13
0
static int comment_43_uncompress(FILE *infp, FILE *outfp, int skip_magic)
{
  block_data_t *block_data = malloc(sizeof(block_data_t));
  size_t work_len = snappy_max_compressed_length(UINT16_MAX); /* length of worst case */
  char *work = malloc(work_len);
  int err = 1;
  stream_state_t state = skip_magic ? PROCESSING_STATE : INITIAL_STATE;

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

  while (state != ERROR_STATE) {
    switch (read_block(infp, block_data)) {
    case EOF:
      if (state == END_OF_STREAM_STATE) {
        err = 0; /* success */
        goto cleanup;
      }
      /* FALLTHROUGH */
    case TOO_SHORT_DATA_BLOCK:
      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;
    }
    state = process_block(outfp, state, block_data, work, work_len);
  }
 cleanup:
  free(block_data);
  free(work);
  return err;
}
Esempio n. 14
0
enum nss_status
_nss_files_setnetgrent (const char *group, struct __netgrent *result)
{
  FILE *fp;
  enum nss_status status;

  if (group[0] == '\0')
    return NSS_STATUS_UNAVAIL;

  /* Find the netgroups file and open it.  */
  fp = fopen (DATAFILE, "rce");
  if (fp == NULL)
    status = errno == EAGAIN ? NSS_STATUS_TRYAGAIN : NSS_STATUS_UNAVAIL;
  else
    {
      /* Read the file line by line and try to find the description
	 GROUP.  We must take care for long lines.  */
      char *line = NULL;
      size_t line_len = 0;
      const ssize_t group_len = strlen (group);

      status = NSS_STATUS_NOTFOUND;
      result->cursor = result->data;

      __fsetlocking (fp, FSETLOCKING_BYCALLER);

      while (!feof_unlocked (fp))
	{
	  ssize_t curlen = getline (&line, &line_len, fp);
	  int found;

	  if (curlen < 0)
	    {
	      status = NSS_STATUS_NOTFOUND;
	      break;
	    }

	  found = (curlen > group_len && strncmp (line, group, group_len) == 0
		   && isspace (line[group_len]));

	  /* Read the whole line (including continuation) and store it
	     if FOUND in nonzero.  Otherwise we don't need it.  */
	  if (found)
	    {
	      /* Store the data from the first line.  */
	      EXPAND (curlen - group_len);
	      memcpy (result->cursor, &line[group_len + 1],
		      curlen - group_len);
	      result->cursor += (curlen - group_len) - 1;
	    }

	  while (line[curlen - 1] == '\n' && line[curlen - 2] == '\\')
	    {
	      /* Yes, we have a continuation line.  */
	      if (found)
		/* Remove these characters from the stored line.  */
		result->cursor -= 2;

	      /* Get next line.  */
	      curlen = getline (&line, &line_len, fp);
	      if (curlen <= 0)
		break;

	      if (found)
		{
		  /* Make sure we have enough room.  */
		  EXPAND (1 + curlen + 1);

		  /* Add separator in case next line starts immediately.  */
		  *result->cursor++ = ' ';

		  /* Copy new line.  */
		  memcpy (result->cursor, line, curlen + 1);
		  result->cursor += curlen;
		}
	    }

	  if (found)
	    {
	      /* Now we have read the line.  */
	      status = NSS_STATUS_SUCCESS;
	      result->cursor = result->data;
	      result->first = 1;
	      break;
	    }
	}

    the_end:
      /* We don't need the file and the line buffer anymore.  */
      free (line);
      fclose (fp);

      if (status != NSS_STATUS_SUCCESS)
	_nss_files_endnetgrent (result);
    }

  return status;
}
static enum nss_status
internal_getgrent_r (ent_t *ent, char *buffer, size_t buflen, const char *user,
		     gid_t group, long int *start, long int *size,
		     gid_t **groupsp, long int limit, int *errnop)
{
  struct parser_data *data = (void *) buffer;
  struct group grpbuf;

  if (!ent->files)
    return getgrent_next_nss (ent, buffer, buflen, user, group,
			      start, size, groupsp, limit, errnop);

  while (1)
    {
      fpos_t pos;
      int parse_res = 0;
      char *p;

      do
	{
	  /* We need at least 3 characters for one line.  */
	  if (__builtin_expect (buflen < 3, 0))
	    {
	    erange:
	      *errnop = ERANGE;
	      return NSS_STATUS_TRYAGAIN;
	    }

	  fgetpos (ent->stream, &pos);
	  buffer[buflen - 1] = '\xff';
	  p = fgets_unlocked (buffer, buflen, ent->stream);
	  if (p == NULL && feof_unlocked (ent->stream))
	    return NSS_STATUS_NOTFOUND;

	  if (p == NULL || __builtin_expect (buffer[buflen - 1] != '\xff', 0))
	    {
	    erange_reset:
	      fsetpos (ent->stream, &pos);
	      goto erange;
	    }

	  /* Terminate the line for any case.  */
	  buffer[buflen - 1] = '\0';

	  /* Skip leading blanks.  */
	  while (isspace (*p))
	    ++p;
	}
      while (*p == '\0' || *p == '#' ||	/* Ignore empty and comment lines. */
	     /* Parse the line.  If it is invalid, loop to
	        get the next line of the file to parse.  */
	     !(parse_res = _nss_files_parse_grent (p, &grpbuf, data, buflen,
						   errnop)));

      if (__builtin_expect (parse_res == -1, 0))
	/* The parser ran out of space.  */
	goto erange_reset;

      if (grpbuf.gr_name[0] != '+' && grpbuf.gr_name[0] != '-')
	/* This is a real entry.  */
	break;

      /* -group */
      if (grpbuf.gr_name[0] == '-' && grpbuf.gr_name[1] != '\0'
	  && grpbuf.gr_name[1] != '@')
	{
	  blacklist_store_name (&grpbuf.gr_name[1], ent);
	  continue;
	}

      /* +group */
      if (grpbuf.gr_name[0] == '+' && grpbuf.gr_name[1] != '\0'
	  && grpbuf.gr_name[1] != '@')
	{
	  if (in_blacklist (&grpbuf.gr_name[1],
			    strlen (&grpbuf.gr_name[1]), ent))
	    continue;
	  /* Store the group in the blacklist for the "+" at the end of
	     /etc/group */
	  blacklist_store_name (&grpbuf.gr_name[1], ent);
	  if (nss_getgrnam_r == NULL)
	    return NSS_STATUS_UNAVAIL;
	  else if (nss_getgrnam_r (&grpbuf.gr_name[1], &grpbuf, buffer,
				   buflen, errnop) != NSS_STATUS_SUCCESS)
	    continue;

	  check_and_add_group (user, group, start, size, groupsp,
			       limit, &grpbuf);

	  return NSS_STATUS_SUCCESS;
	}

      /* +:... */
      if (grpbuf.gr_name[0] == '+' && grpbuf.gr_name[1] == '\0')
	{
	  ent->files = FALSE;
	  return getgrent_next_nss (ent, buffer, buflen, user, group,
				    start, size, groupsp, limit, errnop);
	}
    }

  check_and_add_group (user, group, start, size, groupsp, limit, &grpbuf);

  return NSS_STATUS_SUCCESS;
}
Esempio n. 16
0
int
__readonly_area (const char *ptr, size_t size)
{
  const void *ptr_end = ptr + size;

  FILE *fp = fopen ("/proc/self/maps", "rce");
  if (fp == NULL)
    {
      /* It is the system administrator's choice to not have /proc
	 available to this process (e.g., because it runs in a chroot
	 environment.  Don't fail in this case.  */
      if (errno == ENOENT
	  /* The kernel has a bug in that a process is denied access
	     to the /proc filesystem if it is set[ug]id.  There has
	     been no willingness to change this in the kernel so
	     far.  */
	  || errno == EACCES)
	return 1;
      return -1;
    }

  /* We need no locking.  */
  __fsetlocking (fp, FSETLOCKING_BYCALLER);

  char *line = NULL;
  size_t linelen = 0;

  while (! feof_unlocked (fp))
    {
      if (_IO_getdelim (&line, &linelen, '\n', fp) <= 0)
	break;

      char *p;
      uintptr_t from = strtoul (line, &p, 16);

      if (p == line || *p++ != '-')
	break;

      char *q;
      uintptr_t to = strtoul (p, &q, 16);

      if (q == p || *q++ != ' ')
	break;

      if (from < (uintptr_t) ptr_end && to > (uintptr_t) ptr)
	{
	  /* Found an entry that at least partially covers the area.  */
	  if (*q++ != 'r' || *q++ != '-')
	    break;

	  if (from <= (uintptr_t) ptr && to >= (uintptr_t) ptr_end)
	    {
	      size = 0;
	      break;
	    }
	  else if (from <= (uintptr_t) ptr)
	    size -= to - (uintptr_t) ptr;
	  else if (to >= (uintptr_t) ptr_end)
	    size -= (uintptr_t) ptr_end - from;
	  else
	    size -= to - from;

	  if (!size)
	    break;
	}
    }

  fclose (fp);
  free (line);

  /* If the whole area between ptr and ptr_end is covered by read-only
     VMAs, return 1.  Otherwise return -1.  */
  return size == 0 ? 1 : -1;
}
Esempio n. 17
0
static int snappy_java_uncompress(FILE *infp, FILE *outfp, int skip_magic)
{
  snappy_java_header_t header;
  work_buffer_t wb;
  int err = 1;
  int outfd;

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

  if (skip_magic) {
    /* read header except magic */
    if (fread_unlocked(&header.version, sizeof(header) - sizeof(header.magic), 1, infp) != 1) {
      print_error("Failed to read a file: %s\n", strerror(errno));
      goto cleanup;
    }
  } else {
    /* 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 magic */
    if (memcmp(header.magic, SNAPPY_JAVA_MAGIC, SNAPPY_JAVA_MAGIC_LEN) != 0) {
      print_error("This is not a snappy-java file.\n");
      goto cleanup;
    }
  }

  /* check rest header */
  header.version = ntohl(header.version);
  if (header.version != SNAPPY_JAVA_FILE_VERSION) {
    print_error("Unknown snappy-java version %d\n", header.version);
    goto cleanup;
  }

  header.compatible_version = ntohl(header.compatible_version);
  if (header.compatible_version != SNAPPY_JAVA_FILE_VERSION) {
    print_error("Unknown snappy-java compatible version %d\n", header.compatible_version);
    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, DEFAULT_BLOCK_SIZE);
  for (;;) {
    /* read the compressed length in a block */
    size_t compressed_length = 0;
    size_t uncompressed_length = wb.uclen;
    int idx;

    for (idx = 3; idx >= 0; idx--) {
      int chr = getc_unlocked(infp);
      if (chr == -1) {
        if (idx == 3) {
          /* read all blocks */
          err = 0;
          goto cleanup;
        }
        print_error("Unexpected end of file.\n");
        goto cleanup;
      }
      compressed_length |= (chr << (idx * 8));
    }

    trace("read 4 bytes (compressed_length = %ld)\n", (long)compressed_length);
    if (compressed_length == 0) {
      print_error("Invalid compressed length %ld\n", (long)compressed_length);
      goto cleanup;
    }
    if (compressed_length > wb.clen) {
      work_buffer_resize(&wb, compressed_length, 0);
    }

    /* read the compressed data */
    if (fread_unlocked(wb.c, compressed_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)(compressed_length));

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

    /* uncompress and write */
    if (snappy_uncompress(wb.c, compressed_length, wb.uc, &uncompressed_length)) {
      print_error("Invalid data: RawUncompress failed\n");
      goto cleanup;
    }
    if (write_full(outfd, wb.uc, uncompressed_length) != uncompressed_length) {
      print_error("Failed to write a file: %s\n", strerror(errno));
      goto cleanup;
    }
    trace("write %ld bytes\n", (long)uncompressed_length);
  }
 cleanup:
  work_buffer_free(&wb);
  return err;
}
Esempio n. 18
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;
}
Esempio n. 19
0
static void
usage (void)
{
  printf (_("Usage: sln src dest|file\n\n"));
  printf (_("For bug reporting instructions, please see:\n\
<http://www.gnu.org/software/libc/bugs.html>.\n"));
}

static int
makesymlinks (file)
     const char *file;
{
#ifndef PATH_MAX
#define PATH_MAX 4095
#endif
  char *buffer = NULL;
  size_t bufferlen = 0;
  int ret;
  int lineno;
  FILE *fp;

  if (strcmp (file, "-") == 0)
    fp = stdin;
  else
    {
      fp = fopen (file, "r");
      if (fp == NULL)
	{
	  fprintf (stderr, _("%s: file open error: %m\n"), file);
	  return 1;
	}
    }

  ret = 0;
  lineno = 0;
  while (!feof_unlocked (fp))
    {
      ssize_t n = getline (&buffer, &bufferlen, fp);
      char *src;
      char *dest;
      char *cp = buffer;

      if (n < 0)
	break;
      if (buffer[n - 1] == '\n')
	buffer[n - 1] = '\0';

      ++lineno;
      while (isspace (*cp))
	++cp;
      if (*cp == '\0')
	/* Ignore empty lines.  */
	continue;
      src = cp;

      do
	++cp;
      while (*cp != '\0' && ! isspace (*cp));
      if (*cp != '\0')
	*cp++ = '\0';

      while (isspace (*cp))
	++cp;
      if (*cp == '\0')
	{
	  fprintf (stderr, _("No target in line %d\n"), lineno);
	  ret = 1;
	  continue;
	}
      dest = cp;

      do
	++cp;
      while (*cp != '\0' && ! isspace (*cp));
      if (*cp != '\0')
	*cp++ = '\0';

      ret |= makesymlink (src, dest);
    }
  fclose (fp);

  return ret;
}

static int
makesymlink (src, dest)
     const char *src;
     const char *dest;
{
  struct stat stats;
  const char *error;

  /* Destination must not be a directory. */
  if (lstat (dest, &stats) == 0)
    {
      if (S_ISDIR (stats.st_mode))
	{
	  fprintf (stderr, _("%s: destination must not be a directory\n"),
	  	   dest);
	  return 1;
	}
      else if (unlink (dest) && errno != ENOENT)
	{
	  fprintf (stderr, _("%s: failed to remove the old destination\n"),
	  	   dest);
	  return 1;
	}
    }
  else if (errno != ENOENT)
    {
      error = strerror (errno);
      fprintf (stderr, _("%s: invalid destination: %s\n"), dest, error);
      return -1;
    }

#ifdef S_ISLNK
  if (symlink (src, dest) == 0)
#else
  if (link (src, dest) == 0)
#endif
    {
      /* Destination must exist by now. */
      if (access (dest, F_OK))
        {
	  error = strerror (errno);
	  unlink (dest);
	  fprintf (stderr, _("Invalid link from \"%s\" to \"%s\": %s\n"),
	  	   src, dest, error);
	  return 1;
	}
      return 0;
    }
  else
    {
      error = strerror (errno);
      fprintf (stderr, _("Invalid link from \"%s\" to \"%s\": %s\n"),
      	       src, dest, error);
      return 1;
    }
}
Esempio n. 20
0
int pthread_getattr_np (pthread_t thread, pthread_attr_t *attr)
{
  pthread_handle handle = thread_handle (thread);
  pthread_descr descr;
#ifdef NOT_FOR_L4
  int ret = 0;
#endif

  if (handle == NULL)
    return ENOENT;

  descr = handle_to_descr(handle);

  attr->__detachstate = (descr->p_detached
			 ? PTHREAD_CREATE_DETACHED
			 : PTHREAD_CREATE_JOINABLE);

  attr->__schedpolicy = descr->p_sched_policy;
  if (attr->__schedpolicy == -1)
    return EINVAL;
  attr->__schedparam.sched_priority = descr->p_priority;

  if (attr->__schedparam.sched_priority < 0)
    return EINVAL;

  attr->__inheritsched = descr->p_inheritsched;
  attr->__scope = PTHREAD_SCOPE_SYSTEM;

#ifdef _STACK_GROWS_DOWN
# ifdef USE_TLS
  attr->__stacksize = descr->p_stackaddr - (char *)descr->p_guardaddr
		      - descr->p_guardsize;
# else
  attr->__stacksize = (char *)(descr + 1) - (char *)descr->p_guardaddr
		      - descr->p_guardsize;
# endif
#else
# ifdef USE_TLS
  attr->__stacksize = (char *)descr->p_guardaddr - descr->p_stackaddr;
# else
  attr->__stacksize = (char *)descr->p_guardaddr - (char *)descr;
# endif
#endif
  attr->__guardsize = descr->p_guardsize;
  attr->__stackaddr_set = descr->p_userstack;
#ifdef NEED_SEPARATE_REGISTER_STACK
  if (descr->p_userstack == 0)
    attr->__stacksize *= 2;
  /* XXX This is awkward.  The guard pages are in the middle of the
     two stacks.  We must count the guard size in the stack size since
     otherwise the range of the stack area cannot be computed.  */
  attr->__stacksize += attr->__guardsize;
#endif
#ifdef USE_TLS
  attr->__stackaddr = descr->p_stackaddr;
#else
# ifndef _STACK_GROWS_UP
  attr->__stackaddr = (char *)(descr + 1);
# else
  attr->__stackaddr = (char *)descr;
# endif
#endif


#ifdef NOT_FOR_L4 // XXX: fix for initial thread
#ifdef USE_TLS
  if (attr->__stackaddr == NULL)
#else
  if (descr == &__pthread_initial_thread)
#endif
    {
      /* Stack size limit.  */
      struct rlimit rl;

      /* The safest way to get the top of the stack is to read
	 /proc/self/maps and locate the line into which
	 __libc_stack_end falls.  */
      FILE *fp = fopen ("/proc/self/maps", "rc");
      if (fp == NULL)
	ret = errno;
      /* We need the limit of the stack in any case.  */
      else if (getrlimit (RLIMIT_STACK, &rl) != 0)
	ret = errno;
      else
	{
	  /* We need no locking.  */
	  __fsetlocking (fp, FSETLOCKING_BYCALLER);

	  /* Until we found an entry (which should always be the case)
	     mark the result as a failure.  */
	  ret = ENOENT;

	  char *line = NULL;
	  size_t linelen = 0;
	  uintptr_t last_to = 0;

	  while (! feof_unlocked (fp))
	    {
	      if (getdelim (&line, &linelen, '\n', fp) <= 0)
		break;

	      uintptr_t from;
	      uintptr_t to;
	      if (sscanf (line, "%" SCNxPTR "-%" SCNxPTR, &from, &to) != 2)
		continue;
	      if (from <= (uintptr_t) __libc_stack_end
		  && (uintptr_t) __libc_stack_end < to)
		{
		  /* Found the entry.  Now we have the info we need.  */
		  attr->__stacksize = rl.rlim_cur;
#ifdef _STACK_GROWS_UP
		  /* Don't check to enforce a limit on the __stacksize */
		  attr->__stackaddr = (void *) from;
#else
		  attr->__stackaddr = (void *) to;

		  /* The limit might be too high.  */
		  if ((size_t) attr->__stacksize
		      > (size_t) attr->__stackaddr - last_to)
		    attr->__stacksize = (size_t) attr->__stackaddr - last_to;
#endif

		  /* We succeed and no need to look further.  */
		  ret = 0;
		  break;
		}
	      last_to = to;
	    }

	  fclose (fp);
	  free (line);
	}
    }
#endif
  return 0;

}
Esempio n. 21
0
File: sln.c Progetto: bminor/glibc
static int
makesymlinks (const char *file)
{
  char *buffer = NULL;
  size_t bufferlen = 0;
  int ret;
  int lineno;
  FILE *fp;

  if (strcmp (file, "-") == 0)
    fp = stdin;
  else
    {
      fp = fopen (file, "r");
      if (fp == NULL)
	{
	  fprintf (stderr, _("%s: file open error: %m\n"), file);
	  return 1;
	}
    }

  ret = 0;
  lineno = 0;
  while (!feof_unlocked (fp))
    {
      ssize_t n = getline (&buffer, &bufferlen, fp);
      char *src;
      char *dest;
      char *cp = buffer;

      if (n < 0)
	break;
      if (buffer[n - 1] == '\n')
	buffer[n - 1] = '\0';

      ++lineno;
      while (isspace (*cp))
	++cp;
      if (*cp == '\0')
	/* Ignore empty lines.  */
	continue;
      src = cp;

      do
	++cp;
      while (*cp != '\0' && ! isspace (*cp));
      if (*cp != '\0')
	*cp++ = '\0';

      while (isspace (*cp))
	++cp;
      if (*cp == '\0')
	{
	  fprintf (stderr, _("No target in line %d\n"), lineno);
	  ret = 1;
	  continue;
	}
      dest = cp;

      do
	++cp;
      while (*cp != '\0' && ! isspace (*cp));
      if (*cp != '\0')
	*cp++ = '\0';

      ret |= makesymlink (src, dest);
    }
  fclose (fp);

  return ret;
}
Esempio n. 22
0
/***
 * Implementation
 ***/
inline bool promote::FileReader::eof() const
{
  return (_concurrent ? feof(_fp) : feof_unlocked(_fp)) != 0;
}
Esempio n. 23
0
internal_function
nss_parse_file (const char *fname)
{
  FILE *fp;
  name_database *result;
  name_database_entry *last;
  char *line;
  size_t len;

  /* Open the configuration file.  */
  fp = fopen (fname, "r");
  if (fp == NULL)
    return NULL;

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

  result = (name_database *) malloc (sizeof (name_database));
  if (result == NULL)
    return NULL;

  result->entry = NULL;
  result->library = NULL;
  last = NULL;
  line = NULL;
  len = 0;
  do
    {
      name_database_entry *this;
      ssize_t n;

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

      /* Because the file format does not know any form of quoting we
	 can search forward for the next '#' character and if found
	 make it terminating the line.  */
      *__strchrnul (line, '#') = '\0';

      /* If the line is blank it is ignored.  */
      if (line[0] == '\0')
	continue;

      /* Each line completely specifies the actions for a database.  */
      this = nss_getline (line);
      if (this != NULL)
	{
	  if (last != NULL)
	    last->next = this;
	  else
	    result->entry = this;

	  last = this;
	}
    }
  while (!feof_unlocked (fp));

  /* Free the buffer.  */
  free (line);
  /* Close configuration file.  */
  fclose (fp);

  return result;
}
Esempio n. 24
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;
}
}
Esempio n. 25
0
/* Read the next configuration file.  */
static void
internal_function
read_conf_file (const char *filename, const char *directory, size_t dir_len,
		void **modules, size_t *nmodules)
{
  FILE *fp = fopen (filename, "r");
  char *line = NULL;
  size_t line_len = 0;
  static int modcounter;

  /* Don't complain if a file is not present or readable, simply silently
     ignore it.  */
  if (fp == NULL)
    return;

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

  /* Process the known entries of the file.  Comments start with `#' and
     end with the end of the line.  Empty lines are ignored.  */
  while (!feof_unlocked (fp))
    {
      char *rp, *endp, *word;
      ssize_t n = __getdelim (&line, &line_len, '\n', fp);
      if (n < 0)
	/* An error occurred.  */
	break;

      rp = line;
      /* Terminate the line (excluding comments or newline) by an NUL byte
	 to simplify the following code.  */
      endp = strchr (rp, '#');
      if (endp != NULL)
	*endp = '\0';
      else
	if (rp[n - 1] == '\n')
	  rp[n - 1] = '\0';

      while (__isspace_l (*rp, &_nl_C_locobj))
	++rp;

      /* If this is an empty line go on with the next one.  */
      if (rp == endp)
	continue;

      word = rp;
      while (*rp != '\0' && !__isspace_l (*rp, &_nl_C_locobj))
	++rp;

      if (rp - word == sizeof ("alias") - 1
	  && memcmp (word, "alias", sizeof ("alias") - 1) == 0)
	add_alias (rp, *modules);
      else if (rp - word == sizeof ("module") - 1
	       && memcmp (word, "module", sizeof ("module") - 1) == 0)
	add_module (rp, directory, dir_len, modules, nmodules, modcounter++);
      /* else */
	/* Otherwise ignore the line.  */
    }

  free (line);

  fclose (fp);
}
Esempio n. 26
0
int
_nis_check_default_nss (void)
{
  FILE *fp = fopen (default_nss, "rc");
  int flags = NSS_FLAG_SET;
  if (fp != NULL)
    {
      char *line = NULL;
      size_t linelen = 0;

      __fsetlocking (fp, FSETLOCKING_BYCALLER);

      while (!feof_unlocked (fp))
	{
	  ssize_t n = getline (&line, &linelen, fp);
	  if (n <= 0)
	    break;

	  /* There currently are only two variables we expect, so
	     simplify the parsing.  Recognize only

	       NETID_AUTHORITATIVE = TRUE
	       SERVICES_AUTHORITATIVE = TRUE

	     with arbitrary white spaces.  */
	  char *cp = line;
	  while (isspace (*cp))
	    ++cp;

	  /* Recognize comment lines.  */
	  if (*cp == '#')
	    continue;

	  static const char netid_authoritative[] = "NETID_AUTHORITATIVE";
	  static const char services_authoritative[]
	    = "SERVICES_AUTHORITATIVE";
	  size_t flag_len;
	  if (strncmp (cp, netid_authoritative,
		       flag_len = sizeof (netid_authoritative) - 1) != 0
	      && strncmp (cp, services_authoritative,
			  flag_len = sizeof (services_authoritative) - 1)
		 != 0)
	    continue;

	  cp += flag_len;
	  while (isspace (*cp))
	    ++cp;
	  if (*cp++ != '=')
	    continue;
	  while (isspace (*cp))
	    ++cp;

	  if (strncmp (cp, "TRUE", 4) != 0)
	    continue;
	  cp += 4;

	  while (isspace (*cp))
	    ++cp;

	  if (*cp == '\0')
	    flags |= flag_len == sizeof (netid_authoritative) - 1
		     ? NSS_FLAG_NETID_AUTHORITATIVE
		     : NSS_FLAG_SERVICES_AUTHORITATIVE;
	}

      free (line);

      fclose (fp);
    }

  _nis_default_nss_flags = flags;
  return flags;
}
static void
init (void)
{
  int saved_errno = errno;
  FILE *fp = fopen (default_nss, "rc");
  if (fp != NULL)
    {
      char *line = NULL;
      size_t linelen = 0;

      __fsetlocking (fp, FSETLOCKING_BYCALLER);

      while (!feof_unlocked (fp))
	{
	  ssize_t n = getline (&line, &linelen, fp);
	  if (n <= 0)
	    break;

	  /* Recognize only

	       <THE-VARIABLE> = TRUE

	     with arbitrary white spaces.  */
	  char *cp = line;
	  while (isspace (*cp))
	    ++cp;

	  /* Recognize comment lines.  */
	  if (*cp == '#')
	    continue;

	  int idx;
	  for (idx = 0; idx < nvars; ++idx)
	    if (strncmp (cp, vars[idx].name, vars[idx].len) == 0)
	      break;
	  if (idx == nvars)
	    continue;

	  cp += vars[idx].len;
	  while (isspace (*cp))
	    ++cp;
	  if (*cp++ != '=')
	    continue;
	  while (isspace (*cp))
	    ++cp;

	  if (strncmp (cp, "TRUE", 4) != 0)
	    continue;
	  cp += 4;

	  while (isspace (*cp))
	    ++cp;

	  if (*cp == '\0')
	    default_nss_flags |= vars[idx].flag;
	}

      free (line);

      fclose (fp);
    }
  __set_errno (saved_errno);
}
Esempio n. 28
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;
}
Esempio n. 29
0
int
pthread_getattr_np (
     pthread_t thread_id,
     pthread_attr_t *attr)
{
  struct pthread *thread = (struct pthread *) thread_id;
  struct pthread_attr *iattr = (struct pthread_attr *) attr;
  int ret = 0;

  lll_lock (thread->lock, LLL_PRIVATE);

  /* The thread library is responsible for keeping the values in the
     thread desriptor up-to-date in case the user changes them.  */
  memcpy (&iattr->schedparam, &thread->schedparam,
	  sizeof (struct sched_param));
  iattr->schedpolicy = thread->schedpolicy;

  /* Clear the flags work.  */
  iattr->flags = thread->flags;

  /* The thread might be detached by now.  */
  if (IS_DETACHED (thread))
    iattr->flags |= ATTR_FLAG_DETACHSTATE;

  /* This is the guardsize after adjusting it.  */
  iattr->guardsize = thread->reported_guardsize;

  /* The sizes are subject to alignment.  */
  if (__builtin_expect (thread->stackblock != NULL, 1))
    {
      iattr->stacksize = thread->stackblock_size;
      iattr->stackaddr = (char *) thread->stackblock + iattr->stacksize;
    }
  else
    {
      /* No stack information available.  This must be for the initial
	 thread.  Get the info in some magical way.  */
      assert (abs (thread->pid) == thread->tid);

      /* Stack size limit.  */
      struct rlimit rl;

      /* The safest way to get the top of the stack is to read
	 /proc/self/maps and locate the line into which
	 __libc_stack_end falls.  */
      FILE *fp = fopen ("/proc/self/maps", "rc");
      if (fp == NULL)
	ret = errno;
      /* We need the limit of the stack in any case.  */
      else
	{
	  if (getrlimit (RLIMIT_STACK, &rl) != 0)
	    ret = errno;
	  else
	    {
	      /* We need no locking.  */
	      __fsetlocking (fp, FSETLOCKING_BYCALLER);

	      /* Until we found an entry (which should always be the case)
		 mark the result as a failure.  */
	      ret = ENOENT;

	      char *line = NULL;
	      size_t linelen = 0;
	      uintptr_t last_to = 0;

	      while (! feof_unlocked (fp))
		{
		  if (getdelim (&line, &linelen, '\n', fp) <= 0)
		    break;

		  uintptr_t from;
		  uintptr_t to;
		  if (sscanf (line, "%" SCNxPTR "-%" SCNxPTR, &from, &to) != 2)
		    continue;
		  if (from <= (uintptr_t) __libc_stack_end
		      && (uintptr_t) __libc_stack_end < to)
		    {
		      /* Found the entry.  Now we have the info we need.  */
		      iattr->stacksize = rl.rlim_cur;
		      iattr->stackaddr = (void *) to;

		      /* The limit might be too high.  */
		      if ((size_t) iattr->stacksize
			  > (size_t) iattr->stackaddr - last_to)
			iattr->stacksize = (size_t) iattr->stackaddr - last_to;

		      /* We succeed and no need to look further.  */
		      ret = 0;
		      break;
		    }
		  last_to = to;
		}

	      free (line);
	    }

	  fclose (fp);
	}
    }

  iattr->flags |= ATTR_FLAG_STACKADDR;

  if (ret == 0)
    {
      size_t size = 16;
      cpu_set_t *cpuset = NULL;

      do
	{
	  size <<= 1;

	  void *newp = realloc (cpuset, size);
	  if (newp == NULL)
	    {
	      ret = ENOMEM;
	      break;
	    }
	  cpuset = (cpu_set_t *) newp;

	  ret = __pthread_getaffinity_np (thread_id, size, cpuset);
	}
      /* Pick some ridiculous upper limit.  Is 8 million CPUs enough?  */
      while (ret == EINVAL && size < 1024 * 1024);

      if (ret == 0)
	{
	  iattr->cpuset = cpuset;
	  iattr->cpusetsize = size;
	}
      else
	{
	  free (cpuset);
	  if (ret == ENOSYS)
	    {
	      /* There is no such functionality.  */
	      ret = 0;
	      iattr->cpuset = NULL;
	      iattr->cpusetsize = 0;
	    }
	}
    }

  lll_unlock (thread->lock, LLL_PRIVATE);

  return ret;
}
Esempio n. 30
0
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;
}