void gen_assert_discr_fun(z3_wrapper *z3, const clone *clone, const pred *pred, int fun_arity) {
  gen_header(z3);

  /* the basis of the clone */
  struct pred *pred_list;
  uint64_t num_preds;
  clone_get_predicates(clone, &pred_list, &num_preds);

  /* write a definition for all predicates */
  Z3_func_decl preds[num_preds];
  for(int i = 0; i < num_preds; ++i) {
    char name[8];
    sprintf(name, "p%d", i);
    preds[i] = gen_pred(z3, name, &pred_list[i]);
  }

  Z3_func_decl p = gen_pred(z3, "p", pred);

  /* declare a discriminating function */
  Z3_func_decl f = gen_fun(z3, "f", fun_arity);
  z3->fun = f;

  /* write assertions about function preservation */
  for(int i = 0; i < num_preds; ++i) {
    gen_preserve(z3, 0, f, fun_arity, preds[i], pred_list[i].arity);
  }
  gen_preserve(z3, 1, f, fun_arity, p, pred->arity);

  free(pred_list);
}
Пример #2
0
static
void gen_new_order_single(fix_message_data* data)
{
	data->hdr.MsgType = 'D';
	gen_header(&data->hdr);
	gen_random_string(data->order.Account, sizeof(data->order.Account));
	gen_random_string(data->order.ClOrdID, sizeof(data->order.ClOrdID));
	gen_timestamp(&data->order.TransactTime);
	data->order.HandlInst = CHAR_FROM("123");
	data->order.OrdType = CHAR_FROM("123456789DEGIJKLMP");
	data->order.Side = CHAR_FROM("123456789ABCDEFG");
	data->order.TimeInForce = CHAR_FROM("1234567");
	data->order.Price = gen_price();
}
Пример #3
0
// generate header
void idaapi header(void)
{
  gen_header(GH_PRINT_ALL_BUT_BYTESEX, NULL, device);

  char buf[MAXSTR];
  const char *n = ptype_str();

  // print the processor directive .m32r, or .m32rx
  if ( n != NULL )
  {
    qsnprintf(buf, sizeof(buf), COLSTR(".%s", SCOLOR_ASMDIR), n);
    MakeLine(buf,0);
  }
}
Пример #4
0
static int receive(struct sr_output *o, const struct sr_dev_inst *sdi,
                   const struct sr_datafeed_packet *packet, GString **out)
{
    struct context *ctx;
    const struct sr_datafeed_meta *meta;
    const struct sr_datafeed_logic *logic;
    const struct sr_config *src;
    GSList *l;
    unsigned int i, j;
    uint8_t c;

    *out = NULL;
    if (!o || !o->sdi)
        return SR_ERR_ARG;
    ctx = o->internal;

    switch (packet->type) {
    case SR_DF_META:
        meta = packet->payload;
        for (l = meta->config; l; l = l->next) {
            src = l->data;
            if (src->key == SR_CONF_SAMPLERATE)
                ctx->samplerate = g_variant_get_uint64(src->data);
        }
        break;
    case SR_DF_LOGIC:
        logic = packet->payload;
        if (ctx->num_samples == 0) {
            /* First logic packet in the feed. */
            *out = gen_header(sdi, ctx);
        } else
            *out = g_string_sized_new(512);
        for (i = 0; i <= logic->length - logic->unitsize; i += logic->unitsize) {
            for (j = 0; j < logic->unitsize; j++) {
                /* The OLS format wants the samples presented MSB first. */
                c = *((uint8_t *)logic->data + i + logic->unitsize - 1 - j);
                g_string_append_printf(*out, "%02x", c);
            }
            g_string_append_printf(*out, "@%"PRIu64"\n", ctx->num_samples++);
        }
        break;
    }

    return SR_OK;
}
static HCFileInfo*
parse_configs(const char* fname)
{
  FILE *fd;
  char buf[64*1024]; /* Way huge, but wth */
  HCFileInfo *head_finfo = NULL, *finfo = NULL, *prev_finfo = NULL;

  if (NULL == (fd = fopen(fname, "r")))
    return NULL;

  while (!feof(fd)) {
    char *str, *save;
    int state = 0;
    char *ok=NULL, *miss=NULL, *mime=NULL;

    prev_finfo = finfo;
    finfo = TSmalloc(sizeof(HCFileInfo));
    memset(finfo, 0, sizeof(HCFileInfo));

    if (NULL == head_finfo)
      head_finfo = finfo;
    if (prev_finfo)
      prev_finfo->_next = finfo;

    fread(buf, sizeof(buf), 1, fd);
    str = strtok_r(buf, "\t", &save);
    while (NULL != str) {
      if (strlen(str) > 0) {
        switch (state) {
        case 0:
          if ('/' == *str)
            ++str;
          strncpy(finfo->path, str, MAX_PATH_LEN - 1);
          finfo->p_len = strlen(finfo->path);
          break;
        case 1:
          strncpy(finfo->fname, str, MAX_FILENAME_LEN - 1);
          finfo->basename = strrchr(finfo->fname, '/');
          if (finfo->basename)
            ++(finfo->basename);
          break;
        case 2:
          mime = str;
          break;
        case 3:
          ok = str;
          break;
        case 4:
          miss = str;
          break;
        }
        ++state;
      }
      str = strtok_r(NULL, "\t", &save);
    }

    finfo->ok = gen_header(ok, mime, &finfo->o_len);
    finfo->miss = gen_header(miss, mime, &finfo->m_len);
    finfo->data = TSmalloc(sizeof(HCFileData));
    memset(finfo->data, 0, sizeof(HCFileData));
    reload_status_file(finfo, finfo->data);
  }
  fclose(fd);

  return head_finfo;
}
Пример #6
0
//--------------------------------------------------------------------------
void idaapi header(void)
{
  gen_header(GH_PRINT_ALL);
}
Пример #7
0
static int receive(const struct sr_output *o, const struct sr_datafeed_packet *packet,
		GString **out)
{
	const struct sr_datafeed_meta *meta;
	const struct sr_datafeed_logic *logic;
	const struct sr_config *src;
	GSList *l;
	struct context *ctx;
	int idx, pos, offset;
	uint64_t i, j;
	gchar *p;

	*out = NULL;
	if (!o || !o->sdi)
		return SR_ERR_ARG;
	if (!(ctx = o->priv))
		return SR_ERR_ARG;

	switch (packet->type) {
	case SR_DF_META:
		meta = packet->payload;
		for (l = meta->config; l; l = l->next) {
			src = l->data;
			if (src->key != SR_CONF_SAMPLERATE)
				continue;
			ctx->samplerate = g_variant_get_uint64(src->data);
		}
		break;
	case SR_DF_TRIGGER:
		ctx->trigger = ctx->spl_cnt;
		break;
	case SR_DF_LOGIC:
		if (!ctx->header_done) {
			*out = gen_header(o);
			ctx->header_done = TRUE;
		} else
			*out = g_string_sized_new(512);

		logic = packet->payload;
		for (i = 0; i <= logic->length - logic->unitsize; i += logic->unitsize) {
			ctx->spl_cnt++;
			pos = ctx->spl_cnt & 7;
			for (j = 0; j < ctx->num_enabled_channels; j++) {
				idx = ctx->channel_index[j];
				p = logic->data + i + idx / 8;
				ctx->sample_buf[j] <<= 1;
				if (*p & (1 << (idx % 8)))
					ctx->sample_buf[j] |= 1;
				if (ctx->spl_cnt && pos == 0) {
					/* Buffered a byte's worth, output hex. */
					g_string_append_printf(ctx->lines[j], "%.2x ",
							ctx->sample_buf[j]);
					ctx->sample_buf[j] = 0;
				}

				if (ctx->spl_cnt == ctx->spl) {
					/* Flush line buffers. */
					g_string_append_len(*out, ctx->lines[j]->str, ctx->lines[j]->len);
					g_string_append_c(*out, '\n');
					if (j == ctx->num_enabled_channels  - 1 && ctx->trigger > -1) {
						offset = ctx->trigger + ctx->trigger / 8;
						g_string_append_printf(*out, "T:%*s^ %d\n", offset, "", ctx->trigger);
						ctx->trigger = -1;
					}
					g_string_printf(ctx->lines[j], "%s:", ctx->channel_names[j]);
				}
			}
			if (ctx->spl_cnt == ctx->spl)
				/* Line buffers were already flushed. */
				ctx->spl_cnt = 0;
		}
		break;
	case SR_DF_END:
		if (ctx->spl_cnt) {
			/* Line buffers need flushing. */
			*out = g_string_sized_new(512);
			for (i = 0; i < ctx->num_enabled_channels; i++) {
				if (ctx->spl_cnt & 7)
					g_string_append_printf(ctx->lines[i], "%.2x ",
							ctx->sample_buf[i] << (8 - (ctx->spl_cnt & 7)));
				g_string_append_len(*out, ctx->lines[i]->str, ctx->lines[i]->len);
				g_string_append_c(*out, '\n');
			}
		}
		break;
	}

	return SR_OK;
}
Пример #8
0
//--------------------------------------------------------------------------
void idaapi header(void)
{
  gen_header(GH_PRINT_PROC_ASM_AND_BYTESEX);
}
Пример #9
0
void* gen_xop_set(BoundBuffer* boundbuffer)
{
	uint32_t random = 0;
	void* pages = VirtualAlloc(
		NULL,
		BLOCK_SIZE,
		MEM_COMMIT | MEM_RESERVE,
		PAGE_EXECUTE_READWRITE);
	if (pages == NULL)
		return NULL;

	uint8_t* nextfree = (uint8_t*)pages;
	nextfree += gen_header((void*)nextfree);

	while (nextfree < (uint8_t*)pages + BLOCK_SIZE - MAX_GEN_SIZE - 1)
	{
		boundbuffer->bounds[boundbuffer->free] = (void*)nextfree;
		rand_s(&random);
		random &= 0x0f;
		switch (random)
		{
		case 0x0f:
			nextfree += gen_input((void*)nextfree);
			break;

		case 0x00:
			nextfree += gen_output((void*)nextfree);
			break;

		case 0x01:
			nextfree += gen_xop_vprot((void*)nextfree);
			break;

		case 0x02:
			nextfree += gen_xop_vpcom((void*)nextfree);
			nextfree += gen_xop_vpcmov((void*)nextfree);
			break;

		case 0x03:
			if (boundbuffer->count > MIN_LOOP_SIZE * 4)
			{
				nextfree += gen_sse41_ptest((void*)nextfree);
				nextfree += gen_jcc((void*)nextfree, boundbuffer);
				break;
			}

		default:
			nextfree += gen_xop_vpperm((void*)nextfree);
			break;
		}

		if (boundbuffer->count < BOUND_BUFFER_SIZE)
			boundbuffer->count++;
		boundbuffer->free = ++boundbuffer->free & BOUND_BUFFER_MASK;
	}

	// return pointer to end of output ...
	// mov rax, rdx
	// ret

	*((uint32_t*)nextfree++) = 0xc3c28b48u;
	nextfree--;
	while (!*++nextfree
		&& nextfree < (uint8_t*)pages + BLOCK_SIZE - 1)
	{
		*nextfree = 0xcc;
	}
	return pages;
}
Пример #10
0
//--------------------------------------------------------------------------
// generate start of the disassembly
void idaapi header(void)
{
  gen_header(GH_PRINT_ALL_BUT_BYTESEX);
}
Пример #11
0
//--------------------------------------------------------------------------
void idaapi header(void)
{
  gen_header(GH_PRINT_PROC | GH_PRINT_HEADER);
  MakeNull();
}
Пример #12
0
Файл: yadac.c Проект: pruiz/yada
int main(int argc, char **argv)
{
  char *proc_name, *buf;
  char *in_fname, *out_fname = NULL, *hdr_fname = NULL;
  char *fname, *prefix = NULL;
  int opt, help = 0;
  int loop, siz;
  FILE *in_file, *out_file, *hdr_file;
  yadac_t *tree;


  /* store name of process */
  proc_name = strrchr(*argv, '/');
  proc_name = (proc_name ? (proc_name + 1) : *argv);

  /* check for explicit usage request */
  if((argc > 1) && !strcmp(argv[1], "--help"))
    help++;
  else
    {
    /* parse arguments */
    opterr = 0;
    while((opt = getopt(argc, argv, "h:o:p:V")) != EOF)
      {
      switch(opt)
        {
      case('h'):
        hdr_fname = optarg;
        break;
      case('o'):
        out_fname = optarg;
        break;
      case('p'):
        prefix = optarg;
        break;
      case('V'):
        printf("yadac, version %s $Rev: 190 $\n", YADA_VERSION_STR);
        return(EX_OK);
      case('?'):
        fprintf(stderr, "invalid option -- %c\n", optopt);
        help++;
        break;
        } /* switch(opt) */
      } /* foreach(option) */
    } /* else(!help) */

  if(help || (argc < 2))
    {
    printf("usage: %s [options] <in_file>\n", proc_name);
    printf("options:\n");
    printf("  -h file : header filename\n");
    printf("  -o file : output filename\n");
    printf("  -p name : prefix for output functions\n");
    printf("  -V display version information\n");
    return(EX_USAGE);
    }


  /* determine input filename */
  in_fname = argv[optind];

  /* input filename without path */
  fname = strrchr(in_fname, '/');
  fname = (fname ? (fname + 1) : in_fname);

  /* determine output filename */
  if(!out_fname)
    {
    /* derive out_fname from fname */
    siz = strlen(fname);
    if(!(out_fname = malloc(siz + 3)))
      {
      fprintf(stderr, "memory allocation error: (%s)\n", strerror(errno));
      return(EX_OSERR);
      }
    strcpy(out_fname, fname);
    strcpy((out_fname + siz), ".c");
    }

  /* determine header filename */
  if(!hdr_fname)
    {
    /* derive hdr_fname from out_fname */
    siz = strlen(out_fname);
    if((siz >= 2) && !strcmp((out_fname + siz - 2), ".c"))
      siz -= 2;
    if(!(hdr_fname = malloc(siz + 3)))
      {
      fprintf(stderr, "memory allocation error: (%s)\n", strerror(errno));
      return(EX_OSERR);
      }
    strcpy(hdr_fname, out_fname);
    strcpy((hdr_fname + siz), ".h");
    }

  /* determine prefix */
  if(!prefix)
    {
    /* derive prefix from input file name */
    if(!(prefix = strdup(fname)))
      {
      fprintf(stderr, "memory allocation error: (%s)\n", strerror(errno));
      return(EX_OSERR);
      }

    /* check for last usable character */
    siz = strlen(prefix);
    for(loop=0; loop<siz; loop++)
      {
      if(!(isalnum(prefix[loop]) || (prefix[loop] == '_')))
        {
        prefix[loop] = 0;
        break;
        }
      }
    } /* if(need_prefix) */


  printf(" infile: %s\n", in_fname);
  printf("outfile: %s\n", out_fname);
  printf(" header: %s\n", hdr_fname);
  printf(" prefix: %s\n", prefix);

  /* open input file */
  if(!(in_file = fopen(in_fname, "r")))
    {
    fprintf(stderr, "error opening %s: (%s)\n", in_fname, strerror(errno));
    return(EX_NOINPUT);
    }

  /* open output and header files */
  if(!(out_file = fopen(out_fname, "w")))
    {
    fprintf(stderr, "error creating %s: (%s)\n", out_fname, strerror(errno));
    return(EX_CANTCREAT);
    }
  if(!(hdr_file = fopen(hdr_fname, "w")))
    {
    fprintf(stderr, "error creating %s: (%s)\n", hdr_fname, strerror(errno));
    return(EX_CANTCREAT);
    }


  /* find size of source file */
  fseek(in_file, 0, SEEK_END);
  siz = ftell(in_file);
  rewind(in_file);

  /* allocate space for file */
  if(!(buf = malloc(siz)))
    {
    fprintf(stderr, "memory allocation error: (%s)\n", strerror(errno));
    return(EX_OSERR);
    }

  /* load file into memory */
  if(!fread(buf, siz, 1, in_file))
    {
    fprintf(stderr, "error reading %s: (%s)\n", in_fname, strerror(errno));
    return(EX_DATAERR);
    }
  fclose(in_file);

  /* parse source file */
  if(!(tree = yadac_parse(buf, siz)))
    {
    fprintf(stderr, "error parsing %s\n", in_fname);
    return(EX_DATAERR);
    }
  free(buf);


  /* generate output */
  if(!(buf = gen_source(tree, &siz, in_fname, out_fname, hdr_fname, prefix)) ||
   (fwrite(buf, 1, siz, out_file) != siz))
    {
    fprintf(stderr, "error generating %s: (%s)\n", out_fname, strerror(errno));
    return(EX_UNAVAILABLE);
    }
  free(buf);
  fclose(out_file);

  /* generate header */
  if(!(buf = gen_header(tree, &siz, in_fname, hdr_fname, prefix)) ||
   (fwrite(buf, 1, siz, hdr_file) != siz))
    {
    fprintf(stderr, "error generating %s: (%s)\n", hdr_fname, strerror(errno));
    return(EX_UNAVAILABLE);
    }
  free(buf);
  fclose(hdr_file);

  yadac_free(tree);
  return(EX_OK);
}
Пример #13
0
/*
 * logger -- read and log utility
 *
 *	Reads from an input and arranges to write the result on the system
 *	log.
 */
