static int
timestamp_fprint(FILE * const fp, _Bool unix_ts)
{
    char now_s[128];

    time_t     now;
    struct tm *tm;

    if (time(&now) == (time_t) -1) {
        putc_unlocked('-', fp);
        return -1;
    }
    if (unix_ts) {
        fprintf(fp, "%lu", (unsigned long) now);
    } else {
        tm = localtime(&now);
        strftime(now_s, sizeof now_s, "%c", tm);
        fprintf(fp, "%s", now_s);
    }
    return 0;
}
Exemplo n.º 2
0
finish_output_bmp (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
{
  bmp_dest_ptr dest = (bmp_dest_ptr) dinfo;
  register FILE * outfile = dest->pub.output_file;
  JSAMPARRAY image_ptr;
  register JSAMPROW data_ptr;
  JDIMENSION row;
  register JDIMENSION col;
  cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;

  /* Write the header and colormap */
  if (dest->is_os2)
    write_os2_header(cinfo, dest);
  else
    write_bmp_header(cinfo, dest);

  /* Write the file body from our virtual array */
  for (row = cinfo->output_height; row > 0; row--) {
    if (progress != NULL) {
      progress->pub.pass_counter = (long) (cinfo->output_height - row);
      progress->pub.pass_limit = (long) cinfo->output_height;
      (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
    }
    image_ptr = (*cinfo->mem->access_virt_sarray)
      ((j_common_ptr) cinfo, dest->whole_image, row-1, (JDIMENSION) 1, FALSE);
    data_ptr = image_ptr[0];
    for (col = dest->row_width; col > 0; col--) {
      putc_unlocked(GETJSAMPLE(*data_ptr), outfile);
      data_ptr++;
    }
  }
  if (progress != NULL)
    progress->completed_extra_passes++;

  /* Make sure we wrote the output file OK */
  fflush(outfile);
  if (ferror(outfile))
    ERREXIT(cinfo, JERR_FILE_WRITE);
}
Exemplo n.º 3
0
static int
scramble_stream (FILE *const stream)
{
    size_t n_chars;
    int c;

    for (n_chars = 0; ; n_chars++) {
        c = getc (stream);
        if (c == EOF)
            break;

        c = scramble_char (c);

        if (c != putc_unlocked (c, stdout)) {
            fprintf (stderr, "Failed writing to standard output\n");
            return -1;
        }
    }

    fprintf (stderr, "Read %zu characters\n", n_chars);
    return 0;
}
Exemplo n.º 4
0
wint_t __fputwc_unlocked(wchar_t c, FILE *f)
{
	char mbc[MB_LEN_MAX];
	int l;
	locale_t *ploc = &CURRENT_LOCALE, loc = *ploc;

	if (f->mode <= 0) fwide(f, 1);
	*ploc = f->locale;

	if (isascii(c)) {
		c = putc_unlocked(c, f);
	} else if (f->wpos + MB_LEN_MAX < f->wend) {
		l = wctomb((void *)f->wpos, c);
		if (l < 0) c = WEOF;
		else f->wpos += l;
	} else {
		l = wctomb(mbc, c);
		if (l < 0 || __fwritex((void *)mbc, l, f) < l) c = WEOF;
	}
	if (c==WEOF) f->flags |= F_ERR;
	*ploc = loc;
	return c;
}
Exemplo n.º 5
0
void print_error(const char *file,
                 unsigned line,
                 const char *function,
                 const char *error_string, ...)
{
	char * const file_name = strdup(file);

	if (file_name)
		file = basename(file_name);

	flockfile(stderr);
	fprintf(stderr, "[%d] %s: %u: %s(): ", (int) syscall(SYS_gettid), file, line, function);

	va_list arg;

	va_start(arg, error_string);
	vfprintf(stderr, error_string, arg);
	va_end(arg);
	putc_unlocked('\n', stderr);
	funlockfile(stderr);

	if (file_name)
		free(file_name);
}
Exemplo n.º 6
0
int main(){
  setlocale(LC_ALL,"");
#ifdef LOCAL_TEST
  std::ifstream in("input.txt",std::ifstream::in);
#else
  std::istream& in=std::cin;
#endif
  
  std::string line;
  std::getline(in,line);
  while(std::getline(in,line)){
    size_t sep=line.find(' ');
    std::string str2=line.substr(sep+1);
    line.resize(sep);
    if(line.size()>=str2.size()){
      output(line,str2);
    } else output(str2,line);    
    putc_unlocked('\n',stdout);
  }
#ifdef LOCAL_TEST
  in.close();
#endif
  return 0;
}
Exemplo n.º 7
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;
}
Exemplo n.º 8
0
static int snzip_compress(FILE *infp, FILE *outfp, size_t block_size)
{
  snz_header_t header;
  work_buffer_t wb;
  size_t uncompressed_length;
  int err = 1;
  int nshift;

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

  if (block_size == 0) {
    block_size = 1ul << SNZ_DEFAULT_BLOCK_SIZE;
    nshift = SNZ_DEFAULT_BLOCK_SIZE;
  } else {
    if (block_size > (1ul << SNZ_MAX_BLOCK_SIZE)) {
      print_error("too large block size: %lu\n", block_size);
      goto cleanup;
    }

    for (nshift = 1; nshift <= SNZ_MAX_BLOCK_SIZE; nshift++) {
      if (1ul << nshift == block_size) {
        break;
      }
    }
    if (nshift == SNZ_MAX_BLOCK_SIZE) {
      print_error("The block size must be power of two\n");
      goto cleanup;
    }
  }

  /* write the file header */
  memcpy(header.magic, SNZ_MAGIC, SNZ_MAGIC_LEN);
  header.version = SNZ_FILE_VERSION;
  header.block_size = nshift;

  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. */
    if (compressed_length < (1ul << 7)) {
      putc_unlocked(compressed_length, outfp);
      trace("write 1 byte for compressed data length.\n");
    } else if (compressed_length < (1ul << 14)) {
      putc_unlocked((compressed_length >> 0) | 0x80, outfp);
      putc_unlocked((compressed_length >> 7), outfp);
      trace("write 2 bytes for compressed data length.\n");
    } else if (compressed_length < (1ul << 21)) {
Exemplo n.º 9
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;
}
Exemplo n.º 10
0
int (putc_unlocked)(int c, FILE *f)
{
	return putc_unlocked(c, f);
}
Exemplo n.º 11
0
write_colormap (j_decompress_ptr cinfo, bmp_dest_ptr dest,
		int map_colors, int map_entry_size)
{
  JSAMPARRAY colormap = cinfo->colormap;
  int num_colors = cinfo->actual_number_of_colors;
  FILE * outfile = dest->pub.output_file;
  int i;

  if (colormap != NULL) {
    if (cinfo->out_color_components == 3) {
      /* Normal case with RGB colormap */
      for (i = 0; i < num_colors; i++) {
	putc_unlocked(GETJSAMPLE(colormap[2][i]), outfile);
	putc_unlocked(GETJSAMPLE(colormap[1][i]), outfile);
	putc_unlocked(GETJSAMPLE(colormap[0][i]), outfile);
	if (map_entry_size == 4)
	  putc_unlocked(0, outfile);
      }
    } else {
      /* Grayscale colormap (only happens with grayscale quantization) */
      for (i = 0; i < num_colors; i++) {
	putc_unlocked(GETJSAMPLE(colormap[0][i]), outfile);
	putc_unlocked(GETJSAMPLE(colormap[0][i]), outfile);
	putc_unlocked(GETJSAMPLE(colormap[0][i]), outfile);
	if (map_entry_size == 4)
	  putc_unlocked(0, outfile);
      }
    }
  } else {
    /* If no colormap, must be grayscale data.  Generate a linear "map". */
    for (i = 0; i < 256; i++) {
      putc_unlocked(i, outfile);
      putc_unlocked(i, outfile);
      putc_unlocked(i, outfile);
      if (map_entry_size == 4)
	putc_unlocked(0, outfile);
    }
  }
  /* Pad colormap with zeros to ensure specified number of colormap entries */
  if (i > map_colors)
    ERREXIT1(cinfo, JERR_TOO_MANY_COLORS, i);
  for (; i < map_colors; i++) {
    putc_unlocked(0, outfile);
    putc_unlocked(0, outfile);
    putc_unlocked(0, outfile);
    if (map_entry_size == 4)
      putc_unlocked(0, outfile);
  }
}
Exemplo n.º 12
0
void
__vsyslog_chk(int pri, int flag, const char *fmt, va_list ap)
{
    struct tm now_tm;
    time_t now;
    int fd;
    FILE *f;
    char *buf = 0;
    size_t bufsize = 0;
    size_t msgoff;
#ifndef NO_SIGPIPE
    struct sigaction action, oldaction;
    int sigpipe;
#endif
    int saved_errno = errno;
    char failbuf[3 * sizeof (pid_t) + sizeof "out of memory []"];

#define	INTERNALLOG	LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
    /* Check for invalid bits. */
    if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
        syslog(INTERNALLOG,
               "syslog: unknown facility/priority: %x", pri);
        pri &= LOG_PRIMASK|LOG_FACMASK;
    }

    /* Check priority against setlogmask values. */
    if ((LOG_MASK (LOG_PRI (pri)) & LogMask) == 0)
        return;

    /* Set default facility if none specified. */
    if ((pri & LOG_FACMASK) == 0)
        pri |= LogFacility;

    /* Build the message in a memory-buffer stream.  */
    f = __open_memstream (&buf, &bufsize);
    if (f == NULL)
    {
        /* We cannot get a stream.  There is not much we can do but
           emitting an error messages.  */
        char numbuf[3 * sizeof (pid_t)];
        char *nump;
        char *endp = __stpcpy (failbuf, "out of memory [");
        pid_t pid = __getpid ();

        nump = numbuf + sizeof (numbuf);
        /* The PID can never be zero.  */
        do
            *--nump = '0' + pid % 10;
        while ((pid /= 10) != 0);

        endp = __mempcpy (endp, nump, (numbuf + sizeof (numbuf)) - nump);
        *endp++ = ']';
        *endp = '\0';
        buf = failbuf;
        bufsize = endp - failbuf;
        msgoff = 0;
    }
    else
    {
        __fsetlocking (f, FSETLOCKING_BYCALLER);
        fprintf (f, "<%d>", pri);
        (void) time (&now);
        f->_IO_write_ptr += __strftime_l (f->_IO_write_ptr,
                                          f->_IO_write_end
                                          - f->_IO_write_ptr,
                                          "%h %e %T ",
                                          __localtime_r (&now, &now_tm),
                                          _nl_C_locobj_ptr);
        msgoff = ftell (f);
        if (LogTag == NULL)
            LogTag = __progname;
        if (LogTag != NULL)
            __fputs_unlocked (LogTag, f);
        if (LogStat & LOG_PID)
            fprintf (f, "[%d]", (int) __getpid ());
        if (LogTag != NULL)
        {
            putc_unlocked (':', f);
            putc_unlocked (' ', f);
        }

        /* Restore errno for %m format.  */
        __set_errno (saved_errno);

        /* We have the header.  Print the user's format into the
               buffer.  */
        if (flag == -1)
            vfprintf (f, fmt, ap);
        else
            __vfprintf_chk (f, flag, fmt, ap);

        /* Close the memory stream; this will finalize the data
           into a malloc'd buffer in BUF.  */
        fclose (f);
    }

    /* Output to stderr if requested. */
    if (LogStat & LOG_PERROR) {
        struct iovec iov[2];
        struct iovec *v = iov;

        v->iov_base = buf + msgoff;
        v->iov_len = bufsize - msgoff;
        /* Append a newline if necessary.  */
        if (buf[bufsize - 1] != '\n')
        {
            ++v;
            v->iov_base = (char *) "\n";
            v->iov_len = 1;
        }

        __libc_cleanup_push (free, buf == failbuf ? NULL : buf);

        /* writev is a cancellation point.  */
        (void)__writev(STDERR_FILENO, iov, v - iov + 1);

        __libc_cleanup_pop (0);
    }

    /* Prepare for multiple users.  We have to take care: open and
       write are cancellation points.  */
    struct cleanup_arg clarg;
    clarg.buf = buf;
    clarg.oldaction = NULL;
    __libc_cleanup_push (cancel_handler, &clarg);
    __libc_lock_lock (syslog_lock);

#ifndef NO_SIGPIPE
    /* Prepare for a broken connection.  */
    memset (&action, 0, sizeof (action));
    action.sa_handler = sigpipe_handler;
    sigemptyset (&action.sa_mask);
    sigpipe = __sigaction (SIGPIPE, &action, &oldaction);
    if (sigpipe == 0)
        clarg.oldaction = &oldaction;
#endif

    /* Get connected, output the message to the local logger. */
    if (!connected)
        openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);

    /* If we have a SOCK_STREAM connection, also send ASCII NUL as
       a record terminator.  */
    if (LogType == SOCK_STREAM)
        ++bufsize;

    if (!connected || __send(LogFile, buf, bufsize, send_flags) < 0)
    {
        if (connected)
        {
            /* Try to reopen the syslog connection.  Maybe it went
               down.  */
            closelog_internal ();
            openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
        }

        if (!connected || __send(LogFile, buf, bufsize, send_flags) < 0)
        {
            closelog_internal ();	/* attempt re-open next time */
            /*
             * Output the message to the console; don't worry
             * about blocking, if console blocks everything will.
             * Make sure the error reported is the one from the
             * syslogd failure.
             */
            if (LogStat & LOG_CONS &&
                    (fd = __open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY, 0)) >= 0)
            {
                __dprintf (fd, "%s\r\n", buf + msgoff);
                (void)__close(fd);
            }
        }
    }

