/*
 * Display a gauge, or progress meter.  Starts at percent% and reads stdin.  If
 * stdin is not XXX, then it is interpreted as a percentage, and the display is
 * updated accordingly.  Otherwise the next line is the percentage, and
 * subsequent lines up to another XXX are used for the new prompt.  Note that
 * the size of the window never changes, so the prompt can not get any larger
 * than the height and width specified.
 */
int
dialog_gauge(const char *title,
	     const char *prompt,
	     int height,
	     int width,
	     int percent)
{
    int i, x, y;
    char buf[MY_LEN];
    char prompt_buf[MY_LEN];
    WINDOW *dialog;

    auto_size(title, prompt, &height, &width, MIN_HIGH, MIN_WIDE);
    print_size(height, width);
    ctl_size(height, width);

    /* center dialog box on screen */
    x = box_x_ordinate(width);
    y = box_y_ordinate(height);

    dialog = new_window(height, width, y, x);

    curs_set(0);
    do {
	(void) werase(dialog);
	draw_box(dialog, 0, 0, height, width, dialog_attr, border_attr);

	draw_title(dialog, title);

	wattrset(dialog, dialog_attr);
	print_autowrap(dialog, prompt, height, width - (2 * MARGIN));

	draw_box(dialog,
		 height - 4, 2 + MARGIN,
		 2 + MARGIN, width - 2 * (2 + MARGIN),
		 dialog_attr,
		 border_attr);

	(void) wmove(dialog, height - 3, 4);
	wattrset(dialog, title_attr);

	for (i = 0; i < (width - 2 * (3 + MARGIN)); i++)
	    (void) waddch(dialog, ' ');

	wattrset(dialog, title_attr);
	(void) wmove(dialog, height - 3, (width / 2) - 2);
	(void) wprintw(dialog, "%3d%%", percent);

	x = (percent * (width - 2 * (3 + MARGIN))) / 100;
	wattrset(dialog, A_REVERSE);
	(void) wmove(dialog, height - 3, 4);
	for (i = 0; i < x; i++)
	    (void) waddch(dialog, winch(dialog));

	(void) wrefresh(dialog);

	if (read_data(buf, pipe_fp) == 0)
	    break;
	if (isMarker(buf)) {
	    /*
	     * Historically, next line should be percentage, but one of the
	     * worse-written clones of 'dialog' assumes the number is missing.
	     * (Gresham's Law applied to software).
	     */
	    if (read_data(buf, pipe_fp) == 0)
		break;
	    prompt_buf[0] = '\0';
	    if (decode_percent(buf))
		percent = atoi(buf);
	    else
		strcpy(prompt_buf, buf);

	    /* Rest is message text */
	    while (read_data(buf, pipe_fp) != 0
		   && !isMarker(buf)) {
		if (strlen(prompt_buf) + strlen(buf) < sizeof(prompt_buf) - 1) {
		    strcat(prompt_buf, buf);
		}
	    }
	    prompt = prompt_buf;
	} else if (decode_percent(buf)) {
	    percent = atoi(buf);
	}
    } while (1);

    curs_set(1);
    del_window(dialog);
    return (DLG_EXIT_OK);
}
示例#2
0
UINT8 wd11c00_17_device::dack_r()
{
	return read_data();
}
示例#3
0
static int read_nist_nls_data (const char *fname)
{
    FILE *fp;
    char line[128];
    int err = 0;
    int got_name = 0;
    int got_model = 0;
    int got_data = -1;

    fp = fopen(fname, "r");
    if (fp == NULL) {
	fprintf(stderr, "Couldn't open %s\n", fname);
	return 1;
    }

    tester_init();

    while (fgets(line, sizeof line, fp) && !err) {
	tail_strip(line);
	if (strstr(line, "Dataset Name:")) {
	    err = get_id(line + 13);
	    if (!err) got_name = 1;
	} else if (strstr(line, "Number of Observations:")) {
	    if (sscanf(line + 24, "%d", &tester.nobs) != 1) {
		err = 1;
	    } else {
		if (tester.nobs > 0) {
		    datainfo = create_new_dataset(&Z, tester.nvars + 1, 
						  tester.nobs, 0);
		    if (datainfo == NULL) err = 1;
		} else {
		    err = 1;
		}
	    }
	} else if (strncmp(line, "Model:", 6) == 0) {
	    err = read_model_lines(line, fp);
	    if (!err) got_model = 1;
	} else if (strstr(line, "Starting") && strstr(line, "Certified")) {
	    err = read_params(fp);
	} else if (strncmp(line, "Data:", 5) == 0) {
	    if (got_data < 0) {
		got_data = 0;
	    } else {
		err = read_data(fp);
		if (!err) got_data = 1;
	    }
	} else if (strstr(line, "Predictor")) {
	    err = get_nvars(line);
	} else if (strstr(line, "evel of Diffic")) {
	    print_grade(line);
	}
    }

    if (!got_name) {
	missing("dataset identifier");
    }
    if (!got_model) {
	missing("model specification");
    }
    if (tester.nparam == 0) {
	missing("parameter values");
    }

    if (got_data <= 0) {
	missing("input data");
    } else if (tester.nobs == 0) {
	missing("number of observations");
    }

    fclose(fp);

    return err;
}
示例#4
0
static void process_select(fd_set *rfds, fd_set *wfds, fd_set *efds)
{
	const struct list_node *node = fg_list_front(&flows);
	while (node) {
		struct flow *flow = node->data;
		node = node->next;

		DEBUG_MSG(LOG_DEBUG, "processing pselect() for flow %d",
			  flow->id);

		if (flow->listenfd_data != -1 &&
		    FD_ISSET(flow->listenfd_data, rfds)) {
			DEBUG_MSG(LOG_DEBUG, "ready for accept");
			if (flow->state == GRIND_WAIT_ACCEPT) {
				if (accept_data(flow) == -1) {
					DEBUG_MSG(LOG_ERR, "accept_data() "
						  "failed");
					goto remove;
				}
			}
		}

		if (flow->fd != -1) {
			if (FD_ISSET(flow->fd, efds)) {
				int error_number, rc;
				socklen_t error_number_size =
					sizeof(error_number);
				DEBUG_MSG(LOG_DEBUG, "sock of flow %d in efds",
					  flow->id);
				rc = getsockopt(flow->fd, SOL_SOCKET,
						SO_ERROR,
						(void *)&error_number,
						&error_number_size);
				if (rc == -1) {
					warn("failed to get errno for"
					     "non-blocking connect");
					goto remove;
				}
				if (error_number != 0) {
					warnc(error_number, "connect");
					goto remove;
				}
			}
			if (FD_ISSET(flow->fd, wfds))
				if (write_data(flow) == -1) {
					DEBUG_MSG(LOG_ERR, "write_data() failed");
					goto remove;
				}

			if (FD_ISSET(flow->fd, rfds))
				if (read_data(flow) == -1) {
					DEBUG_MSG(LOG_ERR, "read_data() failed");
					goto remove;
				}
		}
		continue;
remove:
		if (flow->fd != -1) {
			flow->statistics[FINAL].has_tcp_info =
				get_tcp_info(flow,
					     &flow->statistics[FINAL].tcp_info)
					? 0 : 1;
		}
		flow->pmtu = get_pmtu(flow->fd);
		report_flow(flow, FINAL);
		uninit_flow(flow);
		DEBUG_MSG(LOG_ERR, "removing flow %d", flow->id);
		remove_flow(flow);
	}
}
示例#5
0
/* record network stream as per spec in opt
 */
static int
record()
{
    int rsock = -1, destfd = -1, rc = 0, wtime_sec = 0;
    struct ip_mreq mreq;
    struct timeval rtv;
    struct dstream_ctx ds;
    ssize_t nmsgs = 0;
    ssize_t nrcv = -1, lrcv = -1, t_delta = 0;
    uint64_t n_total = 0;
    ssize_t nwr = -1, lwr = -1;
    sig_atomic_t quit = 0;
    struct rdata_opt ropt;
    int oflags = 0;

    char* data = NULL;

    static const u_short RSOCK_TIMEOUT  = 5;
    extern const char CMD_UDP[];

    /* NOPs to eliminate warnings in lean version */
    (void)&t_delta; (void)&lrcv;
    t_delta = lrcv = lwr = 0; quit=0;

    check_fragments( NULL, 0, 0, 0, 0, g_flog );