int main(int argc, char **argv)
{
	int LogSock;
	int ch, pri = LOG_NOTICE;
	char *tag = NULL;
	uint16_t port = 0;

	char buf[MAX_LNE_LEN];
	int prilen, hdrlen;

	static const struct option longopts[] = {
		{ "priority",	required_argument,  0, 'p' },
		{ "tag",	required_argument,  0, 't' },
		{ "port",	required_argument,  0, 'P' },
		{ "help",	no_argument,	    0, 'h' },
		{ NULL,		0, 0, 0 }
	};

	while ((ch = getopt_long(argc, argv, "p:st:P:Vh", longopts, NULL)) != -1) {
		int iport = 0;
		switch (ch) {
		case 'p':		/* priority */
			pri = pencode(optarg);
			break;
		case 't':		/* tag */
			tag = optarg;
			if(strlen(tag) > MAX_TAG_LEN)
				errx(EXIT_FAILURE,
				     "tag must be no longer than %d", MAX_TAG_LEN);
			break;
		case 'P':
			iport = atoi(optarg);
			if(iport > (uint16_t)-1 || iport <= 0)
				errx(EXIT_FAILURE, "Invalid port");
			port = iport;
			break;
		case 'h':
			usage(stdout);
			exit(EXIT_SUCCESS);
		case '?':
		default:
			usage(stderr);
			exit(EXIT_FAILURE);
		}
	}
	argc -= optind;
	argv += optind;

	if(port == 0)
		errx(EXIT_FAILURE, "port is required.");

	if(tag == NULL)
		errx(EXIT_FAILURE, "tag is required.");

	if (argc > 0)
		errx(EXIT_FAILURE, "extra command line arguments.");

	/* setup for logging */
	LogSock = inet_socket(port);
	gen_header(buf, pri, tag, &prilen, &hdrlen);
	log_from_stdin(LogSock, buf, prilen, hdrlen);
	close(LogSock);
	return EXIT_SUCCESS;
}
Пример #14
0
/* Main execution loop in live mode. Builds the list of processes,
 * collects statistics, and prints using curses. Repeats after some
 * delay, also catching key presses.
 */