#ifndef NO_SIGPIPE
    if (sigpipe == 0)
        __sigaction (SIGPIPE, &oldaction, (struct sigaction *) NULL);
#endif

    /* End of critical section.  */
    __libc_cleanup_pop (0);
    __libc_lock_unlock (syslog_lock);

    if (buf != failbuf)
        free (buf);
}
Exemplo n.º 13
0
static int
do_test (void)
{
  const char blah[] = "BLAH";
  char buf[strlen (blah) + 1];
  FILE *fp, *f;
  const char *cp;
  char *wp;

  if ((fp = fdopen (fd, "w+")) == NULL)
    exit (1);

  flockfile (fp);

  f = fp;
  cp = blah;
  if (ftello (fp) != 0
      || fwrite_unlocked (blah, blah - blah, strlen (blah), f++) != 0
      || f != fp + 1
      || fwrite_unlocked ("", 5.0, 0, --f) != 0
      || f != fp
      || fwrite_unlocked (cp++, 16, 0.25, fp) != 0
      || cp != blah + 1
      || fwrite_unlocked (--cp, 0.25, 16, fp) != 0
      || cp != blah
      || fwrite_unlocked (blah, 0, -0.0, fp) != 0
      || ftello (fp) != 0)
    {
      puts ("One of fwrite_unlocked tests failed");
      exit (1);
    }

  if (fwrite_unlocked (blah, 1, strlen (blah) - 2, fp) != strlen (blah) - 2)
    {
      puts ("Could not write string into file");
      exit (1);
    }

  if (putc_unlocked ('A' + 0x1000000, fp) != 'A')
    {
      puts ("putc_unlocked failed");
      exit (1);
    }

  f = fp;
  cp = blah + strlen (blah) - 1;
  if (putc_unlocked (*cp++, f++) != 'H'
      || f != fp + 1
      || cp != strchr (blah, '\0'))
    {
      puts ("fputc_unlocked failed");
      exit (1);
    }

  if (ftello (fp) != (off_t) strlen (blah))
    {
      printf ("Failed to write %zd bytes to temporary file", strlen (blah));
      exit (1);
    }

  rewind (fp);

  f = fp;
  wp = buf;
  memset (buf, ' ', sizeof (buf));
  if (ftello (fp) != 0
      || fread_unlocked (buf, buf - buf, strlen (blah), f++) != 0
      || f != fp + 1
      || fread_unlocked (buf, 5.0, 0, --f) != 0
      || f != fp
      || fread_unlocked (wp++, 16, 0.25, fp) != 0
      || wp != buf + 1
      || fread_unlocked (--wp, 0.25, 16, fp) != 0
      || wp != buf
      || fread_unlocked (buf, 0, -0.0, fp) != 0
      || ftello (fp) != 0
      || memcmp (buf, "     ", sizeof (buf)) != 0)
    {
      puts ("One of fread_unlocked tests failed");
      exit (1);
    }

  if (fread_unlocked (buf, 1, strlen (blah) - 2, fp) != strlen (blah) - 2)
    {
      puts ("Could not read string from file");
      exit (1);
    }

  if (getc_unlocked (fp) != 'A')
    {
      puts ("getc_unlocked failed");
      exit (1);
    }

  f = fp;
  if (fgetc_unlocked (f++) != 'H'
      || f != fp + 1
      || fgetc_unlocked (--f) != EOF
      || f != fp)
    {
      puts ("fgetc_unlocked failed");
      exit (1);
    }

  if (ftello (fp) != (off_t) strlen (blah))
    {
      printf ("Failed to read %zd bytes from temporary file", strlen (blah));
      exit (1);
    }

  funlockfile (fp);
  fclose (fp);

  return 0;
}
Exemplo n.º 14
0
void dmn_loggerv(int level, const char* fmt, va_list ap) {
    if(alt_stderr) {
#ifndef NDEBUG

        time_t t = time(NULL);
        struct tm tmp;
        localtime_r(&t, &tmp);
        char tstamp[10];
        if(!strftime(tstamp, 10, "%T ", &tmp))
            strcpy(tstamp, "--:--:-- ");

#  if defined SYS_gettid && !defined __APPLE__
        pid_t tid = syscall(SYS_gettid);
        char tidbuf[16];
        snprintf(tidbuf, 16, " [%i]", tid);
#  endif

        const char* pfx;
        switch(level) {
            case LOG_DEBUG: pfx = pfx_debug; break;
            case LOG_INFO: pfx = pfx_info; break;
            case LOG_WARNING: pfx = pfx_warning; break;
            case LOG_ERR: pfx = pfx_err; break;
            case LOG_CRIT: pfx = pfx_crit; break;
            default: pfx = pfx_unknown; break;
        }
        flockfile(alt_stderr);
        fputs_unlocked(tstamp, alt_stderr);
        if(our_logname)
            fputs_unlocked(our_logname, alt_stderr);
#  if defined SYS_gettid && !defined __APPLE__
        fputs_unlocked(tidbuf, alt_stderr);
#  endif
        fputs_unlocked(pfx, alt_stderr);
        va_list apcpy;
        va_copy(apcpy, ap);
        vfprintf(alt_stderr, fmt, apcpy);
        va_end(apcpy);
        putc_unlocked('\n', alt_stderr);
        fflush_unlocked(alt_stderr);
        funlockfile(alt_stderr);

#else // NDEBUG
        if(level != LOG_INFO || send_stderr_info) {
            va_list apcpy;
            va_copy(apcpy, ap);
            flockfile(alt_stderr);
            vfprintf(alt_stderr, fmt, apcpy);
            va_end(apcpy);
            putc_unlocked('\n', alt_stderr);
            fflush_unlocked(alt_stderr);
            funlockfile(alt_stderr);
        }
#endif // NDEBUG
    }

    if(dmn_syslog_alive)
        vsyslog(level, fmt, ap);

    dmn_fmtbuf_reset();
}
Exemplo n.º 15
0
static void
__vsyslogex_chk(int pri, int flag, pid_t cpid, pid_t ctid, const char *fmt, va_list ap) {
    struct tm now_tm;
    time_t now;
    int fd;
    FILE *f;
    char *buf = 0;
    size_t bufsize = 0;
    size_t prioff, msgoff;
#ifndef NO_SIGPIPE
    struct sigaction action, oldaction;
    int sigpipe;
#endif
    int saved_errno = errno;
    char failbuf[3 * sizeof (pid_t) + sizeof "out of memory []"];
    const int LogMask = setlogmask(0);

#ifdef _DEBUGFLAGS_H_
    {
        static unsigned int registered = 0;
        if (unlikely(0 == registered)) {
            registered = 1; /* dirty work around to avoid deadlock: syslogex->register->syslogex */
            registered = (registerLibraryDebugFlags(&debugFlags) == EXIT_SUCCESS);
        }
    }
#endif /*_DEBUGFLAGS_H_*/

#define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
    /* Check for invalid bits. */
    if (unlikely(pri & ~(LOG_PRIMASK | LOG_FACMASK))) {
        /*syslog(INTERNALLOG,
               "syslog: unknown facility/priority: %x", pri);*/
        WARNING_MSG("unknown facility/priority: %x", pri);
        pri &= LOG_PRIMASK | LOG_FACMASK;
    }

    /* Check priority against setlogmask values. */
    if (unlikely((LOG_MASK(LOG_PRI(pri)) & LogMask) == 0))
        return;

    /* Set default facility if none specified. */
    if (unlikely((pri & LOG_FACMASK) == 0))
        pri |= LogFacility;

    /* Build the message in a memory-buffer stream.  */
    f = open_memstream(&buf, &bufsize);
    if (unlikely(f == NULL)) {
        /* We cannot get a stream.  There is not much we can do but
           emitting an error messages with the Process ID.  */
        char numbuf[3 * sizeof (pid_t)];
        char *nump;
        char *endp = __stpcpy(failbuf, "out of memory [");
        pid_t pid = getpid();

        nump = numbuf + sizeof (numbuf);
        /* The PID can never be zero.  */
        do {
            *--nump = '0' + pid % 10;
        } while ((pid /= 10) != 0);

        endp = mempcpy((void*) endp, (const void*) nump, (size_t) ((numbuf + sizeof (numbuf)) - nump));
        *endp++ = ']';
        *endp = '\0';
        buf = failbuf;
        bufsize = endp - failbuf;
        msgoff = 0;
    } else {
        __fsetlocking(f, FSETLOCKING_BYCALLER);
        prioff = fprintf(f, "<%d>", pri);
        (void) time(&now);
        f->_IO_write_ptr += strftime(f->_IO_write_ptr,
                f->_IO_write_end - f->_IO_write_ptr,
                "%h %e %T ",
                localtime_r(&now, &now_tm));
        /*f->_IO_write_ptr += strftime_l (f->_IO_write_ptr,
                                          f->_IO_write_end - f->_IO_write_ptr,
                                          "%h %e %T ",
                                          localtime_r (&now, &now_tm));*/
        msgoff = ftell(f);
        if (LogTag == NULL)
            LogTag = __progname;
        if (LogTag != NULL)
            fputs_unlocked(LogTag, f);
        if (LogStat & LOG_PID) {
            const pid_t pid = ((0 == cpid) ? getpid() : cpid);
            if (LogStat & LOG_TID) {
                const pid_t tid = ((0 == ctid) ? gettid() : ctid);
                fprintf(f, "[%d:%d]", (int) pid, (int) tid);
            } else {
                fprintf(f, "[%d]", (int) pid);
            }
        }

        if (LogStat & LOG_RDTSC) {
            const unsigned long long int t = rdtsc();
            fprintf(f, "(%llu)", t);
        } /* (LogStat & LOG_RDTSC) */

        if (LogStat & LOG_CLOCK) {
            #if HAVE_CLOCK_GETTIME
                struct timespec timeStamp;
                if (clock_gettime(CLOCK_MONOTONIC,&timeStamp) == 0) {
                    fprintf(f,"(%lu.%.9d)",timeStamp.tv_sec,timeStamp.tv_nsec);
                } else {
                    const int error = errno;
                    ERROR_MSG("clock_gettime CLOCK_MONOTONIC error %d (%m)",error);
            }
            #else
                static unsigned int alreadyPrinted = 0;
                if (unlikely(0 == alreadyPrinted)) {
                    ERROR_MSG("clock_gettime  not available on this system");
                    alreadyPrinted = 1;
                }
            #endif
        }  /* (LogStat & LOG_CLOCK) */

        if (LogStat & LOG_LEVEL) {
            switch (LOG_PRI(pri)) {
                case LOG_EMERG:
                    fprintf(f, "[EMERG]");
                    break;
                case LOG_ALERT:
                    fprintf(f, "[ALERT]");
                    break;
                case LOG_CRIT:
                    fprintf(f, "[CRIT]");
                    break;
                case LOG_ERR:
                    fprintf(f, "[ERROR]");
                    break;
                case LOG_WARNING:
                    fprintf(f, "[WARNING]");
                    break;
                case LOG_NOTICE:
                    fprintf(f, "[NOTICE]");
                    break;
                case LOG_INFO:
                    fprintf(f, "[INFO]");
                    break;
                case LOG_DEBUG:
                    fprintf(f, "[DEBUG]");
                    break;
            } /* switch(LOG_PRI(pri))*/
        } /* (LogStat & LOG_LEVEL) */

        if (LogTag != NULL) {
            putc_unlocked(':', f);
            putc_unlocked(' ', f);
        }

        /* Restore errno for %m format.  */
        __set_errno(saved_errno);

        /* We have the header.  Print the user's format into the
         buffer.  */
        if (flag == -1) {
            vfprintf(f, fmt, ap);
        } else {
            __vfprintf_chk(f, flag, fmt, ap);
        }

        /* Close the memory stream; this will finalize the data
           into a malloc'd buffer in BUF.  */
        fclose(f);
    }

    /* Output to stderr if requested. */
    if (LogStat & LOG_PERROR) {
        struct iovec iov[2];
        register struct iovec *v = iov;

        v->iov_base = buf + msgoff;
        v->iov_len = bufsize - msgoff;
        /* Append a newline if necessary.  */
        if (buf[bufsize - 1] != '\n') {
            ++v;
            v->iov_base = (char *) "\n";
            v->iov_len = 1;
        }

        pthread_cleanup_push(free, buf == failbuf ? NULL : buf);

        /* writev is a cancellation point.  */
        (void) writev(STDERR_FILENO, iov, v - iov + 1);

        pthread_cleanup_pop(0);
    }

    /* Prepare for multiple users.  We have to take care: open and
  write are cancellation points.  */
    struct cleanup_arg clarg;
    clarg.buf = buf;
    clarg.oldaction = NULL;
    pthread_cleanup_push(cancel_handler, &clarg);
    pthread_mutex_lock(&syslogex_lock);

#ifndef NO_SIGPIPE
    /* Prepare for a broken connection.  */
    memset(&action, 0, sizeof (action));
    action.sa_handler = sigpipe_handler;
    sigemptyset(&action.sa_mask);
    sigpipe = __sigaction(SIGPIPE, &action, &oldaction);
    if (sigpipe == 0)
        clarg.oldaction = &oldaction;
#endif

    /* Get connected, output the message to the local logger. */
    if (!connected) {
        openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
    }

    /* If we have a SOCK_STREAM connection, also send ASCII NUL as
  a record terminator.  */
    if (LogType == SOCK_STREAM) {
        ++bufsize;
    }

    if (!connected || __send(LogFile, buf, bufsize, send_flags) < 0) {
        if (connected) {
            /* Try to reopen the syslog connection.  Maybe it went
          down.  */
            closelog_internal();
            openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
        }

        if (!connected || __send(LogFile, buf, bufsize, send_flags) < 0) {
            closelog_internal(); /* attempt re-open next time */
            /*
             * Output the message to the console; don't worry
             * about blocking, if console blocks everything will.
             * Make sure the error reported is the one from the
             * syslogd failure.
             */
            if (LogStat & LOG_CONS &&
                    (fd = __open(_PATH_CONSOLE, O_WRONLY | O_NOCTTY, 0)) >= 0) {
                dprintf(fd, "%s\r\n", buf + msgoff);
                (void) __close(fd);
            }
        }
    }

#ifndef NO_SIGPIPE
    if (sigpipe == 0)
        __sigaction(SIGPIPE, &oldaction, (struct sigaction *) NULL);
#endif

    /* End of critical section.  */
    pthread_cleanup_pop(0);
    pthread_mutex_unlock(&syslogex_lock);

    if (buf != failbuf) {
        free(buf);
    }
}
Exemplo n.º 16
0
int VMPI_putc_unlocked(int c, FILE *stream)
{
    return putc_unlocked( c, stream );
}
Exemplo n.º 17
0
int
main(int argc, char *argv[])
{
	char	buffer[BUFSIZ];
	wchar_t	wbuffer[BUFSIZ];
	char	*buf;
	wchar_t	*wbuf;
	FILE	*f;
	off_t	off;
	fpos_t	pos;
	size_t	size;
	int	fd, r;
	char	c;
	wchar_t	wc;

	if ((fd = dup(1)) == -1)
		err(2, "dup");
	if ((dup_stdout = fdopen(fd, "w")) == NULL)
		err(2, "fdopen");
	if ((fd = mkstemp(filename)) == -1)
		err(2, "mkstemp");
	if (write(fd, "0123456789\n\n", 12) != 12 || close(fd))
		err(2, "write + close");

	/* status */
	TEST_UNCHANGED(fwide(f, 0));
	TEST_NARROW(fwide(f, -1));
	TEST_WIDE(fwide(f, 1));
	TEST_UNCHANGED(feof(f));
	TEST_UNCHANGED(ferror(f));
	TEST_UNCHANGED(fileno(f));
	TEST_UNCHANGED(clearerr(f));

	/* flush and purge */
	TEST_UNCHANGED(fflush(f));
	TEST_UNCHANGED(fpurge(f));

	/* positioning */
	TEST_UNCHANGED(fgetpos(f, &pos));
	TEST_UNCHANGED(fgetpos(f, &pos); fsetpos(f, &pos));
	TEST_UNCHANGED(ftell(f));
	TEST_UNCHANGED(ftello(f));
	TEST_UNCHANGED(fseek(f, 1, SEEK_CUR));
	TEST_UNCHANGED(fseek(f, 1, SEEK_SET));
	TEST_UNCHANGED(fseek(f, 1, SEEK_END));
	TEST_UNCHANGED(fseeko(f, 1, SEEK_CUR));
	TEST_UNCHANGED(fseeko(f, 1, SEEK_SET));
	TEST_UNCHANGED(fseeko(f, 1, SEEK_END));
	TEST_UNCHANGED(rewind(f));

	/* buffering */
	TEST_UNCHANGED(setbuf(f, NULL));
	TEST_UNCHANGED(setbuf(f, buffer));
	TEST_UNCHANGED(setvbuf(f, buffer, _IONBF, BUFSIZ));
	TEST_UNCHANGED(setvbuf(f, buffer, _IOLBF, BUFSIZ));
	TEST_UNCHANGED(setvbuf(f, buffer, _IOFBF, BUFSIZ));
	TEST_UNCHANGED(setvbuf(f, NULL, _IONBF, 0));
	TEST_UNCHANGED(setvbuf(f, NULL, _IOLBF, 0));
	TEST_UNCHANGED(setvbuf(f, NULL, _IOFBF, 0));
	TEST_UNCHANGED(setbuffer(f, NULL, 0));
	TEST_UNCHANGED(setbuffer(f, buffer, BUFSIZ));
	TEST_UNCHANGED(setlinebuf(f));

	/* locking */
	TEST_UNCHANGED(flockfile(f);funlockfile(f));
	TEST_UNCHANGED(ftrylockfile(f);funlockfile(f));

	/* input */
	TEST_NARROW(getc(f));
	TEST_NARROW(getc_unlocked(f));
	TEST_NARROW(fgetc(f));
	TEST_NARROW(c = fgetc(f); ungetc(c, f));
	TEST_NARROW(fgets(buffer, BUFSIZ, f));
	TEST_NARROW(fscanf(f, "%s\n", buffer));
	TEST_NARROW(fgetln(f, &size));

	/* output */
	TEST_NARROW(putc('c', f));
	TEST_NARROW(putc_unlocked('c', f));
	TEST_NARROW(fputc('c', f));
	TEST_NARROW(fputs("foo", f));
	TEST_NARROW(fprintf(f, "%s\n", "foo"));

	/* input from stdin */
	TEST_NARROW_STD(stdin, getchar());
	TEST_NARROW_STD(stdin, getchar_unlocked());
	TEST_NARROW_STD(stdin, fgets(buffer, BUFSIZ, stdin));
	TEST_NARROW_STD(stdin, scanf("%s\n", buffer));

	/* output to stdout */
	TEST_NARROW_STD(stdout, putchar('c'));
	TEST_NARROW_STD(stdout, putchar_unlocked('c'));
	TEST_NARROW_STD(stdout, puts("foo"));
	TEST_NARROW_STD(stdout, printf("foo"));

	/* word-size ops */
	/*
	 * fread and fwrite are specified as being implemented in
	 * terms of fgetc() and fputc() and therefore must set the
	 * stream orientation to narrow.
	 */
	TEST_NARROW(fread(buffer, 4, BUFSIZ / 4, f));
	TEST_NARROW(fwrite(buffer, 4, BUFSIZ / 4, f));

	/*
	 * getw() and putw() aren't specified anywhere but logically
	 * should behave the same as fread/fwrite.  Not all OSes agree:
	 * Solaris 10 has them not changing the orientation.
	 */
	TEST_NARROW(getw(f));
	TEST_NARROW(putw(1234, f));


	/* WIDE CHAR TIME! */

	/* input */
	TEST_WIDE(getwc(f));
	TEST_WIDE(fgetwc(f));
	TEST_WIDE(wc = fgetwc(f); ungetwc(wc, f));
	TEST_WIDE(fgetws(wbuffer, BUFSIZ, f));
	TEST_WIDE(fwscanf(f, L"%s\n", wbuffer));

	/* output */
	TEST_WIDE(putwc(L'c', f));
	TEST_WIDE(fputwc(L'c', f));
	TEST_WIDE(fputws(L"foo", f));
	TEST_WIDE(fwprintf(f, L"%s\n", L"foo"));

	/* input from stdin */
	TEST_WIDE_STD(stdin, getwchar());
	TEST_WIDE_STD(stdin, wscanf(L"%s\n", wbuffer));

	/* output to stdout */
	TEST_WIDE_STD(stdout, putwchar(L'c'));
	TEST_WIDE_STD(stdout, wprintf(L"foo"));


	/* memory streams */
	f = open_memstream(&buf, &size);
	if (!((r = fwide(f, 0)) < 0))
		fail(__LINE__, r, "<", "open_memstream()");
	fclose(f);
	f = open_wmemstream(&wbuf, &size);
	if (!((r = fwide(f, 0)) > 0))
		fail(__LINE__, r, ">", "open_wmemstream()");
	fclose(f);


	/* random stuff? */
	TEST_UNCHANGED_STD(stderr, perror("foo"));

	remove(filename);
	if (failures)
		exit(1);
	exit(0);
}
Exemplo n.º 18
0
char *
getpass (const char *prompt)
{
  FILE *tty;
  FILE *in, *out;
  struct termios s, t;
  bool tty_changed = false;
  static char *buf;
  static size_t bufsize;
  ssize_t nread;

  /* Try to write to and read from the terminal if we can.
     If we can't open the terminal, use stderr and stdin.  */

  tty = fopen ("/dev/tty", "w+");
  if (tty == NULL)
    {
      in = stdin;
      out = stderr;
    }
  else
    {
      /* We do the locking ourselves.  */
      __fsetlocking (tty, FSETLOCKING_BYCALLER);

      out = in = tty;
    }

  flockfile (out);

  /* Turn echoing off if it is on now.  */
#if HAVE_TCGETATTR
  if (tcgetattr (fileno (in), &t) == 0)
    {
      /* Save the old one. */
      s = t;
      /* Tricky, tricky. */
      t.c_lflag &= ~(ECHO | ISIG);
      tty_changed = (tcsetattr (fileno (in), TCSAFLUSH | TCSASOFT, &t) == 0);
    }
#endif

  /* Write the prompt.  */
  fputs_unlocked (prompt, out);
  fflush_unlocked (out);

  /* Read the password.  */
  nread = getline (&buf, &bufsize, in);

  /* According to the C standard, input may not be followed by output
     on the same stream without an intervening call to a file
     positioning function.  Suppose in == out; then without this fseek
     call, on Solaris, HP-UX, AIX, OSF/1, the previous input gets
     echoed, whereas on IRIX, the following newline is not output as
     it should be.  POSIX imposes similar restrictions if fileno (in)
     == fileno (out).  The POSIX restrictions are tricky and change
     from POSIX version to POSIX version, so play it safe and invoke
     fseek even if in != out.  */
  fseeko (out, 0, SEEK_CUR);

  if (buf != NULL)
    {
      if (nread < 0)
        buf[0] = '\0';
      else if (buf[nread - 1] == '\n')
        {
          /* Remove the newline.  */
          buf[nread - 1] = '\0';
          if (tty_changed)
            {
              /* Write the newline that was not echoed.  */
              putc_unlocked ('\n', out);
            }
        }
    }

  /* Restore the original setting.  */
#if HAVE_TCSETATTR
  if (tty_changed)
    tcsetattr (fileno (in), TCSAFLUSH | TCSASOFT, &s);
#endif

  funlockfile (out);

  call_fclose (tty);

  return buf;
}
Exemplo n.º 19
0
static int my_putc_unlocked(int c, FILE *fp)
{
    return putc_unlocked(c, _get_actual_fp(fp));
}
Exemplo n.º 20
0
/* Process FS's buffer so that line wrapping is done from POINT_OFFS to the
   end of its buffer.  This code is mostly from glibc stdio/linewrap.c.  */