    /* init */
    do {
        data = malloc( g_recopt.bufsize );
        if( NULL == data ) {
            mperror(g_flog, errno, "%s: cannot allocate [%ld] bytes",
                    __func__, (long)g_recopt.bufsize );
            return ERR_INTERNAL;
        }

        rc = subscribe( &rsock, &mreq );
        if( 0 != rc ) break;

        rtv.tv_sec = RSOCK_TIMEOUT;
        rtv.tv_usec = 0;

        rc = setsockopt( rsock, SOL_SOCKET, SO_RCVTIMEO, &rtv, sizeof(rtv) );
        if( -1 == rc ) {
            mperror(g_flog, errno, "%s: setsockopt - SO_RCVTIMEO",
                    __func__);
            rc = ERR_INTERNAL;
            break;
        }

        oflags = O_CREAT | O_TRUNC | O_WRONLY |
                 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
        # if defined(O_LARGEFILE)
            /* O_LARGEFILE is not defined under FreeBSD ??-7.1 */
            oflags |= O_LARGEFILE;
        # endif
        destfd = open( g_recopt.dstfile, oflags,
                (mode_t)(S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
        if( -1 == destfd ) {
            mperror( g_flog, errno, "%s: cannot create destination file [%s]",
                     __func__, g_recopt.dstfile );
            rc = ERR_INTERNAL;
            break;
        }

        rc = calc_buf_settings( &nmsgs, NULL );
        if (0 != rc) break;

        if( nmsgs < (ssize_t)1 ) {
            (void) tmfprintf( g_flog, "Buffer for inbound data is too small [%ld] bytes; "
                    "the minimum size is [%ld] bytes\n",
                    (long)g_recopt.bufsize, (long)ETHERNET_MTU );
            rc = ERR_PARAM;
            break;
        }

        TRACE( (void)tmfprintf( g_flog, "Inbound buffer set to "
                        "[%d] messages\n", nmsgs ) );

        rc = init_dstream_ctx( &ds, CMD_UDP, NULL, nmsgs );
        if( 0 != rc ) {
		free( data );
		return -1;
	}

        (void) set_nice( g_recopt.nice_incr, g_flog );

        /* set up alarm to break main loop */
        if( 0 != g_recopt.end_time ) {
            wtime_sec = (int)difftime( g_recopt.end_time, time(NULL) );
            assert( wtime_sec >= 0 );

            (void) alarm( wtime_sec );

            (void)tmfprintf( g_flog, "Recording will end in [%d] seconds\n",
                    wtime_sec );
        }
    } while(0);

    /* record loop */
    ropt.max_frgs = g_recopt.rbuf_msgs;
    ropt.buf_tmout = -1;

    for( n_total = 0; (0 == rc) && !(quit = must_quit()); ) {
        nrcv = read_data( &ds, rsock, data, g_recopt.bufsize, &ropt );
        if( -1 == nrcv ) { rc = ERR_INTERNAL; break; }

        if( 0 == n_total ) {
            (void) tmfprintf( g_flog, "Recording to file=[%s] started.\n",
                    g_recopt.dstfile );
        }

        TRACE( check_fragments( "received new", g_recopt.bufsize,
                    lrcv, nrcv, t_delta, g_flog ) );
        lrcv = nrcv;

        if( nrcv > 0 ) {
            if( g_recopt.max_fsize &&
                ((int64_t)(n_total + nrcv) >= g_recopt.max_fsize) ) {
                break;
            }

            nwr = write_data( &ds, data, nrcv, destfd );
            if( -1 == nwr ) { rc = ERR_INTERNAL; break; }

            n_total += (size_t)nwr;
            /*
            TRACE( tmfprintf( g_flog, "Wrote [%ld] to file, total=[%ld]\n",
                        (long)nwr, (long)n_total ) );
            */

            TRACE( check_fragments( "wrote to file",
                    nrcv, lwr, nwr, t_delta, g_flog ) );
            lwr = nwr;
        }

        if( ds.flags & F_SCATTERED ) reset_pkt_registry( &ds );

    } /* record loop */

    (void) tmfprintf( g_flog, "Recording to file=[%s] stopped at filesize=[%lu] bytes\n",
                      g_recopt.dstfile, (u_long)n_total );

    /* CLEANUP
     */
    (void) alarm(0);

    TRACE( (void)tmfprintf( g_flog, "Exited record loop: wrote [%lu] bytes to file [%s], "
                    "rc=[%d], alarm=[%ld], quit=[%ld]\n",
                    (u_long)n_total, g_recopt.dstfile, rc, g_alarm, (long)quit ) );

    free_dstream_ctx( &ds );
    free( data );

    close_mcast_listener( rsock, &mreq );
    if( destfd >= 0 ) (void) close( destfd );

    if( quit )
        TRACE( (void)tmfprintf( g_flog, "%s process must quit\n",
                        g_udpxrec_app ) );

    return rc;
}
示例#6
0
static void clear_obf(struct si_sm_data *kcs, unsigned char status)
{
	if (GET_STATUS_OBF(status))
		read_data(kcs);
}
示例#7
0
int main(){ 
    read_data();
    buylow();
    output_data();
    return 0;
    } 
示例#8
0
int main(int argc, char **argv)
{
	unsigned char buf[BUF_SIZE];
	int fd, fd_s;
	pid_t extpid;
	uint32_t crc;
	int pfd[2];
	int val;
	socklen_t optlen;

	if (pipe(pfd)) {
		pr_perror("pipe() failed");
		return 1;
	}

	extpid = fork();
	if (extpid < 0) {
		pr_perror("fork() failed");
		return 1;
	} else if (extpid == 0) {
		test_ext_init(argc, argv);

		close(pfd[1]);
		if (read(pfd[0], &port, sizeof(port)) != sizeof(port)) {
			pr_perror("Can't read port");
			return 1;
		}

		fd = tcp_init_client(ZDTM_FAMILY, "localhost", port);
		if (fd < 0)
			return 1;

#ifdef STREAM
		while (1) {
			if (read_data(fd, buf, BUF_SIZE)) {
				pr_perror("read less then have to");
				return 1;
			}
			if (datachk(buf, BUF_SIZE, &crc))
				return 2;

			datagen(buf, BUF_SIZE, &crc);
			if (write_data(fd, buf, BUF_SIZE)) {
				pr_perror("can't write");
				return 1;
			}
		}
#else
		if (read_data(fd, buf, BUF_SIZE)) {
			pr_perror("read less then have to");
			return 1;
		}
		if (datachk(buf, BUF_SIZE, &crc))
			return 2;

		datagen(buf, BUF_SIZE, &crc);
		if (write_data(fd, buf, BUF_SIZE)) {
			pr_perror("can't write");
			return 1;
		}
#endif
		return 0;
	}

	test_init(argc, argv);

	if ((fd_s = tcp_init_server(ZDTM_FAMILY, &port)) < 0) {
		pr_perror("initializing server failed");
		return 1;
	}

	close(pfd[0]);
	if (write(pfd[1], &port, sizeof(port)) != sizeof(port)) {
		pr_perror("Can't send port");
		return 1;
	}
	close(pfd[1]);

	/*
	 * parent is server of TCP connection
	 */
	fd = tcp_accept_server(fd_s);
	if (fd < 0) {
		pr_perror("can't accept client connection %m");
		return 1;
	}

	val = 1;
	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val))) {
		pr_perror("setsockopt");
		return 1;
	}

	test_daemon();
#ifdef STREAM
	while (test_go()) {
		datagen(buf, BUF_SIZE, &crc);
		if (write_data(fd, buf, BUF_SIZE)) {
			pr_perror("can't write");
			return 1;
		}

		if (read_data(fd, buf, BUF_SIZE)) {
			pr_perror("read less then have to");
			return 1;
		}
		if (datachk(buf, BUF_SIZE, &crc))
			return 2;
	}
	kill(extpid, SIGKILL);
#else
	test_waitsig();

	datagen(buf, BUF_SIZE, &crc);
	if (write_data(fd, buf, BUF_SIZE)) {
		pr_perror("can't write");
		return 1;
	}

	if (read_data(fd, buf, BUF_SIZE)) {
		pr_perror("read less then have to");
		return 1;
	}
	if (datachk(buf, BUF_SIZE, &crc))
		return 2;
#endif
	optlen = sizeof(val);
	if (getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, &optlen)) {
		pr_perror("getsockopt");
		return 1;
	}
	if (val != 1) {
		fail("SO_REUSEADDR are not set for %d\n", fd);
		return 1;
	}

	pass();
	return 0;
}
示例#9
0
文件: mbr.c 项目: andrewgaul/fatback
/*
 * Actually read the partition table elements into their
 * appropriate structure.  byte order conversion handeling included
 */