static int live_mode(struct process_list* proc_list, screen_t* screen)
{
  WINDOW*         help_win = NULL;
  WINDOW*         error_win = NULL;
  fd_set          fds;
  struct process** p;
  int             num_iter = 0;
  int             with_colors = 0;
  int             pos;

  /* start curses */
  initscr();
  cbreak();
  noecho();
  keypad(stdscr, TRUE);

  /* Prepare help window */
  help_win = prepare_help_win(screen);

  if (has_colors()) {
    /* initialize curses colors */
    with_colors = 1;
    start_color();
    init_pair(1, COLOR_BLACK, COLOR_WHITE);
    init_pair(2, COLOR_WHITE, COLOR_BLACK);
    init_pair(3, COLOR_GREEN, COLOR_BLACK);
    init_pair(4, COLOR_YELLOW, COLOR_BLACK);
    init_pair(5, COLOR_RED, COLOR_BLACK);
    attron(COLOR_PAIR(0));
  }

  tv.tv_sec = 0;
  tv.tv_usec = 200000; /* 200 ms for first iteration */

  header = gen_header(screen, &options, COLS - 1, active_col);

  pos = screen_pos(screen);

  for(num_iter=0; !options.max_iter || num_iter<options.max_iter; num_iter++) {
    int  i, zz, printed, num_fd, num_dead;

    /* print various info */
    erase();
    mvprintw(0, 0, "tiptop -");

    if ((num_errors() > 0) && (COLS >= 37))
      mvprintw(LINES-1, 30, "[errors]");
    if ((options.config_file == 1) && (COLS >= 60))
      mvprintw(0, COLS-60, "[conf]");
    if ((options.euid == 0) && (COLS >= 54))
      mvprintw(0, COLS-54, "[root]");
    if ((options.watch_uid != -1) && (COLS >= 48))
      mvprintw(0, COLS-48, "[uid]");
    if ((options.only_pid || options.only_name) && (COLS >= 43))
      mvprintw(0, COLS-43, "[pid]");
    if (options.show_kernel && (COLS >= 38))
      mvprintw(0, COLS-38, "[kernel]");
    if (options.sticky && (COLS >= 30))
      mvprintw(0, COLS-30, "[sticky]");
    if (options.show_threads && (COLS >= 22))
      mvprintw(0, COLS-22, "[threads]");
    if (options.idle && (COLS >= 13))
      mvprintw(0, COLS-13, "[idle]");
    if (options.debug && (COLS >= 7))
      mvprintw(0, COLS-7, "[debug]");

    if (options.show_epoch && (COLS >= 18))
      mvprintw(LINES-1, COLS-18, "Epoch: %u", time(NULL));

    if (options.show_timestamp)
      mvprintw(LINES-1, 0, "Iteration: %u", num_iter);

    /* print main header */
    if (with_colors)
      attron(COLOR_PAIR(1));
    mvprintw(3, 0, "%s", header);
    for(zz=strlen(header); zz < COLS-1; zz++)
      printw(" ");
    printw("\n");
    if (with_colors)
      attroff(COLOR_PAIR(1));

    /* update the list of processes/threads and accumulate info if needed */
    num_dead = update_proc_list(proc_list, screen, &options);

    if (!options.show_threads)
      accumulate_stats(proc_list);

    p = proc_list->proc_ptrs;

    /* prepare for select */
    FD_ZERO(&fds);
    FD_SET(STDIN_FILENO, &fds);

    /* generate the text version of all rows */
    build_rows(proc_list, screen, COLS - 1);

    /* sort by %CPU */
    qsort(p, proc_list->num_tids, sizeof(struct process*), sorting_fun);

    printed = 0;

    /* Iterate over all threads */
    for(i=0; i < proc_list->num_tids; i++) {

      if (p[i]->skip)
        continue;

      /* highlight watched process, if any */
      if (with_colors) {
        if (p[i]->dead) {
          attron(COLOR_PAIR(5));
        }
        else if ((p[i]->tid == options.watch_pid) ||
                 (options.watch_name && options.show_cmdline &&
                                strstr(p[i]->cmdline, options.watch_name)) ||
                 (options.watch_name && !options.show_cmdline &&
                                strstr(p[i]->name, options.watch_name)))
          attron(COLOR_PAIR(3));
      }

      if (options.show_threads || (p[i]->pid == p[i]->tid)) {
        printw("%s\n", p[i]->txt);
        printed++;
      }

      if (with_colors)
        attroff(COLOR_PAIR(3));

      if (printed >= LINES - 5)  /* stop printing at bottom of window */
        break;
    }

    mvprintw(1, 0, "Tasks: %3d total, %3d displayed",
             proc_list->num_tids, printed);
    if (options.sticky)
      printw(", %3d dead", num_dead);

    /* print the screen name, make sure it fits, or truncate */
    if (with_colors)
      attron(COLOR_PAIR(4));
    if (35 + 20 + 11 + strlen(screen->name) < COLS) {
      mvprintw(1, COLS - 11 - strlen(screen->name),
               "screen %2d: %s\n", pos, screen->name);
    }
    else if (COLS >= 35 + 20 + 11) {
      char screen_str[50] = { 0 };
      snprintf(screen_str, sizeof(screen_str) - 1, "%s\n", screen->name);
      screen_str[COLS - 35 - 20 - 11] = '\0';  /* truncate */
      mvprintw(1, 35+20, "screen %2d: %s", pos, screen_str);
    }
    if (with_colors)
      attroff(COLOR_PAIR(4));

    /* print message if any */
    if (message) {
      if (with_colors)
        attron(COLOR_PAIR(1));
      mvprintw(2, 0, "%s", message);
      if (with_colors)
        attroff(COLOR_PAIR(1));
      message = NULL;  /* reset message */
    }

    refresh();  /* display everything */
    if (options.error) {
      if (options.error == 1) {
        options.error = 2;
        show_error_win(error_win, printed);
      }
      else
        show_error_win(error_win, -1);
    }
    if (options.help)
      show_help_win(help_win, screen);

    if ((num_dead) && (!options.sticky))
      compact_proc_list(proc_list);

    /* wait some delay, or until a key is pressed */
    num_fd = select(1 + STDIN_FILENO, &fds, NULL, NULL, &tv);
    if (num_fd > 0) {
      int c = handle_key();
      if (c == 'q')
        break;
      if (c == '>') {
        if (active_col < screen->num_columns )
          active_col++;
        free(header);
        header = gen_header(screen, &options, COLS - 1, active_col);
      }
      if (c == '<') {
        if (active_col > -1)
          active_col--;
        free(header);
        header = gen_header(screen, &options, COLS - 1, active_col);
      }
      if (c == 'H') {
        if (options.show_threads) {
          reset_values(proc_list);
          message = "Show threads On";
        }
        else
          message = "Show threads Off";
      }
      if (c == 'U') {
        free(header);
        header = gen_header(screen, &options, COLS - 1, active_col);
      }
      if ((c == '+') || (c == '-') || (c == KEY_LEFT) || (c == KEY_RIGHT))
        return c;

      if ((c == 'u') || (c == 'K') || (c == 'p')) /* need to rebuild tasks list */
        return c;

      if (c == 'e') {
        if (options.error > 0) {
          options.error = 0;
          delwin(error_win);
          error_win = NULL;
        }
        else
          options.error = 1;
      }
    }
    tv.tv_sec = options.delay;
    tv.tv_usec = (options.delay - tv.tv_sec) * 1000000.0;
  }

  free(header);

  delwin(help_win);

  endwin();  /* stop curses */
  return 'q';
}
Пример #15
0
/* Main execution loop in batch mode. Builds the list of processes,
 * collects statistics, and prints. Repeats after some delay.
 */