void
__argp_fmtstream_update (argp_fmtstream_t fs)
{
  char *buf, *nl;
  size_t len;

  /* Scan the buffer for newlines.  */
  buf = fs->buf + fs->point_offs;
  while (buf < fs->p)
    {
      size_t r;

      if (fs->point_col == 0 && fs->lmargin != 0)
	{
	  /* We are starting a new line.  Print spaces to the left margin.  */
	  const size_t pad = fs->lmargin;
	  if (fs->p + pad < fs->end)
	    {
	      /* We can fit in them in the buffer by moving the
		 buffer text up and filling in the beginning.  */
	      memmove (buf + pad, buf, fs->p - buf);
	      fs->p += pad; /* Compensate for bigger buffer. */
	      memset (buf, ' ', pad); /* Fill in the spaces.  */
	      buf += pad; /* Don't bother searching them.  */
	    }
	  else
	    {
	      /* No buffer space for spaces.  Must flush.  */
	      size_t i;
	      for (i = 0; i < pad; i++)
		{
#ifdef _LIBC
		  if (_IO_fwide (fs->stream, 0) > 0)
                    {
#if ! _LIBC || __OPTION_POSIX_WIDE_CHAR_DEVICE_IO
                      putwc_unlocked (L' ', fs->stream);
#else
                      abort ();
#endif
                    }
		  else
#endif
		    putc_unlocked (' ', fs->stream);
		}
	    }
	  fs->point_col = pad;
	}

      len = fs->p - buf;
      nl = memchr (buf, '\n', len);

      if (fs->point_col < 0)
	fs->point_col = 0;

      if (!nl)
	{
	  /* The buffer ends in a partial line.  */

	  if (fs->point_col + len < fs->rmargin)
	    {
	      /* The remaining buffer text is a partial line and fits
		 within the maximum line width.  Advance point for the
		 characters to be written and stop scanning.  */
	      fs->point_col += len;
	      break;
	    }
	  else
	    /* Set the end-of-line pointer for the code below to
	       the end of the buffer.  */
	    nl = fs->p;
	}
      else if (fs->point_col + (nl - buf) < (ssize_t) fs->rmargin)
	{
	  /* The buffer contains a full line that fits within the maximum
	     line width.  Reset point and scan the next line.  */
	  fs->point_col = 0;
	  buf = nl + 1;
	  continue;
	}

      /* This line is too long.  */
      r = fs->rmargin - 1;

      if (fs->wmargin < 0)
	{
	  /* Truncate the line by overwriting the excess with the
	     newline and anything after it in the buffer.  */
	  if (nl < fs->p)
	    {
	      memmove (buf + (r - fs->point_col), nl, fs->p - nl);
	      fs->p -= buf + (r - fs->point_col) - nl;
	      /* Reset point for the next line and start scanning it.  */
	      fs->point_col = 0;
	      buf += r + 1; /* Skip full line plus \n. */
	    }
	  else
	    {
	      /* The buffer ends with a partial line that is beyond the
		 maximum line width.  Advance point for the characters
		 written, and discard those past the max from the buffer.  */
	      fs->point_col += len;
	      fs->p -= fs->point_col - r;
	      break;
	    }
	}
      else
	{
	  /* Do word wrap.  Go to the column just past the maximum line
	     width and scan back for the beginning of the word there.
	     Then insert a line break.  */

	  char *p, *nextline;
	  int i;

	  p = buf + (r + 1 - fs->point_col);
	  while (p >= buf && !isblank (*p))
	    --p;
	  nextline = p + 1;	/* This will begin the next line.  */

	  if (nextline > buf)
	    {
	      /* Swallow separating blanks.  */
	      if (p >= buf)
		do
		  --p;
		while (p >= buf && isblank (*p));
	      nl = p + 1;	/* The newline will replace the first blank. */
	    }
	  else
	    {
	      /* A single word that is greater than the maximum line width.
		 Oh well.  Put it on an overlong line by itself.  */
	      p = buf + (r + 1 - fs->point_col);
	      /* Find the end of the long word.  */
	      do
		++p;
	      while (p < nl && !isblank (*p));
	      if (p == nl)
		{
		  /* It already ends a line.  No fussing required.  */
		  fs->point_col = 0;
		  buf = nl + 1;
		  continue;
		}
	      /* We will move the newline to replace the first blank.  */
	      nl = p;
	      /* Swallow separating blanks.  */
	      do
		++p;
	      while (isblank (*p));
	      /* The next line will start here.  */
	      nextline = p;
	    }

	  /* Note: There are a bunch of tests below for
	     NEXTLINE == BUF + LEN + 1; this case is where NL happens to fall
	     at the end of the buffer, and NEXTLINE is in fact empty (and so
	     we need not be careful to maintain its contents).  */

	  if ((nextline == buf + len + 1
	       ? fs->end - nl < fs->wmargin + 1
	       : nextline - (nl + 1) < fs->wmargin)
	      && fs->p > nextline)
	    {
	      /* The margin needs more blanks than we removed.  */
	      if (fs->end - fs->p > fs->wmargin + 1)
		/* Make some space for them.  */
		{
		  size_t mv = fs->p - nextline;
		  memmove (nl + 1 + fs->wmargin, nextline, mv);
		  nextline = nl + 1 + fs->wmargin;
		  len = nextline + mv - buf;
		  *nl++ = '\n';
		}
	      else
		/* Output the first line so we can use the space.  */
		{
#ifdef _LIBC
		  __fxprintf (fs->stream, "%.*s\n",
			      (int) (nl - fs->buf), fs->buf);
#else
		  if (nl > fs->buf)
		    fwrite_unlocked (fs->buf, 1, nl - fs->buf, fs->stream);
		  putc_unlocked ('\n', fs->stream);
#endif

		  len += buf - fs->buf;
		  nl = buf = fs->buf;
		}
	    }
	  else
	    /* We can fit the newline and blanks in before
	       the next word.  */
	    *nl++ = '\n';

	  if (nextline - nl >= fs->wmargin
	      || (nextline == buf + len + 1 && fs->end - nextline >= fs->wmargin))
	    /* Add blanks up to the wrap margin column.  */
	    for (i = 0; i < fs->wmargin; ++i)
	      *nl++ = ' ';
	  else
	    for (i = 0; i < fs->wmargin; ++i)
#ifdef _LIBC
	      if (_IO_fwide (fs->stream, 0) > 0)
                {
#ifdef OPTION_POSIX_WIDE_CHAR_DEVICE_IO
                  putwc_unlocked (L' ', fs->stream);
#else
                  abort ();
#endif
                }
	      else
#endif
		putc_unlocked (' ', fs->stream);

	  /* Copy the tail of the original buffer into the current buffer
	     position.  */
	  if (nl < nextline)
	    memmove (nl, nextline, buf + len - nextline);
	  len -= nextline - buf;

	  /* Continue the scan on the remaining lines in the buffer.  */
	  buf = nl;

	  /* Restore bufp to include all the remaining text.  */
	  fs->p = nl + len;

	  /* Reset the counter of what has been output this line.  If wmargin
	     is 0, we want to avoid the lmargin getting added, so we set
	     point_col to a magic value of -1 in that case.  */
	  fs->point_col = fs->wmargin ? fs->wmargin : -1;
	}
    }

  /* Remember that we've scanned as far as the end of the buffer.  */
  fs->point_offs = fs->p - fs->buf;
}
Exemplo n.º 21
0
int
jklog_log_ml (jklog * logger, const char *message, const char *marker,
	      unsigned level)
{
#if defined(HAVE_FLOCKFILE) && defined(HAVE_FUNLOCKFILE)
  flockfile (logger->stream);
#endif
#ifdef HAVE_ANSI_COLORS
  if (logger->display & JKLOG_DISPLAY_COLORS)
    fputs (level_color (level), logger->stream);
#endif
  if (logger->display & JKLOG_DISPLAY_SHOW_NAME
      || logger->display & JKLOG_DISPLAY_SHOW_LEVEL)
    {
      putc_unlocked ('[', logger->stream);
    }
  if (logger->display & JKLOG_DISPLAY_SHOW_NAME)
    {
      if (fprintf (logger->stream, "%s", logger->name) < 0)
	{
	  return -1;
	}
    }
  if (logger->display & JKLOG_DISPLAY_SHOW_NAME
      && logger->display & JKLOG_DISPLAY_SHOW_LEVEL)
    {
      fputs (" :: ", logger->stream);
    }
  if (logger->display & JKLOG_DISPLAY_SHOW_NAME
      && !(logger->display & JKLOG_DISPLAY_SHOW_LEVEL))
    {
      fputs ("] ", logger->stream);
    }
  else if (logger->display & JKLOG_DISPLAY_SHOW_LEVEL)
    {
      char buf[7];
      snprintf (buf, 7, "%s]", level_name (level));
      if (fprintf (logger->stream, "%-6s ", buf) < 0)
	{
	  return -1;
	}
    }
  if ((logger->display & JKLOG_DISPLAY_SHOW_MARKER) && (marker != NULL))
    {
      if (fprintf (logger->stream, "%s: ", marker) < 0)
	{
	  return -1;
	}
    }
  if (logger->display & JKLOG_DISPLAY_SHOW_TIME)
    {
      time_t clocktime;
      time (&clocktime);
      struct tm *tm = localtime (&clocktime);
      char datebuf[strlen (logger->datetime_format) * 5];
      if (strftime (datebuf, 512, logger->datetime_format, tm) == 0)
	{
	  return -1;
	}
      if (fprintf (logger->stream, "%s: ", datebuf) < 0)
	{
	  return -1;
	}
    }
  fprintf (logger->stream, "%s\n", message);
#ifdef HAVE_ANSI_COLORS
  if (logger->display & JKLOG_DISPLAY_COLORS)
    fputs ("\033[0m", logger->stream);
#endif
#if defined(HAVE_FLOCKFILE) && defined(HAVE_FUNLOCKFILE)
  funlockfile (logger->stream);
#endif
  return 0;
}
Exemplo n.º 22
0
int
main (int argc, char *argv[])
{
  Elf *elf;
  int fd;
  GElf_Ehdr ehdr;
  int cnt;

  fd = open (argv[1], O_RDONLY);
  if (fd == -1)
    {
      printf ("cannot open \"%s\": %s\n", argv[1], strerror (errno));
      exit (1);
    }

  elf_version (EV_CURRENT);

  elf = elf_begin (fd, ELF_C_READ, NULL);
  if (elf == NULL)
    {
      printf ("cannot open ELF file: %s\n", elf_errmsg (-1));
      exit (1);
    }

  if (elf_kind (elf) != ELF_K_ELF)
    {
      printf ("\"%s\" is not an ELF file\n", argv[1]);
      exit (1);
    }

  if (gelf_getehdr (elf, &ehdr) == NULL)
    {
      printf ("cannot get the ELF header: %s\n", elf_errmsg (-1));
      exit (1);
    }

  printf ("idx type    %*s %*s %*s %*s %*s  align flags\n",
	  gelf_getclass (elf) == ELFCLASS32 ? 9 : 17, "offset",
	  gelf_getclass (elf) == ELFCLASS32 ? 10 : 18, "vaddr",
	  gelf_getclass (elf) == ELFCLASS32 ? 10 : 18, "paddr",
	  gelf_getclass (elf) == ELFCLASS32 ? 9 : 12, "filesz",
	  gelf_getclass (elf) == ELFCLASS32 ? 9 : 12, "memsz");

  for (cnt = 0; cnt < ehdr.e_phnum; ++cnt)
    {
      static const char *typenames[] =
      {
	[PT_NULL] = "NULL",
	[PT_LOAD] = "LOAD",
	[PT_DYNAMIC] = "DYNAMIC",
	[PT_INTERP] = "INTERP",
	[PT_NOTE] = "NOTE",
	[PT_SHLIB] = "SHLIB",
	[PT_PHDR] = "PHDR"
      };
      GElf_Phdr mem;
      GElf_Phdr *phdr = gelf_getphdr (elf, cnt, &mem);
      char buf[19];
      const char *p_type = typenames[phdr->p_type];

      /* If we don't know the name of the type we use the number value.  */
      if (phdr->p_type >= PT_NUM)
	{
	  snprintf (buf, sizeof (buf), "%x", phdr->p_type);
	  p_type = buf;
	}

      printf ("%3d %-7s %#0*llx %#0*llx %#0*llx %#0*llx %#0*llx %#6llx ",
	      cnt, p_type,
	      gelf_getclass (elf) == ELFCLASS32 ? 9 : 17,
	      (unsigned long long int) phdr->p_offset,
	      gelf_getclass (elf) == ELFCLASS32 ? 10 : 18,
	      (unsigned long long int) phdr->p_vaddr,
	      gelf_getclass (elf) == ELFCLASS32 ? 10 : 18,
	      (unsigned long long int) phdr->p_paddr,
	      gelf_getclass (elf) == ELFCLASS32 ? 9 : 12,
	      (unsigned long long int) phdr->p_filesz,
	      gelf_getclass (elf) == ELFCLASS32 ? 9 : 12,
	      (unsigned long long int) phdr->p_memsz,
	      (unsigned long long int) phdr->p_align);

      putc_unlocked ((phdr->p_flags & PF_X) ? 'X' : ' ', stdout);
      putc_unlocked ((phdr->p_flags & PF_W) ? 'W' : ' ', stdout);
      putc_unlocked ((phdr->p_flags & PF_R) ? 'R' : ' ', stdout);

      putc_unlocked ('\n', stdout);

      if (phdr->p_type == PT_INTERP)
	{
	  /* We can show the user the name of the interpreter.  */
	  size_t maxsize;
	  char *filedata = elf_rawfile (elf, &maxsize);

	  if (filedata != NULL && phdr->p_offset < maxsize)
	    printf ("\t[Requesting program interpreter: %s]\n",
		    filedata + phdr->p_offset);
	}
    }

  if (elf_end (elf) != 0)
    {
      printf ("error while freeing ELF descriptor: %s\n", elf_errmsg (-1));
      exit (1);
    }

  return 0;
}
Exemplo n.º 23
0
int __darwin___swbuf(int c, __darwin_FILE* f)
{
	return putc_unlocked(c, f->linux_fp);
}
Exemplo n.º 24
0
static int
do_test (void)
{
  const char blah[] = "BLAH";
  char buf[strlen (blah) + 1];
  FILE *fp, *f;
  const char *cp;
  char *wp;

  if ((fp = fdopen (fd, "w+")) == NULL)
    exit (1);

  flockfile (fp);

  f = fp;
  cp = blah;
  /* These tests deliberately use fwrite_unlocked with the size
     argument specified as 0, which results in "division by zero"
     warnings from the expansion of that macro (in code that is not
     evaluated for a size of 0).  This applies to the tests of
     fread_unlocked below as well.  */
  DIAG_PUSH_NEEDS_COMMENT;
  DIAG_IGNORE_NEEDS_COMMENT (4.9, "-Wdiv-by-zero");
  if (ftello (fp) != 0
      || fwrite_unlocked (blah, blah - blah, strlen (blah), f++) != 0
      || f != fp + 1
      || fwrite_unlocked ("", 5.0, 0, --f) != 0
      || f != fp
      || fwrite_unlocked (cp++, 16, 0.25, fp) != 0
      || cp != blah + 1
      || fwrite_unlocked (--cp, 0.25, 16, fp) != 0
      || cp != blah
      || fwrite_unlocked (blah, 0, -0.0, fp) != 0
      || ftello (fp) != 0)
    {
      puts ("One of fwrite_unlocked tests failed");
      exit (1);
    }
  DIAG_POP_NEEDS_COMMENT;

  if (fwrite_unlocked (blah, 1, strlen (blah) - 2, fp) != strlen (blah) - 2)
    {
      puts ("Could not write string into file");
      exit (1);
    }

  if (putc_unlocked ('A' + 0x1000000, fp) != 'A')
    {
      puts ("putc_unlocked failed");
      exit (1);
    }

  f = fp;
  cp = blah + strlen (blah) - 1;
  if (putc_unlocked (*cp++, f++) != 'H'
      || f != fp + 1
      || cp != strchr (blah, '\0'))
    {
      puts ("fputc_unlocked failed");
      exit (1);
    }

  if (ftello (fp) != (off_t) strlen (blah))
    {
      printf ("Failed to write %zd bytes to temporary file", strlen (blah));
      exit (1);
    }

  rewind (fp);

  f = fp;
  wp = buf;
  memset (buf, ' ', sizeof (buf));
  /* See explanation above.  */
  DIAG_PUSH_NEEDS_COMMENT;
  DIAG_IGNORE_NEEDS_COMMENT (4.9, "-Wdiv-by-zero");
  if (ftello (fp) != 0
      || fread_unlocked (buf, buf - buf, strlen (blah), f++) != 0
      || f != fp + 1
      || fread_unlocked (buf, 5.0, 0, --f) != 0
      || f != fp
      || fread_unlocked (wp++, 16, 0.25, fp) != 0
      || wp != buf + 1
      || fread_unlocked (--wp, 0.25, 16, fp) != 0
      || wp != buf
      || fread_unlocked (buf, 0, -0.0, fp) != 0
      || ftello (fp) != 0
      || memcmp (buf, "     ", sizeof (buf)) != 0)
    {
      puts ("One of fread_unlocked tests failed");
      exit (1);
    }
  DIAG_POP_NEEDS_COMMENT;

  if (fread_unlocked (buf, 1, strlen (blah) - 2, fp) != strlen (blah) - 2)
    {
      puts ("Could not read string from file");
      exit (1);
    }

  if (getc_unlocked (fp) != 'A')
    {
      puts ("getc_unlocked failed");
      exit (1);
    }

  f = fp;
  if (fgetc_unlocked (f++) != 'H'
      || f != fp + 1
      || fgetc_unlocked (--f) != EOF
      || f != fp)
    {
      puts ("fgetc_unlocked failed");
      exit (1);
    }

  if (ftello (fp) != (off_t) strlen (blah))
    {
      printf ("Failed to read %zd bytes from temporary file", strlen (blah));
      exit (1);
    }

  funlockfile (fp);
  fclose (fp);

  return 0;
}
Exemplo n.º 25
0
/*****************************************************************************
 * PrintMsg: output a standard message item to stderr
 *****************************************************************************
 * Print a message to stderr, with colour formatting if needed.
 *****************************************************************************/