static int read_ptable(off_t offset, struct ptable_entry *table)
{
     int i;
     sig_t signature;
     u_int8_t *index, *buffer;
     fbvar_t *sectsize_var;
     unsigned sectsize;
     enum { PTABLE_OFFSET      = 446,
            BOOT_INDICATOR_OFF = 0,
            START_HEAD_OFF     = 1,
            START_SECT_OFF     = 2,
            START_CYL_OFF      = 3,
            SYS_INDICATOR_OFF  = 4,
            END_HEAD_OFF       = 5,
            END_SECT_OFF       = 6,
            END_CYL_OFF        = 7,
            SECTOR_OFFSET_OFF  = 8,
            TOTAL_SECTORS_OFF  = 12,
            CYL_MASK           = 0xC0,
            SECT_MASK          = ~CYL_MASK,
            PTABLE_SIZE        = 16
     };

     if (!table)
          return 0;

     /* get the sector size from the fatback global variable table */
     sectsize_var = get_fbvar("sectsize");
     if (!sectsize_var->val.ival) {
          display(NORMAL, "Error: sectsize set to 0!\n");
          free(sectsize_var);
          return 0;
     }
     sectsize = sectsize_var->val.ival;
     free(sectsize_var);

     buffer = emalloc(sectsize);
     if (!read_data(buffer, offset, sectsize)) {
          return 0;
     }
     index = buffer + PTABLE_OFFSET;

     /* Load partition table elements into their apropriate struct.  This may
      * seem a little cumbersome, but it is the easiest way to do it PORTABLY
      */
     for (i = 0; i < NUM_PTABLE_ENTRIES; i++) {
          index += !!i * PTABLE_SIZE;
          table[i].boot_indicator = little_endian_8(index +BOOT_INDICATOR_OFF);
          table[i].start_head = little_endian_8(index + START_HEAD_OFF);
          table[i].start_cyl = little_endian_8(index + START_CYL_OFF);
          table[i].start_cyl += (index[START_SECT_OFF] & CYL_MASK) << 2;
          table[i].start_sect = index[START_SECT_OFF] & SECT_MASK;
          table[i].sys_indicator = little_endian_8(index + SYS_INDICATOR_OFF);
          table[i].end_head = little_endian_8(index + END_HEAD_OFF);
          table[i].end_cyl = little_endian_8(index + END_CYL_OFF);
          table[i].end_cyl += (index[END_SECT_OFF] & CYL_MASK) << 2;
          table[i].end_sect = index[END_SECT_OFF] & SECT_MASK;
          table[i].offset = little_endian_32(index + SECTOR_OFFSET_OFF);
          table[i].sectors = little_endian_32(index + TOTAL_SECTORS_OFF);
     }

     signature = read_sig(&buffer[sectsize - 2]);
     free(buffer);
     return scheck_ptable(table, signature);
}
示例#10
0
std::string MROMInstaller::open(const std::string& file)
{
	char* manifest = NULL;
	const ZipEntry *script_entry;
	ZipArchive zip;

	MemMapping map;
	if (sysMapFile(file.c_str(), &map) != 0) {
		LOGERR("Failed to sysMapFile '%s'\n", file.c_str());
		return false;
	}

	if (mzOpenZipArchive(map.addr, map.length, &zip) != 0)
		return "Failed to open installer file!";

	script_entry = mzFindZipEntry(&zip, "manifest.txt");
	if(!script_entry)
	{
		mzCloseZipArchive(&zip);
		sysReleaseMap(&map);
		return "Failed to find manifest.txt";
	}

	int res = read_data(&zip, script_entry, &manifest, NULL);

	mzCloseZipArchive(&zip);
	sysReleaseMap(&map);

	if(res < 0)
		return "Failed to read manifest.txt!";

	int line_cnt = 1;
	for(char *line = strtok(manifest, "\r\n"); line; line = strtok(NULL, "\r\n"), ++line_cnt)
	{
		if(line[0] == '#')
			continue;

		char *val = strchr(line, '=');
		if(!val)
			continue;

		std::string key = std::string(line, val-line);
		++val; // skip '=' char

		char *start = strchr(val, '"');
		char *end = strrchr(val, '"');

		if(!start || start == end || start+1 == end)
			gui_print("Line %d: failed to parse string\n", line_cnt);
		else
		{
			++start;
			m_vals[key] = std::string(start, end-start);
			LOGI("MROMInstaller: got tag %s=%s\n", key.c_str(), m_vals[key].c_str());
		}
	}

	free(manifest);

	static const char* needed[] = {
		"manifest_ver", "devices", "base_folders"
	};

	for(uint32_t i = 0; i < sizeof(needed)/sizeof(needed[0]); ++i)
	{
		std::map<std::string, std::string>::const_iterator itr = m_vals.find(needed[i]);
		if(itr == m_vals.end())
			return std::string("Required key not found in manifest: ") + needed[i];
	}

	m_file = file;
	return std::string();
}
示例#11
0
static int get_tonecurve(struct shinkos1245_ctx *ctx, int type, int table, char *fname)
{
	int ret = 0, num, remaining;
	uint8_t *data, *ptr;

	struct shinkos1245_cmd_tone cmd;
	struct shinkos1245_resp_status resp;

	INFO("Dump %s Tone Curve to '%s'\n", shinkos1245_tonecurves(type, table), fname);

	/* Issue a tone_read_start */
	shinkos1245_fill_hdr(&cmd.hdr);
	cmd.cmd[0] = 0x0c;
	cmd.tone[0] = 0x54;
	cmd.tone[1] = 0x4f;
	cmd.tone[2] = 0x4e;
	cmd.tone[3] = 0x45;
	cmd.cmd2[0] = 0x72;
	cmd.read_write.tone_table = type;
	cmd.read_write.param_table = table;

	ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
				&resp, sizeof(resp), &num);

	if (ret < 0) {
		ERROR("Failed to execute TONE_READ command\n");
		return ret;
	}
	if (resp.code != CMD_CODE_OK) {
		ERROR("Bad return code on TONE_READ (%02x)\n",
		      resp.code);
		return -99;
	}

	/* Get the data out */
	remaining = TONE_CURVE_SIZE;
	data = malloc(remaining);
	if (!data) {
		ERROR("Memory Allocation Failure!\n");
		return -11;
	}
	ptr = data;

	while(remaining) {
		/* Issue a tone_data message */
		cmd.cmd2[0] = 0x20;

		ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
					 &resp, sizeof(resp), &num);

		if (ret < 0) {
			ERROR("Failed to execute TONE_DATA command\n");
			goto done;
		}
		if (resp.code != CMD_CODE_OK) {
			ERROR("Bad return code on TONE_DATA (%02x)\n",
			      resp.code);
			ret = -99;
			goto done;
		}

		/* And read back 64-bytes of data */
		ret = read_data(ctx->dev, ctx->endp_up,
				ptr, TONE_CURVE_DATA_BLOCK_SIZE, &num);
		if (num != TONE_CURVE_DATA_BLOCK_SIZE) {
			ret = -99;
			goto done;
		}
		if (ret < 0)
			goto done;
		ptr += num;
	}

	/* Issue a tone_end */
	cmd.cmd2[0] = 0x65;
	ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
				&resp, sizeof(resp), &num);

	if (ret < 0) {
		ERROR("Failed to execute TONE_END command\n");
		goto done;
	}
	if (resp.code != CMD_CODE_OK) {
		ERROR("Bad return code on TONE_END (%02x)\n",
		      resp.code);
		ret = -99;
		goto done;
	}

	/* Open file and write it out */
	{
		int tc_fd = open(fname, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
		if (tc_fd < 0) {
			ret = tc_fd;
			goto done;
		}

		ret = write(tc_fd, data, TONE_CURVE_SIZE);
		if (ret < 0)
			goto done;
		close(tc_fd);
	}

done:
	free(data);

	return ret;
}
示例#12
0
int			my_readfile_from_fd(int fd, char **data)
{
  if (fd < 0 || fd == 1 || fd == 2)
    return (0);
  return (read_data(fd, data));
}
示例#13
0
BOOL receive_smb_raw(int fd, char *buffer, unsigned int timeout)
{
	ssize_t len,ret;

	smb_read_error = 0;

	len = read_smb_length_return_keepalive(fd,buffer,timeout);
	if (len < 0) {
		DEBUG(10,("receive_smb_raw: length < 0!\n"));

		/*
		 * Correct fix. smb_read_error may have already been
		 * set. Only set it here if not already set. Global
		 * variables still suck :-). JRA.
		 */

		if (smb_read_error == 0)
			smb_read_error = READ_ERROR;
		return False;
	}

	/*
	 * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
	 * of header. Don't print the error if this fits.... JRA.
	 */

	if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
		DEBUG(0,("Invalid packet length! (%lu bytes).\n",(unsigned long)len));
		if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {

			/*
			 * Correct fix. smb_read_error may have already been
			 * set. Only set it here if not already set. Global
			 * variables still suck :-). JRA.
			 */

			if (smb_read_error == 0)
				smb_read_error = READ_ERROR;
			return False;
		}
	}

	if(len > 0) {
		if (timeout > 0) {
			ret = read_socket_with_timeout(fd,buffer+4,len,len,timeout);
		} else {
			ret = read_data(fd,buffer+4,len);
		}

		if (ret != len) {
			if (smb_read_error == 0) {
				smb_read_error = READ_ERROR;
			}
			return False;
		}
		
		/* not all of samba3 properly checks for packet-termination of strings. This
		   ensures that we don't run off into empty space. */
		SSVAL(buffer+4,len, 0);
	}

	return True;
}
示例#14
0
void dct(dct_data_t input[DW * N], dct_data_t output[DW * N])
{
	pthread_t thread_id[D];
	Params thread_args[D];
	TP0Params tp0_thread_args;

#ifdef FPGA
//	int fdr, fdw;

	fdr = open("/dev/xillybus_read_32", O_RDONLY);
	fdw = open("/dev/xillybus_write_32", O_WRONLY);
	if ((fdr < 0) || (fdw < 0)) {
		perror("Failed to open Xillybus device file(s)");
		exit(1);
	}
#endif
   
//	int buf_2d_in[D][DCT_SIZE][DCT_SIZE];
//	int buf_2d_out[D][DCT_SIZE][DCT_SIZE];
	dct_data_t *buf_2d_in0, *buf_2d_in1;
	dct_data_t *buf_2d_out0, *buf_2d_out1;

//	dct_data_t row_outbuf[D][DCT_SIZE][DCT_SIZE];
//	dct_data_t col_outbuf[D][DCT_SIZE][DCT_SIZE], col_inbuf[D][DCT_SIZE][DCT_SIZE];
	dct_data_t *row_outbuf0, *row_outbuf1;
	dct_data_t *col_outbuf0, *col_outbuf1;
	dct_data_t *col_inbuf0, *col_inbuf1;

	buf_2d_in0 = (dct_data_t *)malloc(SFN * DCT_SIZE * DCT_SIZE * sizeof(dct_data_t));
	buf_2d_in1 = (dct_data_t *)malloc(SFN * DCT_SIZE * DCT_SIZE * sizeof(dct_data_t));
	buf_2d_out0 = (dct_data_t *)malloc(SFN * DCT_SIZE * DCT_SIZE * sizeof(dct_data_t));
	buf_2d_out1 = (dct_data_t *)malloc(SFN * DCT_SIZE * DCT_SIZE * sizeof(dct_data_t));
	row_outbuf0 = (dct_data_t *)malloc(SFN * DCT_SIZE * DCT_SIZE * sizeof(dct_data_t));
	row_outbuf1 = (dct_data_t *)malloc(SFN * DCT_SIZE * DCT_SIZE * sizeof(dct_data_t));
	col_outbuf0 = (dct_data_t *)malloc(SFN * DCT_SIZE * DCT_SIZE * sizeof(dct_data_t));
	col_outbuf1 = (dct_data_t *)malloc(SFN * DCT_SIZE * DCT_SIZE * sizeof(dct_data_t));
	col_inbuf0 = (dct_data_t *)malloc(SFN * DCT_SIZE * DCT_SIZE * sizeof(dct_data_t));
	col_inbuf1 = (dct_data_t *)malloc(SFN * DCT_SIZE * DCT_SIZE * sizeof(dct_data_t));

	thread_args[1].buf_2d_in = buf_2d_in1;
	thread_args[1].row_outbuf = row_outbuf1;
	thread_args[1].col_inbuf = col_inbuf1;
	thread_args[1].nii_block = col_inbuf0;

	tp0_thread_args.col_inbuf = col_inbuf0;
	tp0_thread_args.col_outbuf = col_outbuf0;
	tp0_thread_args.buf_2d_out = buf_2d_out0;
	tp0_thread_args.nii_block = buf_2d_in1;
	tp0_thread_args.input = input;
	tp0_thread_args.output = output;

	// pre operations
	read_data(input + 0 * SFN * N, buf_2d_in0);
	dct_2d(buf_2d_in0, row_outbuf0);
	transpose(row_outbuf0, col_inbuf0);

	read_data(input + 1 * SFN * N, buf_2d_in1);

	pthread_mutex_init(&thread_counter_mutex, NULL);
	pthread_cond_init(&thread_counter_cv, NULL);
	thread_counter = 0;	// used in sync_threads()

	pthread_create(&thread_id[1], NULL, &half_dct_2d_pth_1, &thread_args[1]);
	pthread_create(&thread_id[0], NULL, &half_dct_2d_pth_0, &tp0_thread_args);

	pthread_join(thread_id[1], NULL);
	pthread_join(thread_id[0], NULL);

#ifdef FPGA
	close(fdr);
	close(fdw);
#endif
	
	//post operations
	dct_2d(col_inbuf1, col_outbuf1);
	transpose(col_outbuf1, buf_2d_out1);
	write_data(buf_2d_out1, output + (DW - 1 * SFN) * N);

	free(buf_2d_in0);
	free(buf_2d_in1);
	free(buf_2d_out0);
	free(buf_2d_out1);
	free(row_outbuf0);
	free(row_outbuf1);
	free(col_outbuf0);
	free(col_outbuf1);
	free(col_inbuf0);
	free(col_inbuf1);
}
示例#15
0
文件: uvcfb.c 项目: TangoZhu/libhal
int main(int argc, char *argv[])
{
	struct timeval tv1;		//监控键盘输入的select时间参数
	unsigned long size;		//一帧画面的字节数
	int index=0;			//V4L2 input索引号
	struct v4l2_capability cap;		//V4L2设备功能结构体变量
	struct v4l2_input i;		//V4L2设备输入信息
	struct v4l2_framebuffer fb;		//V4L2的一帧设备缓存
	int on=1;				//控制V4L2设备overlay的参数
	int tmp;
	fd_set fds1;			//监控键盘输入的select fd_set变量
	int fd;				//监控键盘输入的select句柄
	char cmd[256];			//存储从键盘读入的字符串
	
	cam_fp = cam_init();		//获得摄像头句柄
	fb_fp = fb_init();			//获得帧缓冲句柄
	
	size=width*height*fb_bpp/8;

	if((tmp=ioctl(cam_fp, VIDIOC_QUERYCAP, &cap))<0) 
	{		//查询驱动功能
		printf("VIDIOC_QUERYCAP error, ret=0x%x\n",tmp);
		goto err;
	}
	printf("Driver:%s, Card:%s, cap=0x%x,bus info is %s\n",cap.driver,cap.card,cap.capabilities,cap.bus_info);
	
	memset(&i, 0, sizeof(i));
	i.index=index;
	if(ioctl(cam_fp, VIDIOC_ENUMINPUT, &i)<0)
	{//枚举输入源
		goto err;
	}
	printf("input name:%s\n",i.name);	
	
	index=0;
	if(ioctl(cam_fp, VIDIOC_S_INPUT, &index)<0)		//设置输入源
	{
	    printf("VIDIOC_S_INPUT failed\n");
		goto err;
    }
	if(ioctl(cam_fp, VIDIOC_S_OUTPUT, &index)<0)		//设置输出源
	{
	    
	    printf(" VIDIOC_S_OUTPUT failed\n");
	        goto err;
	}
	if(ioctl(cam_fp, VIDIOC_G_FBUF, &fb)<0)		//获取V4L2设备FB属性参数
	{
	    printf(" VIDIOC_G_FBUF failed\n");
		goto err;
	}

	printf("g_fbuf:capabilities=0x%x,flags=0x%x,width=%d,height=%d\n"
	       "pixelformat=0x%x,bytesperline=%d,colorspace=%d,base=0x%x\n",
		    fb.capability,fb.flags,fb.fmt.width,fb.fmt.height
		    ,fb.fmt.pixelformat,fb.fmt.bytesperline,fb.fmt.colorspace
		    ,fb.base);
		    
	fb.capability = cap.capabilities;	//V4L2设备功能赋值给V4L2的FB功能属性
	fb.fmt.width =width;				//LCD的FB宽度赋值给V4L2的FB宽度
	fb.fmt.height = height;				//LCD的FB高度赋值给V4L2的FB高度
	fb.fmt.pixelformat = (fb_bpp==32)?V4L2_PIX_FMT_BGR32:V4L2_PIX_FMT_RGB565;		//赋值V4L2的FB像素位数

	if(ioctl(cam_fp, VIDIOC_S_FBUF, &fb)<0)		//设置新的FB属性给摄像头
	{
	
        printf(" VIDIOC_S_FBUF failed\n");
   		goto err;
    }
    
	on = 1;
	if(ioctl(cam_fp, VIDIOC_OVERLAY, &on)<0)//使能摄像头的overlay
	{
	
        printf(" VIDIOC_OVERLAY failed\n");
		goto err;
	}
	
	vf_buff = (char*)malloc(size);
	if(vf_buff==NULL)
	{
		goto err;
	}

	if(fb_bpp==16)
	{	//16位BMP
	    *((unsigned int*)(bmp_head_t+18)) = width;
	    *((unsigned int*)(bmp_head_t+22)) = height;
	    *((unsigned short*)(bmp_head_t+28)) = 16;
	}
	else
	{
    	bmp_head[0] = 'B';
    	bmp_head[1] = 'M';
    	*((unsigned int*)(bmp_head+2)) = (width*fb_bpp/8)*height+54;		//整个位图大小
    	*((unsigned int*)(bmp_head+10)) = 54;				//从54字节开始存图像
    	*((unsigned int*)(bmp_head+14)) = 40;				//图像描述信息块的大小
    	*((unsigned int*)(bmp_head+18)) = width;
    	*((unsigned int*)(bmp_head+22)) = height;
    	*((unsigned short*)(bmp_head+26)) = 1;				//图像的plane总数
    	*((unsigned short*)(bmp_head+28)) = fb_bpp;
    	*((unsigned short*)(bmp_head+34)) = (width*fb_bpp/8)*height;		//图像数据区大小
	}
	
	while(1)
	{
	    if (!read_data(cam_fp, vf_buff, width, height, fb_bpp))		//读摄像头数据到vf_buff
	    {
		    printf("read error\n");
	    }
	    memcpy(fb_addr,vf_buff,width*height*fb_bpp/8);		//将读到的图像数据从内存拷贝到帧缓冲地址
	    fd=0;							//键盘句柄
	    tv1.tv_sec=0;
	    tv1.tv_usec=0;						//无限等待
	    FD_ZERO(&fds1);
	    FD_SET(fd,&fds1);					//绑定句柄跟监控对象
	    select(fd+1,&fds1,NULL,NULL,&tv1);			//监控键盘输入
	    if(FD_ISSET(fd,&fds1))					//如果键盘有输入
	    {
		    memset(cmd,0,sizeof(cmd));
		    read(fd,cmd,256);					//读取键盘输入的字符
		    if(strncmp(cmd,"quit",4)==0)
		    {			//如果键盘输入quit
    		    printf("-->quit\n");
    		    on=0;
    		    if(ioctl(cam_fp, VIDIOC_OVERLAY, &on)<0)//关掉V4L2设备的overlay
    		    {
    			    goto err;
    			}
    		    close(fb_fp);
    		    close(cam_fp);					//释放FB跟摄像头的句柄
    		    return 0;
		    }
		    else if(strncmp(cmd,"capt",4)==0)
		    {			//如果键盘输入capt
    		    printf("-->capture\n");
    		    printf("write to img --> ");
    		    writeImageToFile(size);				//把FB数据保存到位图中
    		    printf("OK\n");
		    }
	    }
	}

err:
	if (cam_fp)
		close(cam_fp);
	if (fb_fp)
		close(fb_fp);
	return 1;
}
示例#16
0
void
tcpobserver::exiting_connect(pid_t pid)
{
    int result;

    result = ptrace(PTRACE_PEEKUSER, pid, RAX * 8, NULL);

    if (result < 0)
        return;

    if (m_proc[pid].m_addrlen < sizeof(long))
        return;


    sockaddr_storage saddr;
    std::string      domain;
    double           datetime;
    uint16_t         port;
    char             addr[64];

    read_data(pid, &saddr, m_proc[pid].m_addr, sizeof(long));

    switch (saddr.ss_family) {
    case AF_INET:
    {
        sockaddr_in *saddr_in;

        if (m_proc[pid].m_addrlen < sizeof(sockaddr_in))
            return;

        read_data(pid, &saddr, m_proc[pid].m_addr, sizeof(sockaddr_in));

        saddr_in = (sockaddr_in*)&saddr;

        inet_ntop(AF_INET, &saddr_in->sin_addr, addr, sizeof(addr));
        port   = ntohs(saddr_in->sin_port);
        domain = "IPv4";

        break;
    }
    case AF_INET6:
    {
        sockaddr_in6 *saddr_in6;

        if (m_proc[pid].m_addrlen < sizeof(sockaddr_in6))
            return;

        read_data(pid, &saddr, m_proc[pid].m_addr, sizeof(sockaddr_in6));

        saddr_in6 = (sockaddr_in6*)&saddr;

        inet_ntop(AF_INET6, &saddr_in6->sin6_addr, addr, sizeof(addr));
        port   = ntohs(saddr_in6->sin6_port);
        domain = "IPv6";

        break;
    }
    default:
        return;
    }

    datetime = get_datetime();

    m_fd_set.insert(result);

    std::cerr << std::setprecision(19)
              << "datetime@" << datetime
              << " op@connect"
              << " fd@" << result
              << " protocol@" << domain
              << " addr@" << addr
              << " port@" << port
              << " pid@" << pid
              << std::endl;
}
示例#17
0
const
size_t assemble_arm(
		uint8_t *const bytecode,
		const size_t bytecode_sz,
		const char *const assembly,
		const size_t asm_sz)
{
	size_t sz = 0;

	char path[PATH_MAX];
	snprintf(path, sizeof(path), "/tmp/rappel-output.XXXXXX");

	const int t = mkstemp(path);

	if (t == -1) {
		perror("mkstemp");
		exit(EXIT_FAILURE);
	}

	REQUIRE (unlink(path) == 0);

	int fildes[2];
	REQUIRE (pipe(fildes) == 0);

	const pid_t asm_pid = fork();

	if (asm_pid < 0) {
		perror("fork");
		exit(EXIT_FAILURE);
	} else if (asm_pid == 0) {
		_child_assemble(fildes, t);
		// Not reached
		abort();
	}

	verbose_printf("as is pid %d\n", asm_pid);

	REQUIRE (close(fildes[0]) == 0);

	write_data(fildes[1], (uint8_t *)assembly, asm_sz);

	REQUIRE (close(fildes[1]) == 0);

	int asm_status;
	REQUIRE (waitpid(asm_pid, &asm_status, 0) != -1);

	if (WIFSIGNALED(asm_status)) {
		fprintf(stderr, "as exited with signal %d.\n", WTERMSIG(asm_status));
	} else if (WIFEXITED(asm_status) && WEXITSTATUS(asm_status)) {
		fprintf(stderr, "as exited %d.\n", WEXITSTATUS(asm_status));
		goto exit;
	}

	REQUIRE (lseek(t, SEEK_SET, 0) != -1);

	int results[2];
	REQUIRE (pipe(results) == 0);

	const pid_t objcopy_pid = fork();

	if (objcopy_pid < 0) {
		perror("fork");
		exit(EXIT_FAILURE);
	} else if (objcopy_pid == 0) {
		_child_objcopy(results, t);
		// Not reached
		abort();
	}

	verbose_printf("objcopy is pid %d\n", objcopy_pid);

	REQUIRE (close(results[1]) == 0);

	mem_assign(bytecode, bytecode_sz, TRAP, TRAP_SZ);

	sz = read_data(results[0], bytecode, bytecode_sz);

	if (sz >= bytecode_sz) {
		fprintf(stderr, "Too much bytecode to handle, exiting...\n");
		exit(EXIT_FAILURE);
	}

	int objcopy_status;
	REQUIRE (waitpid(objcopy_pid, &objcopy_status, 0) != -1);

	if (WIFEXITED(objcopy_status) && WIFSIGNALED(objcopy_status))
		fprintf(stderr, "objcopy exited with signal %d.\n", WTERMSIG(objcopy_status));
	else if (WIFEXITED(objcopy_status) && WEXITSTATUS(objcopy_status))
		fprintf(stderr, "objcopy exited %d.\n", WEXITSTATUS(objcopy_status));

exit:
	REQUIRE (close(t) == 0);

	return sz;
}
static int test_data(void)
{
    hid_t          fid;
    hsize_t        pal_dims[2];
    hsize_t        width;
    hsize_t        height;
    unsigned char  pal[256*3]; /* buffer to hold an HDF5 palette */
    rgb_t          rgb[256];   /* buffer to hold a .pal file palette */
    int            i, n;

    /* create a file using default properties */
    if ((fid=H5Fcreate(FILE2,H5F_ACC_TRUNC,H5P_DEFAULT,H5P_DEFAULT))<0)
        goto out;

    printf("Testing read ascii image data and generate images\n");

    /*-------------------------------------------------------------------------
    * read 8bit image data
    *-------------------------------------------------------------------------
    */

    TESTING2("make indexed image");

    /* read first data file */
    if (read_data(DATA_FILE1,&width,&height)<0)
        goto out;

    /* make an image */
    if (H5IMmake_image_8bit(fid,IMAGE1_NAME,width,height,image_data)<0)
        goto out;

    PASSED();


    TESTING2("attaching palettes");

    /*-------------------------------------------------------------------------
    * palette #1. rainbow palette. data is contained in "pal_rgb.h"
    *-------------------------------------------------------------------------
    */

    /* initialize the palette data */
    pal_dims[0] = 256;
    pal_dims[1] = 3;

    /* make a palette */
    if (H5IMmake_palette(fid,PAL1_NAME,pal_dims,pal_rgb)<0)
        goto out;

    /* attach a palette to the image dataset */
    if (H5IMlink_palette(fid,IMAGE1_NAME,PAL1_NAME)<0)
        goto out;

    /*-------------------------------------------------------------------------
    * palette #2. sepia palette.
    * read a PAL file and attach the palette to the HDF5 file
    *-------------------------------------------------------------------------
    */

    /* read a PAL file */
    if (read_palette(PAL2_FILE, rgb, sizeof(rgb))<0)
        goto out;

    /* transfer to the HDF5 buffer */
    for ( i=0, n=0; i<256*3; i+=3, n++)
    {
        pal[i]  =rgb[n].r;
        pal[i+1]=rgb[n].g;
        pal[i+2]=rgb[n].b;
    }

    /* make a palette */
    if (H5IMmake_palette(fid,PAL2_NAME,pal_dims,pal)<0)
        goto out;

    /* attach the palette to the image dataset */
    if (H5IMlink_palette(fid,IMAGE1_NAME,PAL2_NAME)<0)
        goto out;

    /*-------------------------------------------------------------------------
    * palette #3. earth palette.
    * read a PAL file and attach the palette to the HDF5 file
    *-------------------------------------------------------------------------
    */

    /* read a PAL file */
    if (read_palette(PAL3_FILE, rgb, sizeof(rgb))<0)
        goto out;

    /* transfer to the HDF5 buffer */
    for ( i=0, n=0; i<256*3; i+=3, n++)
    {
        pal[i]  =rgb[n].r;
        pal[i+1]=rgb[n].g;
        pal[i+2]=rgb[n].b;
    }

    /* make a palette */
    if (H5IMmake_palette(fid,PAL3_NAME,pal_dims,pal)<0)
        goto out;

    /* attach the palette to the image dataset */
    if (H5IMlink_palette(fid,IMAGE1_NAME,PAL3_NAME)<0)
        goto out;

    PASSED();


    /*-------------------------------------------------------------------------
    * palette #4. blue-red
    * make a palette whith blue to red colors
    *-------------------------------------------------------------------------
    */
    for ( i=0, n=0; i<256*3; i+=3, n++)
    {
        pal[i]  =n;
        pal[i+1]=0;
        pal[i+2]=255-n;
    }

    /* make a palette */
    if (H5IMmake_palette(fid,PAL4_NAME,pal_dims,pal)<0)
        goto out;

    /* attach the palette to the image dataset */
    if (H5IMlink_palette(fid,IMAGE1_NAME,PAL4_NAME)<0)
        goto out;


    /*-------------------------------------------------------------------------
    * true color image example with pixel interlace
    *-------------------------------------------------------------------------
    */

    TESTING2("make true color image with pixel interlace");

    /* read second data file */
    if ((read_data(DATA_FILE2,&width,&height))<0)
        goto out;

    /* make image */
    if ((H5IMmake_image_24bit(fid,IMAGE2_NAME,width,height,"INTERLACE_PIXEL",image_data))<0)
        goto out;

    PASSED();

    /*-------------------------------------------------------------------------
    * True color image example with plane interlace
    *-------------------------------------------------------------------------
    */

    TESTING2("make true color image with plane interlace");

    /* read third data file */
    if ((read_data(DATA_FILE3,&width,&height))<0)
        goto out;

    /* make image */
    if ((H5IMmake_image_24bit(fid,IMAGE3_NAME,width,height,"INTERLACE_PLANE",image_data))<0)
        goto out;

    PASSED();


    /*-------------------------------------------------------------------------
    * close
    *-------------------------------------------------------------------------
    */
    if (H5Fclose(fid)<0)
        goto out;

    return 0;

    /* error zone, gracefully close */
out:
    H5E_BEGIN_TRY {
        H5Fclose(fid);
    } H5E_END_TRY;
    H5_FAILED();
    return FAIL;
}
示例#19
0
/* This implements the state machine defined in the IPMI manual, see
   that for details on how this works.  Divide that flowchart into
   sections delimited by "Wait for IBF" and this will become clear. */