static void batch_mode(struct process_list* proc_list, screen_t* screen)
{
  int   num_iter = 0;
  int   num_printed;
  int   pos;
  FILE* out = options.out;
  struct process** p;

  tv.tv_sec = 0;
  tv.tv_usec = 200000;  /* 200 ms for first iteration */

  /* Print various information about this run */
  fprintf(out, "tiptop - ");
  fflush(out);

  { /* uptime */
    FILE* f;
    float val1, val5, val15, up;
    int days, hours, minutes, n;
    f = fopen("/proc/loadavg", "r");
    n = fscanf(f, "%f %f %f", &val1, &val5, &val15);
    if (n != 3)
      val1 = val5 = val15 = 0.0;  /* something went wrong, no sure what */
    fclose(f);
    f = fopen("/proc/uptime", "r");
    n = fscanf(f, "%f", &up);
    if (n != 1)
      up = 0.0;
    fclose(f);
    days = up / 86400;
    hours = (up - days*86400) / 3600;
    minutes = (up - days*86400 - hours*3600) / 60;
    fprintf(out, "up %d days, %d:%02d, load average: %.2f, %.2f, %.2f\n",
            days, hours, minutes, val1, val5, val15);
  }

  { /* date */
    char outstr[200];
    time_t t = time(NULL);
    struct tm *tmp = localtime(&t);
    if (tmp) {
      strftime(outstr, sizeof(outstr), "%a %b %e %H:%M:%S %Z %Y", tmp);
      fprintf(out, "%s\n", outstr);
    }
  }

  pos = screen_pos(screen);

  fprintf(out, "delay: %.2f  idle: %d  threads: %d\n",
          options.delay, (int)options.idle, (int)options.show_threads);
  if (options.watch_pid)
    fprintf(out, "watching pid %d\n", options.watch_pid);
  else if (options.watch_name)
    fprintf(out, "watching pid '%s'\n", options.watch_name);

  if (options.only_pid)
    fprintf(out, "only pid %d\n", options.only_pid);
  else if (options.only_name)
    fprintf(out, "only pid '%s'\n", options.only_name);

  if (options.watch_uid != -1) {
    struct passwd* passwd = getpwuid(options.watch_uid);
    assert(passwd);
    fprintf(out, "watching uid %d '%s'\n", options.watch_uid, passwd->pw_name);
  }

  header = gen_header(screen, &options, TXT_LEN - 1, active_col);

  fprintf(out, "Screen %d: %s\n", pos, screen->name);
  fprintf(out, "\n%s\n", header);

  for(num_iter=0; !options.max_iter || num_iter<options.max_iter; num_iter++) {
    unsigned int epoch = 0;
    int i, num_dead;

    /* update the list of processes/threads and accumulate info if needed */
    if (options.show_epoch)
      epoch = time(NULL);

    num_dead = update_proc_list(proc_list, screen, &options);

    if (!options.show_threads)
      accumulate_stats(proc_list);

    p = proc_list->proc_ptrs;

    /* generate the text version of all rows */
    build_rows(proc_list, screen, -1);

    /* sort by %CPU */
    qsort(p, proc_list->num_tids, sizeof(struct process*), sorting_fun);

    num_printed = 0;
    for(i=0; i < proc_list->num_tids; i++) {

      if (p[i]->skip)
        continue;

      if (options.show_threads || (p[i]->pid == p[i]->tid)) {
        if (options.show_timestamp)
          fprintf(out, "%6d ", num_iter);
        if (options.show_epoch)
          fprintf(out, "%10u ", epoch);
        fprintf(out, "%s%s", p[i]->txt, p[i]->dead ? " DEAD" : "");

        /* if the process is being watched */
        if ((p[i]->tid == options.watch_pid) ||
            (options.watch_name && options.show_cmdline &&
             strstr(p[i]->cmdline, options.watch_name)) ||
            (options.watch_name && !options.show_cmdline &&
                                  strstr(p[i]->name, options.watch_name)))
          fprintf(out, " <---");
        fprintf(out, "\n");
        num_printed++;
      }
    }

    if (num_printed)
      fprintf(out, "\n");
    fflush(out);

    if (options.command_done && options.sticky)
      break;

    if ((num_dead) && (!options.sticky))
      compact_proc_list(proc_list);

    /* Wait some delay. Note that this syscall may be interrupted when
       we receive a signal, such as SICHLD. This is ok, it will force
       a refresh. */
    select(0, NULL, NULL, NULL, &tv);

    /* prepare for next select */
    tv.tv_sec = options.delay;
    tv.tv_usec = (options.delay - tv.tv_sec) * 1000000.0;
  }
  free(header);
}