static void PrintMsg ( vlc_object_t *p_this, const msg_item_t *p_item )
{
#   define COL(x,y)  "\033[" #x ";" #y "m"
#   define RED     COL(31,1)
#   define GREEN   COL(32,1)
#   define YELLOW  COL(0,33)
#   define WHITE   COL(0,1)
#   define GRAY    "\033[0m"
    static const char msgtype[4][9] = { "", " error", " warning", " debug" };
    static const char msgcolor[4][8] = { WHITE, RED, YELLOW, GRAY };

    libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
    int type = p_item->i_type;

    if (priv->i_verbose < 0 || priv->i_verbose < (type - VLC_MSG_ERR))
        return;

    const char *objtype = p_item->psz_object_type;
    msg_bank_t *bank = priv->msg_bank;
    void * val = vlc_dictionary_value_for_key (&bank->enabled_objects,
                                               p_item->psz_module);
    if( val == kObjectPrintingDisabled )
        return;
    if( val == kObjectPrintingEnabled )
        /* Allowed */;
    else
    {
        val = vlc_dictionary_value_for_key (&bank->enabled_objects,
                                            objtype);
        if( val == kObjectPrintingDisabled )
            return;
        if( val == kObjectPrintingEnabled )
            /* Allowed */;
        else if( !bank->all_objects_enabled )
            return;
    }

    /* Send the message to stderr */
    FILE *stream = stderr;
    int canc = vlc_savecancel ();

    flockfile (stream);
    fprintf (stream, priv->b_color ? "["GREEN"%p"GRAY"] " : "[%p] ",
            (void *)p_item->i_object_id);
    if (p_item->psz_header != NULL)
        utf8_fprintf (stream, "[%s] ", p_item->psz_header);
    utf8_fprintf (stream, "%s %s%s: ", p_item->psz_module, objtype,
                  msgtype[type]);
    if (priv->b_color)
        fputs (msgcolor[type], stream);
    fputs (p_item->psz_msg, stream);
    if (priv->b_color)
        fputs (GRAY, stream);
    putc_unlocked ('\n', stream);
#if defined (WIN32) || defined (__OS2__)
    fflush (stream);
#endif
    funlockfile (stream);
#ifdef ANDROID
    int level[] = {ANDROID_LOG_INFO, ANDROID_LOG_ERROR, ANDROID_LOG_WARN, ANDROID_LOG_DEBUG};
    __android_log_print(
        level[p_item->i_type],
        "faplayer",
        p_item->psz_header ? "[%p][%s] %s %s: %s" : "[%p]%s%s %s: %s",
        (void *) p_item->i_object_id,
        p_item->psz_header ? p_item->psz_header : "",
        p_item->psz_module,
        p_item->psz_object_type,
        p_item->psz_msg
    );
#endif
    vlc_restorecancel (canc);
}