static enum si_sm_result kcs_event(struct si_sm_data *kcs, long time)
{
	unsigned char status;
	unsigned char state;

	status = read_status(kcs);

	if (kcs_debug & KCS_DEBUG_STATES)
		printk(KERN_DEBUG "KCS: State = %d, %x\n", kcs->state, status);

	/* All states wait for ibf, so just do it here. */
	if (!check_ibf(kcs, status, time))
		return SI_SM_CALL_WITH_DELAY;

	/* Just about everything looks at the KCS state, so grab that, too. */
	state = GET_STATUS_STATE(status);

	switch (kcs->state) {
	case KCS_IDLE:
		/* If there's and interrupt source, turn it off. */
		clear_obf(kcs, status);

		if (GET_STATUS_ATN(status))
			return SI_SM_ATTN;
		else
			return SI_SM_IDLE;

	case KCS_START_OP:
		if (state != KCS_IDLE) {
			start_error_recovery(kcs,
					     "State machine not idle at start");
			break;
		}

		clear_obf(kcs, status);
		write_cmd(kcs, KCS_WRITE_START);
		kcs->state = KCS_WAIT_WRITE_START;
		break;

	case KCS_WAIT_WRITE_START:
		if (state != KCS_WRITE_STATE) {
			start_error_recovery(
				kcs,
				"Not in write state at write start");
			break;
		}
		read_data(kcs);
		if (kcs->write_count == 1) {
			write_cmd(kcs, KCS_WRITE_END);
			kcs->state = KCS_WAIT_WRITE_END;
		} else {
			write_next_byte(kcs);
			kcs->state = KCS_WAIT_WRITE;
		}
		break;

	case KCS_WAIT_WRITE:
		if (state != KCS_WRITE_STATE) {
			start_error_recovery(kcs,
					     "Not in write state for write");
			break;
		}
		clear_obf(kcs, status);
		if (kcs->write_count == 1) {
			write_cmd(kcs, KCS_WRITE_END);
			kcs->state = KCS_WAIT_WRITE_END;
		} else {
			write_next_byte(kcs);
		}
		break;
		
	case KCS_WAIT_WRITE_END:
		if (state != KCS_WRITE_STATE) {
			start_error_recovery(kcs,
					     "Not in write state for write end");
			break;
		}
		clear_obf(kcs, status);
		write_next_byte(kcs);
		kcs->state = KCS_WAIT_READ;
		break;

	case KCS_WAIT_READ:
		if ((state != KCS_READ_STATE) && (state != KCS_IDLE_STATE)) {
			start_error_recovery(
				kcs,
				"Not in read or idle in read state");
			break;
		}

		if (state == KCS_READ_STATE) {
			if (! check_obf(kcs, status, time))
				return SI_SM_CALL_WITH_DELAY;
			read_next_byte(kcs);
		} else {
			/* We don't implement this exactly like the state
			   machine in the spec.  Some broken hardware
			   does not write the final dummy byte to the
			   read register.  Thus obf will never go high
			   here.  We just go straight to idle, and we
			   handle clearing out obf in idle state if it
			   happens to come in. */
			clear_obf(kcs, status);
			kcs->orig_write_count = 0;
			kcs->state = KCS_IDLE;
			return SI_SM_TRANSACTION_COMPLETE;
		}
		break;

	case KCS_ERROR0:
		clear_obf(kcs, status);
		status = read_status(kcs);
		if  (GET_STATUS_OBF(status)) /* controller isn't responding */
			if (time_before(jiffies, kcs->error0_timeout))
				return SI_SM_CALL_WITH_TICK_DELAY;
		write_cmd(kcs, KCS_GET_STATUS_ABORT);
		kcs->state = KCS_ERROR1;
		break;

	case KCS_ERROR1:
		clear_obf(kcs, status);
		write_data(kcs, 0);
		kcs->state = KCS_ERROR2;
		break;
		
	case KCS_ERROR2:
		if (state != KCS_READ_STATE) {
			start_error_recovery(kcs,
					     "Not in read state for error2");
			break;
		}
		if (! check_obf(kcs, status, time))
			return SI_SM_CALL_WITH_DELAY;

		clear_obf(kcs, status);
		write_data(kcs, KCS_READ_BYTE);
		kcs->state = KCS_ERROR3;
		break;
		
	case KCS_ERROR3:
		if (state != KCS_IDLE_STATE) {
			start_error_recovery(kcs,
					     "Not in idle state for error3");
			break;
		}

		if (! check_obf(kcs, status, time))
			return SI_SM_CALL_WITH_DELAY;

		clear_obf(kcs, status);
		if (kcs->orig_write_count) {
			restart_kcs_transaction(kcs);
		} else {
			kcs->state = KCS_IDLE;
			return SI_SM_TRANSACTION_COMPLETE;
		}
		break;
			
	case KCS_HOSED:
		break;
	}

	if (kcs->state == KCS_HOSED) {
		init_kcs_data(kcs, kcs->io);
		return SI_SM_HOSED;
	}

	return SI_SM_CALL_WITHOUT_DELAY;
}
示例#20
0
文件: udpxy.c 项目: AllardJ/Tomato
/* relay traffic from source to destination socket
 *
 */
static int
relay_traffic( int ssockfd, int dsockfd, struct server_ctx* ctx,
               int dfilefd, const struct in_addr* mifaddr )
{
    volatile sig_atomic_t quit = 0;

    int rc = 0;
    ssize_t nmsgs = -1;
    ssize_t nrcv = 0, nsent = 0, nwr = 0,
            lrcv = 0, lsent = 0;
    char*  data = NULL;
    size_t data_len = g_uopt.rbuf_len;
    struct rdata_opt ropt;
    time_t pause_time = 0, rfr_tm = time(NULL);
    sigset_t ubset;

    const int ALLOW_PAUSES = get_flagval( "UDPXY_ALLOW_PAUSES", 0 );
    const ssize_t MAX_PAUSE_MSEC =
        get_sizeval( "UDPXY_PAUSE_MSEC", 1000);

    /* permissible variation in data-packet size */
    static const ssize_t t_delta = 0x20;

    struct dstream_ctx ds;

    static const int SET_PID = 1;
    struct tps_data tps;

    assert( ctx && mifaddr && MAX_PAUSE_MSEC > 0 );

    (void) sigemptyset (&ubset);
    sigaddset (&ubset, SIGINT);
    sigaddset (&ubset, SIGQUIT);
    sigaddset (&ubset, SIGTERM);

    /* restore the ability to receive *quit* signals */
    rc = sigprocmask (SIG_UNBLOCK, &ubset, NULL);
    if (0 != rc) {
        mperror (g_flog, errno, "%s: sigprocmask", __func__);
        return -1;
    }

    /* NOPs to eliminate warnings in lean version */
    (void)&lrcv; (void)&lsent; (void)&t_delta;

    check_fragments( NULL, 0, 0, 0, 0, g_flog );

    /* INIT
     */

    rc = calc_buf_settings( &nmsgs, NULL );
    if (0 != rc) return -1;

    TRACE( (void)tmfprintf( g_flog, "Data buffer will hold up to "
                        "[%d] messages\n", nmsgs ) );

    rc = init_dstream_ctx( &ds, ctx->rq.cmd, g_uopt.srcfile, nmsgs );
    if( 0 != rc ) return -1;

    (void) set_nice( g_uopt.nice_incr, g_flog );

    do {
        if( NULL == g_uopt.srcfile ) {
            rc = set_timeouts( ssockfd, dsockfd,
                               ctx->rcv_tmout, 0,
                               ctx->snd_tmout, 0 );
            if( 0 != rc ) break;
        }

        if( dsockfd > 0 ) {
            rc = sync_dsockbuf_len( ssockfd, dsockfd );
            if( 0 != rc ) break;

            rc = send_http_response( dsockfd, 200, "OK" );
            if( 0 != rc ) break;

            /* timeshift: to detect PAUSE make destination
            * socket non-blocking, otherwise make it blocking
            * (since it might have been set unblocking earlier)
            */
            rc = set_nblock( dsockfd, (ALLOW_PAUSES ? 1 : 0) );
            if( 0 != rc ) break;
        }

        data = malloc(data_len);
        if( NULL == data ) {
            mperror( g_flog, errno, "%s: malloc", __func__ );
            break;
        }

        if( g_uopt.cl_tpstat )
            tpstat_init( &tps, SET_PID );
    } while(0);

    TRACE( (void)tmfprintf( g_flog, "Relaying traffic from socket[%d] "
            "to socket[%d], buffer size=[%d], Rmsgs=[%d], pauses=[%d]\n",
            ssockfd, dsockfd, data_len, g_uopt.rbuf_msgs, ALLOW_PAUSES) );

    /* RELAY LOOP
     */
    ropt.max_frgs = g_uopt.rbuf_msgs;
    ropt.buf_tmout = g_uopt.dhold_tmout;

    pause_time = 0;

    while( (0 == rc) && !(quit = must_quit()) ) {
        if( g_uopt.mcast_refresh > 0 ) {
            check_mcast_refresh( ssockfd, &rfr_tm, mifaddr );
        }

        nrcv = read_data( &ds, ssockfd, data, data_len, &ropt );
        if( -1 == nrcv ) break;

        TRACE( check_fragments( "received new", data_len,
                    lrcv, nrcv, t_delta, g_flog ) );
        lrcv = nrcv;

        if( dsockfd && (nrcv > 0) ) {
            nsent = write_data( &ds, data, nrcv, dsockfd );
            if( -1 == nsent ) break;

            if ( nsent < 0 ) {
                if ( !ALLOW_PAUSES ) break;
                if ( 0 != pause_detect( nsent, MAX_PAUSE_MSEC, &pause_time ) )
                    break;
            }

            TRACE( check_fragments("sent", nrcv,
                        lsent, nsent, t_delta, g_flog) );
            lsent = nsent;
        }

        if( (dfilefd > 0) && (nrcv > 0) ) {
            nwr = write_data( &ds, data, nrcv, dfilefd );
            if( -1 == nwr )
                break;
            TRACE( check_fragments( "wrote to file",
                    nrcv, lsent, nwr, t_delta, g_flog ) );
            lsent = nwr;
        }

        if( ds.flags & F_SCATTERED ) reset_pkt_registry( &ds );

        if( uf_TRUE == g_uopt.cl_tpstat )
            tpstat_update( ctx, &tps, nsent );

    } /* end of RELAY LOOP */

    /* CLEANUP
     */
    TRACE( (void)tmfprintf( g_flog, "Exited relay loop: received=[%ld], "
        "sent=[%ld], quit=[%ld]\n", (long)nrcv, (long)nsent, (long)quit ) );

    free_dstream_ctx( &ds );
    if( NULL != data ) free( data );

    if( 0 != (quit = must_quit()) ) {
        TRACE( (void)tmfprintf( g_flog, "Child process=[%d] must quit\n",
                    getpid()) );
    }

    return rc;
}
示例#21
0
unsigned char readTradeInfo(void)
{
	return read_data((void *)&stTotalTrade,sizeof(stTotalTrade),ADD_USER_DATA);

}
示例#22
0
int InterpolateVideo::load_configuration()
{
	KeyFrame *prev_keyframe, *next_keyframe;
	InterpolateVideoConfig old_config;
	old_config.copy_from(&config);

	next_keyframe = get_next_keyframe(get_source_position());
	prev_keyframe = get_prev_keyframe(get_source_position());
// Previous keyframe stays in config object.
	read_data(prev_keyframe);


	int64_t prev_position = edl_to_local(prev_keyframe->position);
	int64_t next_position = edl_to_local(next_keyframe->position);
	if(prev_position == 0 && next_position == 0)
	{
		next_position = prev_position = get_source_start();
	}
// printf("InterpolateVideo::load_configuration 1 %lld %lld %lld %lld\n",
// prev_keyframe->position,
// next_keyframe->position,
// prev_position,
// next_position);

// Get range to average in requested rate
	range_start = prev_position;
	range_end = next_position;


// Use keyframes to determine range
	if(config.use_keyframes)
	{
		active_input_rate = get_framerate();
// Between keyframe and edge of range or no keyframes
		if(range_start == range_end)
		{
// Between first keyframe and start of effect
			if(get_source_position() >= get_source_start() &&
				get_source_position() < range_start)
			{
				range_start = get_source_start();
			}
			else
// Between last keyframe and end of effect
			if(get_source_position() >= range_start &&
				get_source_position() < get_source_start() + get_total_len())
			{
// Last frame should be inclusive of current effect
				range_end = get_source_start() + get_total_len() - 1;
			}
			else
			{
// Should never get here
				;
			}
		}


// Make requested rate equal to input rate for this mode.

// Convert requested rate to input rate
// printf("InterpolateVideo::load_configuration 2 %lld %lld %f %f\n", 
// range_start, 
// range_end,
// get_framerate(),
// config.input_rate);
//		range_start = (int64_t)((double)range_start / get_framerate() * active_input_rate + 0.5);
//		range_end = (int64_t)((double)range_end / get_framerate() * active_input_rate + 0.5);
	}
	else
// Use frame rate
	{
		active_input_rate = config.input_rate;
// Convert to input frame rate
		range_start = (int64_t)(get_source_position() / 
			get_framerate() *
			active_input_rate);
		range_end = (int64_t)(get_source_position() / 
			get_framerate() *
			active_input_rate) + 1;
	}

// printf("InterpolateVideo::load_configuration 1 %lld %lld %lld %lld %lld %lld\n",
// prev_keyframe->position,
// next_keyframe->position,
// prev_position,
// next_position,
// range_start,
// range_end);


	return !config.equivalent(&old_config);
}
示例#23
0
文件: kcs_bmc.c 项目: guribe94/linux
static void kcs_bmc_handle_data(struct kcs_bmc *kcs_bmc)
{
	u8 data;

	switch (kcs_bmc->phase) {
	case KCS_PHASE_WRITE_START:
		kcs_bmc->phase = KCS_PHASE_WRITE_DATA;
		/* fall through */

	case KCS_PHASE_WRITE_DATA:
		if (kcs_bmc->data_in_idx < KCS_MSG_BUFSIZ) {
			set_state(kcs_bmc, WRITE_STATE);
			write_data(kcs_bmc, KCS_ZERO_DATA);
			kcs_bmc->data_in[kcs_bmc->data_in_idx++] =
						read_data(kcs_bmc);
		} else {
			kcs_force_abort(kcs_bmc);
			kcs_bmc->error = KCS_LENGTH_ERROR;
		}
		break;

	case KCS_PHASE_WRITE_END_CMD:
		if (kcs_bmc->data_in_idx < KCS_MSG_BUFSIZ) {
			set_state(kcs_bmc, READ_STATE);
			kcs_bmc->data_in[kcs_bmc->data_in_idx++] =
						read_data(kcs_bmc);
			kcs_bmc->phase = KCS_PHASE_WRITE_DONE;
			kcs_bmc->data_in_avail = true;
			wake_up_interruptible(&kcs_bmc->queue);
		} else {
			kcs_force_abort(kcs_bmc);
			kcs_bmc->error = KCS_LENGTH_ERROR;
		}
		break;

	case KCS_PHASE_READ:
		if (kcs_bmc->data_out_idx == kcs_bmc->data_out_len)
			set_state(kcs_bmc, IDLE_STATE);

		data = read_data(kcs_bmc);
		if (data != KCS_CMD_READ_BYTE) {
			set_state(kcs_bmc, ERROR_STATE);
			write_data(kcs_bmc, KCS_ZERO_DATA);
			break;
		}

		if (kcs_bmc->data_out_idx == kcs_bmc->data_out_len) {
			write_data(kcs_bmc, KCS_ZERO_DATA);
			kcs_bmc->phase = KCS_PHASE_IDLE;
			break;
		}

		write_data(kcs_bmc,
			kcs_bmc->data_out[kcs_bmc->data_out_idx++]);
		break;

	case KCS_PHASE_ABORT_ERROR1:
		set_state(kcs_bmc, READ_STATE);
		read_data(kcs_bmc);
		write_data(kcs_bmc, kcs_bmc->error);
		kcs_bmc->phase = KCS_PHASE_ABORT_ERROR2;
		break;

	case KCS_PHASE_ABORT_ERROR2:
		set_state(kcs_bmc, IDLE_STATE);
		read_data(kcs_bmc);
		write_data(kcs_bmc, KCS_ZERO_DATA);
		kcs_bmc->phase = KCS_PHASE_IDLE;
		break;

	default:
		kcs_force_abort(kcs_bmc);
		break;
	}
}
示例#24
0
	LLDSPEC color_t gdisp_lld_read_color(GDisplay* g) {
		uint16_t	data;

		data = read_data(g);
		return gdispNative2Color(data);
	}
示例#25
0
/***************************************************************************
  check the DNS queue
  ****************************************************************************/
void run_dns_queue(void)
{
	struct query_record r;
	struct packet_struct *p, *p2;
	struct name_record *namerec;
	int size;

	if (fd_in == -1)
		return;

        /* Allow SIGTERM to kill us. */
        BlockSignals(False, SIGTERM);

	if (!process_exists_by_pid(child_pid)) {
		close(fd_in);
		close(fd_out);
		start_async_dns();
	}

	if ((size=read_data(fd_in, (char *)&r, sizeof(r))) != sizeof(r)) {
		if (size) {
			DEBUG(0,("Incomplete DNS answer from child!\n"));
			fd_in = -1;
		}
                BlockSignals(True, SIGTERM);
		return;
	}

        BlockSignals(True, SIGTERM);

	namerec = add_dns_result(&r.name, r.result);

	if (dns_current) {
		if (query_current(&r)) {
			DEBUG(3,("DNS calling send_wins_name_query_response\n"));
			in_dns = 1;
			if(namerec == NULL)
				send_wins_name_query_response(NAM_ERR, dns_current, NULL);
			else
				send_wins_name_query_response(0,dns_current,namerec);
			in_dns = 0;
		}

		dns_current->locked = False;
		free_packet(dns_current);
		dns_current = NULL;
	}

	/* loop over the whole dns queue looking for entries that
	   match the result we just got */
	for (p = dns_queue; p;) {
		struct nmb_packet *nmb = &p->packet.nmb;
		struct nmb_name *question = &nmb->question.question_name;

		if (nmb_name_equal(question, &r.name)) {
			DEBUG(3,("DNS calling send_wins_name_query_response\n"));
			in_dns = 1;
			if(namerec == NULL)
				send_wins_name_query_response(NAM_ERR, p, NULL);
			else
				send_wins_name_query_response(0,p,namerec);
			in_dns = 0;
			p->locked = False;

			if (p->prev)
				p->prev->next = p->next;
			else
				dns_queue = p->next;
			if (p->next)
				p->next->prev = p->prev;
			p2 = p->next;
			free_packet(p);
			p = p2;
		} else {
			p = p->next;
		}
	}

	if (dns_queue) {
		dns_current = dns_queue;
		dns_queue = dns_queue->next;
		if (dns_queue)
			dns_queue->prev = NULL;
		dns_current->next = NULL;

		if (!write_child(dns_current)) {
			DEBUG(3,("failed to send DNS query to child!\n"));
			return;
		}
	}
}
示例#26
0
/*
 * State machine of the non-blocking read.
 */
bool DHT_nonblocking::read_nonblocking( )
{
  bool status = false;

  switch( dht_state )
  {
  /* We may begin measuring any time. */
  case DHT_IDLE:
    dht_state = DHT_BEGIN_MEASUREMENT;
    break;

  /* Initiate a sensor read.  The read begins by going to high impedance
     state for 250 ms. */
  case DHT_BEGIN_MEASUREMENT:
    digitalWrite( _pin, HIGH );
    /* Reset 40 bits of received data to zero. */
    data[ 0 ] = data[ 1 ] = data[ 2 ] = data[ 3 ] = data[ 4 ] = 0;
    dht_timestamp = millis( );
    dht_state = DHT_BEGIN_MEASUREMENT_2;
    break;

  /* After the high impedance state, pull the pin low for 20 ms. */
  case DHT_BEGIN_MEASUREMENT_2:
    /* Wait for 250 ms. */
    if( millis( ) - dht_timestamp > 250 )
    {
      pinMode( _pin, OUTPUT );
      digitalWrite( _pin, LOW );
      dht_timestamp = millis( );
      dht_state = DHT_DO_READING;
    }
    break;

  case DHT_DO_READING:
    /* Wait for 20 ms. */
    if( millis( ) - dht_timestamp > 20 )
    {
      dht_timestamp = millis( );
      dht_state = DHT_COOLDOWN;
      status = read_data( );
//      if( status != true )
//      {
//        Serial.println( "Reading failed" );
//      }
    }
    break;

  /* If it has been less than two seconds since the last time we read
     the sensor, then let the sensor cool down.. */
  case DHT_COOLDOWN:
    if( millis( ) - dht_timestamp > COOLDOWN_TIME )
    {
      dht_state = DHT_IDLE;
    }
    break;

  default:
    break;
  }

  return( status );
}
示例#27
0
unsigned char isapnp_read_byte(unsigned char idx)
{
	write_address(idx);
	return read_data();
}
示例#28
0
文件: dump.c 项目: andreiw/polaris
int
main(int argc, char *argv[])
{
	const char *filename = NULL;
	const char *ufile = NULL;
	int error = 0;
	int c, fd, ufd;

	ctf_data_t cd;
	const ctf_preamble_t *pp;
	ctf_header_t *hp;
	Elf *elf;
	GElf_Ehdr ehdr;

	(void) elf_version(EV_CURRENT);

	for (opterr = 0; optind < argc; optind++) {
		while ((c = getopt(argc, argv, "dfhlsStu:")) != (int)EOF) {
			switch (c) {
			case 'd':
				flags |= F_DATA;
				break;
			case 'f':
				flags |= F_FUNC;
				break;
			case 'h':
				flags |= F_HDR;
				break;
			case 'l':
				flags |= F_LABEL;
				break;
			case 's':
				flags |= F_STR;
				break;
			case 'S':
				flags |= F_STATS;
				break;
			case 't':
				flags |= F_TYPES;
				break;
			case 'u':
				ufile = optarg;
				break;
			default:
				if (optopt == '?')
					return (print_usage(stdout, 1));
				warn("illegal option -- %c\n", optopt);
				return (print_usage(stderr, 0));
			}
		}

		if (optind < argc) {
			if (filename != NULL)
				return (print_usage(stderr, 0));
			filename = argv[optind];
		}
	}

	if (filename == NULL)
		return (print_usage(stderr, 0));

	if (flags == 0 && ufile == NULL)
		flags = F_ALLMSK;

	if ((fd = open(filename, O_RDONLY)) == -1)
		die("failed to open %s", filename);

	if ((elf = elf_begin(fd, ELF_C_READ, NULL)) != NULL &&
	    gelf_getehdr(elf, &ehdr) != NULL) {

		Elf_Data *dp;
		Elf_Scn *ctfscn = findelfscn(elf, &ehdr, ".SUNW_ctf");
		Elf_Scn *symscn;
		GElf_Shdr ctfshdr;

		if (ctfscn == NULL || (dp = elf_getdata(ctfscn, NULL)) == NULL)
			die("%s does not contain .SUNW_ctf data\n", filename);

		cd.cd_ctfdata = dp->d_buf;
		cd.cd_ctflen = dp->d_size;

		/*
		 * If the sh_link field of the CTF section header is non-zero
		 * it indicates which section contains the symbol table that
		 * should be used. We default to the .symtab section if sh_link
		 * is zero or if there's an error reading the section header.
		 */
		if (gelf_getshdr(ctfscn, &ctfshdr) != NULL &&
		    ctfshdr.sh_link != 0) {
			symscn = elf_getscn(elf, ctfshdr.sh_link);
		} else {
			symscn = findelfscn(elf, &ehdr, ".symtab");
		}

		/* If we found a symbol table, find the corresponding strings */
		if (symscn != NULL) {
			GElf_Shdr shdr;
			Elf_Scn *symstrscn;

			if (gelf_getshdr(symscn, &shdr) != NULL) {
				symstrscn = elf_getscn(elf, shdr.sh_link);

				cd.cd_nsyms = shdr.sh_size / shdr.sh_entsize;
				cd.cd_symdata = elf_getdata(symscn, NULL);
				cd.cd_strdata = elf_getdata(symstrscn, NULL);
			}
		}
	} else {
		struct stat st;

		if (fstat(fd, &st) == -1)
			die("failed to fstat %s", filename);

		cd.cd_ctflen = st.st_size;
		cd.cd_ctfdata = mmap(NULL, cd.cd_ctflen, PROT_READ,
		    MAP_PRIVATE, fd, 0);
		if (cd.cd_ctfdata == MAP_FAILED)
			die("failed to mmap %s", filename);
	}

	/*
	 * Get a pointer to the CTF data buffer and interpret the first portion
	 * as a ctf_header_t.  Validate the magic number and size.
	 */

	if (cd.cd_ctflen < sizeof (ctf_preamble_t))
		die("%s does not contain a CTF preamble\n", filename);

	/* LINTED - pointer alignment */
	pp = (const ctf_preamble_t *)cd.cd_ctfdata;

	if (pp->ctp_magic != CTF_MAGIC)
		die("%s does not appear to contain CTF data\n", filename);

	if (pp->ctp_version == CTF_VERSION) {
		/* LINTED - pointer alignment */
		hp = (ctf_header_t *)cd.cd_ctfdata;
		cd.cd_ctfdata = (caddr_t)cd.cd_ctfdata + sizeof (ctf_header_t);

		if (cd.cd_ctflen < sizeof (ctf_header_t)) {
			die("%s does not contain a v%d CTF header\n", filename,
			    CTF_VERSION);
		}

	} else {
		die("%s contains unsupported CTF version %d\n", filename,
		    pp->ctp_version);
	}

	/*
	 * If the data buffer is compressed, then malloc a buffer large enough
	 * to hold the decompressed data, and use zlib to decompress it.
	 */
	if (hp->cth_flags & CTF_F_COMPRESS) {
		z_stream zstr;
		void *buf;
		int rc;

		if ((buf = malloc(hp->cth_stroff + hp->cth_strlen)) == NULL)
			die("failed to allocate decompression buffer");

		bzero(&zstr, sizeof (z_stream));
		zstr.next_in = (void *)cd.cd_ctfdata;
		zstr.avail_in = cd.cd_ctflen;
		zstr.next_out = buf;
		zstr.avail_out = hp->cth_stroff + hp->cth_strlen;

		if ((rc = inflateInit(&zstr)) != Z_OK)
			die("failed to initialize zlib: %s\n", zError(rc));

		if ((rc = inflate(&zstr, Z_FINISH)) != Z_STREAM_END)
			die("failed to decompress CTF data: %s\n", zError(rc));

		if ((rc = inflateEnd(&zstr)) != Z_OK)
			die("failed to finish decompression: %s\n", zError(rc));

		if (zstr.total_out != hp->cth_stroff + hp->cth_strlen)
			die("CTF data is corrupt -- short decompression\n");

		cd.cd_ctfdata = buf;
		cd.cd_ctflen = hp->cth_stroff + hp->cth_strlen;
	}

	if (flags & F_HDR)
		error |= print_header(hp, &cd);
	if (flags & (F_LABEL))
		error |= print_labeltable(hp, &cd);
	if (flags & (F_DATA | F_STATS))
		error |= read_data(hp, &cd);
	if (flags & (F_FUNC | F_STATS))
		error |= read_funcs(hp, &cd);
	if (flags & (F_TYPES | F_STATS))
		error |= read_types(hp, &cd);
	if (flags & (F_STR | F_STATS))
		error |= read_strtab(hp, &cd);
	if (flags & F_STATS)
		error |= print_stats();

	/*
	 * If the -u option is specified, write the uncompressed CTF data to a
	 * raw CTF file.  CTF data can already be extracted compressed by
	 * applying elfdump -w -N .SUNW_ctf to an ELF file, so we don't bother.
	 */
	if (ufile != NULL) {
		ctf_header_t h;

		bcopy(hp, &h, sizeof (h));
		h.cth_flags &= ~CTF_F_COMPRESS;

		if ((ufd = open(ufile, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0 ||
		    write(ufd, &h, sizeof (h)) != sizeof (h) ||
		    write(ufd, cd.cd_ctfdata, cd.cd_ctflen) != cd.cd_ctflen) {
			warn("failed to write CTF data to '%s'", ufile);
			error |= E_ERROR;
		}

		(void) close(ufd);
	}

	if (elf != NULL)
		(void) elf_end(elf);

	(void) close(fd);
	return (error);
}
示例#29
0
void
AsxTokenizer::move_next ()
{
	char c;

	while ((c = read_char ()) != -1) {

		if (in_data) {
			bool entirely_whitespace;
			current_token->set_type (TOKEN_DATA);
			current_token->set_value (read_data (c, entirely_whitespace));
			current_token->set_entirely_whitespace (entirely_whitespace);
			return;
		}

		if (c == OP_OPEN_ELEMENT) {
			if (is_comment_open (c)) {
				read_comment ();
				continue;
			}
			current_token->set_type (TOKEN_OPEN_ELEMENT);
			current_token->set_value (NULL);
			in_data = false;
			return;
		}

		if (c == OP_CLOSE_ELEMENT) {
			current_token->set_type (TOKEN_CLOSE_ELEMENT);
			current_token->set_value (NULL);
			in_data = true;
			return;
		}

		if (c == OP_ASSIGNMENT) {
			current_token->set_type (TOKEN_ASSIGNMENT);
			current_token->set_value (NULL);
			return;
		}

		if (c == OP_SLASH) {
			current_token->set_type (TOKEN_SLASH);
			current_token->set_value (NULL);
			return;
		}

		if (g_ascii_isspace (c)) {
			current_token->set_type (TOKEN_WHITESPACE);
			current_token->set_value (NULL);
			return;
		}

		if (is_quote_char (c)) {
			current_token->set_type (TOKEN_QUOTED_STRING);
			current_token->set_value (read_quoted_string (c));
			return;
		}

		if (is_name_char (c)) {
			current_token->set_type (TOKEN_NAME);
			current_token->set_value (read_name (c));
			return;
		}
	}

	current_token->set_type (TOKEN_EOF);
	current_token->set_value (NULL);
}
示例#30
0
int main(int argc, char* argv[]) {

	
	

	// read input file
	unsigned long n;
	int* data;


	// validate input
	if(argc < 2) {
		fprintf(stderr, "Usage: %s filename [numprocs=8]\n", argv[0]);
		return -1;
	}
	
	
	int p;
	if( argc >= 3 ) {
		sscanf(argv[2], "%d", &p);
	}
	if(p < 1 || p > 8) {
		p = 8;
	}
	
	omp_set_num_threads(p);
	log(LOG_DEBUG, "p=%i\n", p);
	
	
	read_data(argv[1], &data, &n);

	unsigned long partition_size = n / p;
	
	double total_time = get_timeofday();

	// sort
	
	{
	sort_task_t sort_task;
	
	
	int r;
	#pragma omp parallel for private(sort_task)
	for(r = 0; r < p; r++) {
		sort_task.task_id = r;
		sort_task.n = partition_size;
		sort_task.data = data;
		sort_task.start = r*partition_size;
		
		sort_thread_main( &sort_task );
	}
	
	}
	
	// merge
	{
	int nodes;
	for(nodes = p / 2; nodes > 0; nodes /= 2, partition_size *= 2) {
		
		merge_task_t merge_task;
		
		int r;
		#pragma omp parallel for private(merge_task)
		for(r = 0; r < nodes; r++) {
			merge_task.task_id = r;
			merge_task.n = partition_size;
			merge_task.data = data;
			merge_task.start_left = (2*r) * partition_size;
			merge_task.start_right = (2*r + 1) * partition_size;
		
			int* temp = (int*)malloc( 2*partition_size*sizeof(int) );
		
			merge_task.result = temp;
			
			merge_thread_main( &merge_task );


			memcpy( merge_task.data + merge_task.start_left, merge_task.result, 2*merge_task.n*sizeof(int) );
			free( merge_task.result );
			
			
		}
		
		#pragma omp barrier
		
		
	}
	}
	
	total_time = get_timeofday() - total_time;
	
	printf(TIME_OUTPUT, total_time, p);
	
	// display
	{
	unsigned long i;
	for(i = 0; i < n; i++) {
		printf("%i ", data[i]);
	}
	printf("\n");
	}
}