示例#1
0
文件: psort.c 项目: BWK/os161
static
void
dovalidate(void)
{
	const char *name;
	int fd, i, mykeys, keys_done, keys_to_do;
	int key, smallest, largest;

	name = PATH_SORTED;
	fd = doopen(name, O_RDONLY, 0);

	mykeys = getmykeys();
	seekmyplace(name, fd);

	smallest = RANDOM_MAX;
	largest = 0;

	keys_done = 0;
	while (keys_done < mykeys) {
		keys_to_do = mykeys - keys_done;
		if (keys_to_do > WORKNUM) {
			keys_to_do = WORKNUM;
		}

		doexactread(name, fd, workspace, keys_to_do * sizeof(int));

		for (i=0; i<keys_to_do; i++) {
			key = workspace[i];

			if (key < 0) {
				complain("%s: found negative key", name);
				exit(1);
			}
			if (key == 0) {
				complain("%s: found zero key", name);
				exit(1);
			}
			if (key >= RANDOM_MAX) {
				complain("%s: found too-large key", name);
				exit(1);
			}

			if (key < smallest) {
				smallest = key;
			}
			if (key > largest) {
				largest = key;
			}
		}

		keys_done += keys_to_do;
	}
	doclose(name, fd);

	name = validname(me);
	fd = doopen(name, O_WRONLY|O_CREAT|O_TRUNC, 0664);
	dowrite(name, fd, &smallest, sizeof(smallest));
	dowrite(name, fd, &largest, sizeof(largest));
	doclose(name, fd);
}
示例#2
0
void dotest()
{
  dowrite(0x0, 0xf00f00);

  dowrite(0x11110000, 0x00000000);
  dowrite(0x22220000, 0x00000000);
  dowrite(0x33330000, 0x00000000);
  dowrite(0x44440000, 0x00000000);

  doread(0x11110000, 0x00000000);
  doread(0x22220000, 0x00000000);
  doread(0x33330000, 0x00000000);
  doread(0x44440000, 0x00000000);


  dowrite(0x11110000, 0x11111111);
  dowrite(0x22220000, 0x22222222);
  dowrite(0x33330000, 0x33333333);
  dowrite(0x44440000, 0x44444444);

  doread(0x11110000, 0x11111111);
  doread(0x22220000, 0x00222222);
  doread(0x33330000, 0x00003333);
  doread(0x44440000, 0x00000044);


  dowrite(0x0, 0xdeadbeef);
  doread(0x0, 0xfeedface);
}
示例#3
0
static
void
filter_output(const char *buf, size_t len)
{
	size_t pos, start;
	bool inesc = false;
	bool inquote = false;
	char quote = '\0';

	start = 0;
	for (pos = 0; pos < len - 1; pos++) {
		if (!inquote && buf[pos] == '/' && buf[pos+1] == '*') {
			if (!incomment) {
				if (pos > start) {
					dowrite(buf + start, pos - start);
				}
				start = pos;
				pos += 2;
				incomment = true;
				/* cancel out the loop's pos++ */
				pos--;
				continue;
			}
		} else if (buf[pos] == '*' && buf[pos+1] == '/') {
			if (incomment) {
				pos += 2;
				if (mode.output_retain_comments) {
					dowrite(buf + start, pos - start);
				}
				start = pos;
				incomment = false;
				/* cancel out the loop's pos++ */
				pos--;
				continue;
			}
		}

		if (incomment) {
			/* nothing */
		} else if (inesc) {
			inesc = false;
		} else if (buf[pos] == '\\') {
			inesc = true;
		} else if (!inquote && (buf[pos] == '"' || buf[pos] == '\'')) {
			inquote = true;
			quote = buf[pos];
		} else if (inquote && buf[pos] == quote) {
			inquote = false;
		}
	}
	pos++;

	if (pos > start) {
		if (!incomment || mode.output_retain_comments) {
			dowrite(buf + start, pos - start);
		}
	}
}
示例#4
0
static
void
readfile(const char *name)
{
	int fd, closefd;
	struct indexentry x;
	size_t len, remaining, here;
	const char *s, *t;

	if (name == NULL || !strcmp(name, "-")) {
		fd = STDIN_FILENO;
		closefd = -1;
	}
	else {
		fd = open(name, O_RDONLY);
		if (fd < 0) {
			err(1, "%s", name);
		}
		closefd = fd;
	}

	x.pos = 0;
	x.len = 0;
	while (1) {
		len = doread(fd, name, buf, sizeof(buf));
		if (len == 0) {
			break;
		}

		remaining = len;
		for (s = buf; s != NULL; s = t) {
			t = memchr(s, '\n', remaining);
			if (t != NULL) {
				t++;
				here = (t - s);
				x.len += here;
				remaining -= here;
				dowrite(indexfd, indexname, &x, sizeof(x));
				x.pos += x.len;
				x.len = 0;
			}
			else {
				x.len += remaining;
			}
		}
		dowrite(datafd, dataname, buf, len);
	}
	if (x.len > 0) {
		dowrite(indexfd, indexname, &x, sizeof(x));
	}

	if (closefd != -1) {
		close(closefd);
	}
}
示例#5
0
文件: sysfile.c 项目: 0intro/vx32
long
syspwrite(uint32 *arg)
{
	vlong v;

	// Plan 9 VX replaced dodgy varargs code
	v = *(vlong*)&arg[3];

	if(v == ~0ULL)
		return dowrite(arg, nil);

	return dowrite(arg, &v);
}
示例#6
0
void justice_writer(int num, int duration) {
    pthread_mutex_lock(&new_op_mutex);
    pthread_mutex_lock(&writer_mutex);
    dowrite(num, duration);
    pthread_mutex_unlock(&writer_mutex);
    pthread_mutex_unlock(&new_op_mutex);
}
示例#7
0
unsigned QWrite( f_handle file, void *buffer, unsigned len, char *name )
/**********************************************************************/
/* write from far memory */
{
    int     h;
    char    rc_buff[RESOURCE_MAX_SIZE];

    if( len == 0 )
        return( 0 );

#ifdef _INT_DEBUG
    {
        unsigned long pos = QPos(file);

        if( pos <= SpyWrite && SpyWrite <= pos + len && file == Root->outfile->handle) {
            DEBUG((DBG_ALWAYS, "About to write to %s (handle %d) %d bytes at position %d:", name, file, len, pos));
            PrintMemDump(buffer, len, DUMP_BYTE);
        }
    }
#endif

    CheckBreak();
    h = dowrite( file, buffer, len );
    if( name != NULL ) {
        if( h == -1 ) {
            LnkMsg( ERR+MSG_IO_PROBLEM, "12", name, strerror( errno ) );
        } else if( (unsigned)h != len ) {
            Msg_Get( MSG_IOERRLIST_7, rc_buff );
            LnkMsg( (FTL+MSG_IO_PROBLEM) & ~OUT_MAP, "12", name, rc_buff );
        }
    }
    return( h );
}
VOID png_write(struct RecorderData *data, APTR fh, APTR argb, ULONG modulo, ULONG width, ULONG height, ULONG dupcount)
{
	struct png_header ihdr;
	ULONG length, length2;
	UBYTE *buffer;

	buffer = data->writebuffer;

	ihdr.width = width;
	ihdr.height = height;
	ihdr.depth = 8;
	ihdr.colortype = 2; /* RGB */
	ihdr.compression = 0;
	ihdr.filter = 0;
	ihdr.interlaced = 0;

	length = write_chunk(buffer, sizeof(ihdr), LE_SWAPLONG_C(MAKE_ID('I','H','D','R')), &ihdr);
	length2 = png_encode(&buffer[length], data->writebuffersize - length - 8, argb, modulo, width, height);

	if (length2)
	{
		static const struct png_iend iend = { { 0, LE_SWAPLONG_C(MAKE_ID('I','E','N','D')) }, 0xae426082 };
		ULONG i;

		length += length2;

		qcopy((APTR)&iend, &buffer[length], sizeof(iend));

		for (i = 0; i < dupcount; i++)
		{
			dowrite(fh, buffer, length);
		}
	}
}
示例#9
0
static
void
writeheader(struct disk_data *dd, const char *filename, uint32_t configsectors)
{
    off_t fsize;
    char buf[HEADERSIZE];

    memset(buf, 0, HEADERSIZE);
    strcpy(buf, HEADER_MESSAGE);

    if (dowrite(dd->dd_fd, 0, buf, HEADERSIZE, dd->dd_paranoid)) {
        msg("disk: slot %d: %s: Write of header: %s",
            dd->dd_slot, filename, strerror(errno));
        die();
    }

    fsize = configsectors;
    fsize *= SECTSIZE;
    fsize += HEADERSIZE;

    if (ftruncate(dd->dd_fd, fsize)) {
        msg("disk: slot %d: %s: ftruncate: %s",
            dd->dd_slot, filename, strerror(errno));
        die();
    }
}
示例#10
0
static uint32_t store(int fd, const unsigned char *data, ssize_t datasize) {
	z_stream strm;
	memset(&strm, 0, sizeof(strm));

	unsigned char outbuf[4096];

	uint32_t complen = 0;

	strm.next_in = const_cast<unsigned char*>(data);
	strm.avail_in = datasize;

	deflateInit2(&strm, 7, Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
	for (;;) {
		strm.next_out = outbuf;
		strm.avail_out = sizeof(outbuf);
		int ret = deflate(&strm, Z_FINISH);
		int have = sizeof(outbuf) - strm.avail_out;
		complen += have;
		dowrite(fd, outbuf, have);

		if (ret == Z_STREAM_END) break;
		if (ret != Z_OK) {
			std::cerr << "deflate failed: " << ret << "\n";
			exit(1);
		}
	}
	deflateEnd(&strm);

	return complen;
}
示例#11
0
/*
 *  this just proxies what the factotum tells it to.
 */
AuthInfo*
authproto(Session *s, Fid *f, AuthRpc *rpc, AuthGetkey *getkey, char *params)
{
	char *buf;
	int m, n, ret;
	AuthInfo *a;
	char oerr[ERRMAX];

	rerrstr(oerr, sizeof oerr);
	werrstr("UNKNOWN AUTH ERROR");

	if(dorpc(rpc, "start", params, strlen(params), getkey) != ARok){
		werrstr("fauth_proxy start: %r");
		return nil;
	}

	buf = malloc(AuthRpcMax);
	if(buf == nil)
		return nil;
	for(;;){
		switch(dorpc(rpc, "read", nil, 0, getkey)){
		case ARdone:
			free(buf);
			a = auth_getinfo(rpc);
			errstr(oerr, sizeof oerr);	/* no error, restore whatever was there */
			return a;
		case ARok:
			if(dowrite(s, f, rpc->arg, rpc->narg) != rpc->narg){
				werrstr("auth_proxy write fd: %r");
				goto Error;
			}
			break;
		case ARphase:
			n = 0;
			memset(buf, 0, AuthRpcMax);
			while((ret = dorpc(rpc, "write", buf, n, getkey)) == ARtoosmall){
				if(atoi(rpc->arg) > AuthRpcMax)
					break;
				m = doread(s, f, buf+n, atoi(rpc->arg)-n);
				if(m <= 0){
					if(m == 0)
						werrstr("auth_proxy short read: %s", buf);
					goto Error;
				}
				n += m;
			}
			if(ret != ARok){
				werrstr("auth_proxy rpc write: %s: %r", buf);
				goto Error;
			}
			break;
		default:
			werrstr("auth_proxy rpc: %r");
			goto Error;
		}
	}
Error:
	free(buf);
	return nil;
}
示例#12
0
static
void
dumpdata(void)
{
	struct indexentry x;
	off_t indexsize, pos, done;
	size_t amount, len;

	indexsize = dolseek(indexfd, indexname, 0, SEEK_CUR);
	pos = indexsize;
	assert(pos % sizeof(x) == 0);
	while (pos != 0) {
		pos -= sizeof(x);
		dolseek(indexfd, indexname, pos, SEEK_SET);

		len = doread(indexfd, indexname, &x, sizeof(x));
		if (len != sizeof(x)) {
			errx(1, "%s: read: Unexpected EOF", indexname);
		}
		dolseek(datafd, dataname, x.pos, SEEK_SET);

		for (done = 0; done < x.len; done += amount) {
			amount = sizeof(buf);
			if ((off_t)amount > x.len - done) {
				amount = x.len - done;
			}
			len = doread(datafd, dataname, buf, amount);
			if (len != amount) {
				errx(1, "%s: read: Unexpected short count"
				     " %zu of %zu", dataname, len, amount);
			}
			dowrite(STDOUT_FILENO, "stdout", buf, len);
		}
	}
}
示例#13
0
文件: fs.c 项目: 00001/plan9port
char*
rwrite(Fid *f)
{
	Ram *r;
	ulong off;
	int cnt;

	r = f->ram;
	if(dopermw(f->ram)==0)
		return Eperm;
	if(r->busy == 0)
		return Enotexist;
	off = rhdr.offset;
	if(r->perm & DMAPPEND)
		off = r->ndata;
	cnt = rhdr.count;
	if(r->qid.type & QTDIR)
		return "file is a directory";
	if(off > 100*1024*1024)		/* sanity check */
		return "write too big";
	dowrite(r, rhdr.data, off, cnt);
	r->qid.vers++;
	r->mtime = time(0);
	thdr.count = cnt;
	return 0;
}
示例#14
0
文件: psort.c 项目: BWK/os161
static
void
sortbins(void)
{
	const char *name;
	int i, fd;
	off_t binsize;

	for (i=0; i<numprocs; i++) {
		name = binname(me, i);
		binsize = getsize(name);
		if (binsize % sizeof(int) != 0) {
			complainx("%s: bin size %ld no good", name,
				  (long) binsize);
			exit(1);
		}
		if (binsize > (off_t) sizeof(workspace)) {
			complainx("proc %d: %s: bin too large", me, name);
			exit(1);
		}

		fd = doopen(name, O_RDWR, 0);
		doexactread(name, fd, workspace, binsize);

		sortints(workspace, binsize/sizeof(int));

		dolseek(name, fd, 0, SEEK_SET);
		dowrite(name, fd, workspace, binsize);
		doclose(name, fd);
	}
}
示例#15
0
/* parse arguments of write command */
int runwrite(int argc, char **argv){
  char *name, *rstr;
  int bulk, i, rnd, rnum, rv;
  name = NULL;
  rstr = NULL;
  bulk = rnd = FALSE;
  rnum = 0;
  for(i = 2; i < argc; i++){
    if(!name && argv[i][0] == '-'){
      if(!name && !strcmp(argv[i], "-bulk"))
        bulk = TRUE;
      else if(!name && !strcmp(argv[i], "-rnd"))
        rnd = TRUE;
      else
        usage();
    } else if(!name){
      name = argv[i];
    } else if(!rstr){
      rstr = argv[i];
    } else {
      usage();
    }
  }
  if(!name || !rstr)
    usage();
  rnum = atoi(rstr);
  if(rnum < 1)
    usage();
  rv = dowrite(name, rnum, bulk, rnd);
  return rv;
}
示例#16
0
文件: frag.c 项目: Apekhsha/glusterfs
/*
 * @offset, @count: random values from [0, max_file_size - 1]
 */
static int frag_write(struct frag_ctx *ctx, off_t offset, size_t count)
{
	int ret;
	struct stat test_stbuf;
	struct stat good_stbuf;

	if (offset + count > ctx->max_file_size)
		offset = offset / 2;
	if (offset + count > ctx->max_file_size)
		count = count / 2;

	if (fstat(ctx->test_fd, &test_stbuf)) {
		fprintf(stderr, "WRITE: fstat of test file failed\n");
		return -1;
	}
	if (offset > test_stbuf.st_size)
		printf("writing hole\n");

	ret = dowrite(ctx->test_fd, offset, count, ctx->content);
	if (ret < 0 || ret != count){
		fprintf(stderr, "WRITE: failed to write test file\n");
		return -1;
	}
	ret = dowrite(ctx->good_fd, offset, count, ctx->content);
	if (ret < 0 || ret != count) {
		fprintf(stderr, "WRITE: failed to write test file\n");
		return -1;
	}	
	if (fstat(ctx->test_fd, &test_stbuf)) {
                fprintf(stderr, "WRITE: fstat of test file failed\n");
		return -1;
	}
	if (fstat(ctx->good_fd, &good_stbuf)) {
                fprintf(stderr, "WRITE: fstat of good file failed\n");
		return -1;
	}
	if (test_stbuf.st_size != good_stbuf.st_size) {
		fprintf(stderr,
			"READ: Bad file size %d (expected %d)\n",
			(int)test_stbuf.st_size,
			(int)good_stbuf.st_size);
		return -1;
	}
	return 0;
}
示例#17
0
static
void
writeheader(const char *file, int fd)
{
    char buf[SECTORSIZE];

    memset(buf, 0, sizeof(buf));
    strcpy(buf, HEADERSTRING);

    dolseek(file, fd, 0, SEEK_SET);
    dowrite(file, fd, buf, sizeof(buf));
}
示例#18
0
文件: psort.c 项目: BWK/os161
static
void
bin(void)
{
	int infd, outfds[numprocs];
	const char *name;
	int i, mykeys, keys_done, keys_to_do;
	int key, pivot, binnum;

	infd = doopen(PATH_KEYS, O_RDONLY, 0);

	mykeys = getmykeys();
	seekmyplace(PATH_KEYS, infd);

	for (i=0; i<numprocs; i++) {
		name = binname(me, i);
		outfds[i] = doopen(name, O_WRONLY|O_CREAT|O_TRUNC, 0664);
	}

	pivot = (RANDOM_MAX / numprocs);

	keys_done = 0;
	while (keys_done < mykeys) {
		keys_to_do = mykeys - keys_done;
		if (keys_to_do > WORKNUM) {
			keys_to_do = WORKNUM;
		}

		doexactread(PATH_KEYS, infd, workspace,
			    keys_to_do * sizeof(int));

		for (i=0; i<keys_to_do; i++) {
			key = workspace[i];

			binnum = key / pivot;
			if (key <= 0) {
				complainx("proc %d: garbage key %d", me, key);
				key = 0;
			}
			assert(binnum >= 0);
			assert(binnum < numprocs);
			dowrite("bin", outfds[binnum], &key, sizeof(key));
		}

		keys_done += keys_to_do;
	}
	doclose(PATH_KEYS, infd);

	for (i=0; i<numprocs; i++) {
		doclose(binname(me, i), outfds[i]);
	}
}
示例#19
0
/**
 * _network_writeq_add(Q, buf, buflen, timeo, callback, cookie, abstimeo):
 * Add a buffer write to the specified write queue.  The callback function
 * will be called when the write is finished, fails, or is cancelled.
 * If ${abstimeo} is zero, the timeout is relative to when the buffer in
 * question starts to be written (i.e., when the previous buffered write
 * finishes); otherwise, the timeout is relative to the present time.  If
 * ${buflen} is zero, the callback will be performed, at the appropriate
 * point, with a status of NETWORK_STATUS_ZEROBYTE.
 */
int
_network_writeq_add(NETWORK_WRITEQ * Q, const uint8_t * buf, size_t buflen,
    struct timeval * timeo, network_callback * callback, void * cookie,
    int abstimeo)
{
	struct network_writeq_buf * QB;
	struct network_writeq_buf ** tailptr_old;
	struct network_writeq_buf * head_old;

	/* Wrap parameters into a structure. */
	if ((QB = malloc(sizeof(struct network_writeq_buf))) == NULL)
		goto err0;
	QB->buf = buf;
	QB->buflen = buflen;
	memcpy(&QB->timeo, timeo, sizeof(struct timeval));
	QB->abstimeo = abstimeo;
	QB->callback = callback;
	QB->cookie = cookie;
	QB->next = NULL;

	/* Compute absolute time if appropriate. */
	if (abstimeo && tvmath_addctime(&QB->timeo))
		goto err1;

	/* Add this to the write queue. */
	head_old = Q->head;
	tailptr_old = Q->tailptr;
	*Q->tailptr = QB;
	Q->tailptr = &QB->next;

	/* If the queue head was NULL, we need to kick off the writing. */
	if (head_old == NULL) {
		/* Cork the socket so that we don't send small packets. */
		if (network_cork(Q->fd))
			goto err2;

		if (dowrite(Q))
			goto err2;
	}

	/* Success! */
	return (0);

err2:
	Q->tailptr = tailptr_old;
	*Q->tailptr = NULL;
err1:
	free(QB);
err0:
	/* Failure! */
	return (-1);
}
示例#20
0
static
int
disk_writesector(struct disk_data *dd)
{
    off_t offset = dd->dd_sect;
    offset *= SECTSIZE;
    offset += HEADERSIZE;

    g_stats.s_wsects++;

    return dowrite(dd->dd_fd, offset, dd->dd_buf, SECTSIZE,
                   dd->dd_paranoid);
}
示例#21
0
/**
 * callback_bufdone(cookie, status):
 * Call the upstream callback for the buffer at the head of the write queue
 * ${cookie}, remove it from the queue, and write the next buffer.
 */
static int
callback_bufdone(void * cookie, int status)
{
	struct network_writeq_internal * Q = cookie;
	struct network_writeq_buf * head_old;
	int rc;

	/* Unlink the current buffer from the queue. */
	head_old = Q->head;
	Q->head = head_old->next;

	/* Update tail pointer if necessary. */
	if (Q->tailptr == &head_old->next)
		Q->tailptr = &Q->head;

	/*
	 * A callback of NETWORK_STATUS_CLOSED in response to an attempt to
	 * write zero bytes is really a NETWORK_STATUS_ZEROBYTE.
	 */
	if ((status == NETWORK_STATUS_CLOSED) && (head_old->buflen == 0))
		status = NETWORK_STATUS_ZEROBYTE;

	/*
	 * If there's another buffer waiting to be written, register it to
	 * be sent.  If not and we're not handling an error, uncork the
	 * socket.
	 */
	if (Q->head != NULL) {
		if (dowrite(Q))
			goto err1;
	} else {
		if ((status == NETWORK_STATUS_OK) && network_uncork(Q->fd))
			status = NETWORK_STATUS_ERR;
	}

	/* Call the upstream callback. */
	rc = (head_old->callback)(head_old->cookie, status);

	/* Free the write parameters structure. */
	free(head_old);

	/* Return value from callback. */
	return (rc);

err1:
	(head_old->callback)(head_old->cookie, status);
	free(head_old);

	/* Failure! */
	return (-1);
}
示例#22
0
int main() {

  try {
    initialize();
    dowrite();
    doread();
    terminateit();
  }
  catch (SQLException &e) {
    cout << "SQL exception :" << e.getMessage() << endl;
  }

  return 0;
}
示例#23
0
文件: psort.c 项目: BWK/os161
static
void
genkeys_sub(void)
{
	int fd, i, mykeys, keys_done, keys_to_do, value;

	fd = doopen(PATH_KEYS, O_WRONLY, 0);

	mykeys = getmykeys();
	seekmyplace(PATH_KEYS, fd);

	srandom(seeds[me]);
	keys_done = 0;
	while (keys_done < mykeys) {
		keys_to_do = mykeys - keys_done;
		if (keys_to_do > WORKNUM) {
			keys_to_do = WORKNUM;
		}

		for (i=0; i<keys_to_do; i++) {
			value = random();

			// check bounds of value
			assert(value >= 0);
			assert(value <= RANDOM_MAX);

			// do not allow the value to be zero or RANDOM_MAX
			while (value == 0 || value == RANDOM_MAX) {
				value = random();
			}

			workspace[i] = value;
		}

		dowrite(PATH_KEYS, fd, workspace, keys_to_do*sizeof(int));
		keys_done += keys_to_do;
	}

	doclose(PATH_KEYS, fd);
}
示例#24
0
/* parse arguments of write command */
int runwrite(int argc, char **argv){
  char *name, *rstr;
  int i, rnum, rv;
  name = NULL;
  rstr = NULL;
  rnum = 0;
  for(i = 2; i < argc; i++){
    if(!name && argv[i][0] == '-'){
      usage();
    } else if(!name){
      name = argv[i];
    } else if(!rstr){
      rstr = argv[i];
    } else {
      usage();
    }
  }
  if(!name || !rstr) usage();
  rnum = atoi(rstr);
  if(rnum < 1) usage();
  rv = dowrite(name, rnum);
  return rv;
}
示例#25
0
int main(int argc, char **argv) {
	if (argc < 2) {
		std::cerr << "syntax: " << argv[0] << " filename\n";
		exit(1);
	}

	std::string error;

	std::string inFilename = argv[1];
	std::shared_ptr<NormalFile> plainfile(new MMappedFile(inFilename.c_str(), error));
	if (!plainfile->valid()) {
		std::cerr << "couldn't open file: " << error << "\n";
		exit(1);
	}
	std::shared_ptr<IndexedDeflateFile> file(new IndexedDeflateFile(plainfile, error));
	if (!file->valid()) {
		std::cerr << "couldn't open archive: " << error << "\n";
		exit(1);
	}

	std::cerr << "Filesize: " << file->filesize() << "\n";

	FileReader reader(file);
	while (reader.length() > 0) {
		int want = std::min<int64_t>(4096, reader.length());
		const unsigned char *data;
		ssize_t datasize;
		if (!reader.read(want, data, datasize)) {
			std::cerr << "read failed: " << reader.lastError() << "\n";
			exit(1);
		}
		dowrite(1, data, datasize);
	}

	return 0;
}
示例#26
0
int main(int argc, char **argv)
{
	char *value, *subs;
	int i;
	char *subopts[] = {
#define SUB_VAL				0
		"val",
#define SUB_YUV_MODE			1
		"mode",
#define SUB_DIR				2
		"dir",

		NULL
	};

	int fd = -1;

	/* bitfield for OptSetCodec */

	/* command args */
	const char *device = "/dev/video0";	/* -d device */
	int ch;
	int yuv_mode = 0;
	unsigned short gpio_out = 0x0;	/* GPIO output data */
	unsigned short gpio_dir = 0x0;	/* GPIO direction bits */
	int gpio_set_dir = 0;
	int passthrough = 0;
	long audio_mute = 0;
	long stereo_mode = 0;
	long bilingual_mode = 0;
	int debug_level = 0;
	__u32 reset = 0;
	int new_debug_level, gdebug_level;
	double timestamp;
	char *ptsstr;
	char short_options[26 * 2 * 2 + 1];

	if (argc == 1) {
		usage();
		return 0;
	}
	while (1) {
		int option_index = 0;
		int idx = 0;

		for (i = 0; long_options[i].name; i++) {
			if (!isalpha(long_options[i].val))
				continue;
			short_options[idx++] = long_options[i].val;
			if (long_options[i].has_arg == required_argument)
				short_options[idx++] = ':';
		}
		short_options[idx] = 0;
		ch = getopt_long(argc, argv, short_options,
				 long_options, &option_index);
		if (ch == -1)
			break;

		options[(int)ch] = 1;
		switch (ch) {
		case OptSetYuvMode:
		    {
			subs = optarg;
			while (*subs != '\0') {
				switch (getsubopt(&subs, subopts, &value)) {
				case SUB_YUV_MODE:
					if (value == NULL) {
						fprintf(stderr,
							"No value given to suboption <mode>\n");
						usage();
						return 1;

					}
					yuv_mode = strtol(value, 0L, 0);
					if (yuv_mode < 0 || yuv_mode > 3) {
						fprintf(stderr, "invalid yuv mode\n");
						return 1;
					}
					break;
				}
			}
		    }
		    break;
		case OptHelp:
			usage();
			return 0;
		case OptSetDebugLevel:{
			debug_level = strtol(optarg, 0L, 0);
			break;
		}
		case OptSetDevice:
			device = optarg;
			if (device[0] >= '0' && device[0] <= '9' && strlen(device) <= 3) {
				static char newdev[20];

				sprintf(newdev, "/dev/video%s", device);
				device = newdev;
			}
			break;
		case OptReset:
			reset = strtol(optarg, 0L, 0);
			break;
		case OptPassThrough:
			passthrough = strtol(optarg, 0L, 0);
			break;
		case OptSetAudioMute:
			audio_mute = strtol(optarg, 0L, 0);
			break;
		case OptSetStereoMode:
			stereo_mode = strtol(optarg, 0L, 0);
			break;
		case OptSetBilingualMode:
			bilingual_mode = strtol(optarg, 0L, 0);
			break;
		case OptSetGPIO:
			subs = optarg;
			while (*subs != '\0') {
				switch (getsubopt(&subs, subopts, &value)) {
				case SUB_DIR:
					if (value == NULL) {
						fprintf(stderr,
							"No value given to suboption <dir>\n");
						usage();
						exit(1);
					}
					gpio_dir = strtol(value, 0L, 0);
					gpio_set_dir = 1;
					break;
				case SUB_VAL:
					if (value == NULL) {
						fprintf(stderr,
							"No value given to suboption <val>\n");
						usage();
						exit(1);
					}
					gpio_out = (unsigned short)strtol(value, 0L, 0);
					break;
				default:
					fprintf(stderr,
						"Invalid suboptions specified\n");
					usage();
					exit(1);
					break;
				}
			}
			break;
		case ':':
			fprintf(stderr, "Option `%s' requires a value\n",
				argv[optind]);
			usage();
			return 1;
		case '?':
			fprintf(stderr, "Unknown argument `%s'\n",
				argv[optind]);
			usage();
			return 1;
		}
	}
	if (optind < argc) {
		printf("unknown arguments: ");
		while (optind < argc)
			printf("%s ", argv[optind++]);
		printf("\n");
		usage();
		return 1;
	}

	fd = open(device, O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "Failed to open %s: %s\n", device,
			strerror(errno));
		exit(1);
	}

	/* Setting Opts */

	if (options[OptFrameSync]) {
		printf("ioctl: VIDEO_GET_EVENT\n");

		for (;;) {
			struct video_event ev;
			int fps = 30;
			v4l2_std_id std;

			if (ioctl(fd, VIDIOC_G_STD, &std) == 0)
				fps = (std & V4L2_STD_525_60) ? 30 : 25;
			if (ioctl(fd, VIDEO_GET_EVENT, &ev) < 0) {
				fprintf(stderr, "ioctl: VIDEO_GET_EVENT failed\n");
				break;
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
			} else if (ev.timestamp.tv_sec == 0 && ev.timestamp.tv_nsec == 0) {
#else
			} else if (ev.timestamp == 0) {
#endif
				unsigned long long pts = 0, frame = 0;
				struct timeval tv;
				gettimeofday(&tv, NULL);
				timestamp =
				    (double)tv.tv_sec +
				    ((double)tv.tv_usec / 1000000.0);

				ioctl(fd, VIDEO_GET_PTS, &pts);
				ioctl(fd, VIDEO_GET_FRAME_COUNT, &frame);
				ptsstr = pts_to_string(pts, fps);
				printf("%10.6f: pts %-20s, %lld frames\n",
				     timestamp, ptsstr, frame);
			}
		}
	}

	if (options[OptSetGPIO]) {
		struct v4l2_dbg_register reg;

		reg.match.type = V4L2_CHIP_MATCH_HOST;
		reg.match.addr = 0;
		reg.reg = IVTV_REG_GPIO_DIR_OFFSET;
		reg.val = gpio_dir;
		if (gpio_set_dir && doioctl(fd, VIDIOC_DBG_S_REGISTER, &reg,
			"VIDIOC_DBG_S_REGISTER") == 0)
			printf("GPIO dir set to 0x%04llx\n", reg.val);
		reg.reg = IVTV_REG_GPIO_OUT_OFFSET;
		reg.val = gpio_out;
		if (doioctl(fd, VIDIOC_DBG_S_REGISTER, &reg,
			"VIDIOC_DBG_S_REGISTER") == 0)
			printf("GPIO out set to 0x%04llx\n", reg.val);
	}

	if (options[OptListGPIO]) {
		struct v4l2_dbg_register reg;

		reg.match.type = V4L2_CHIP_MATCH_HOST;
		reg.match.addr = 0;
		reg.reg = IVTV_REG_GPIO_IN_OFFSET;
		if (ioctl(fd, VIDIOC_DBG_G_REGISTER, &reg) == 0)
			printf("GPIO in:  0x%04llx\n", reg.val);
		reg.reg = IVTV_REG_GPIO_DIR_OFFSET;
		if (ioctl(fd, VIDIOC_DBG_G_REGISTER, &reg) == 0)
			printf("GPIO dir: 0x%04llx\n", reg.val);
		reg.reg = IVTV_REG_GPIO_OUT_OFFSET;
		if (ioctl(fd, VIDIOC_DBG_G_REGISTER, &reg) == 0)
			printf("GPIO out: 0x%04llx\n", reg.val);
	}

	if (options[OptSetDebugLevel]) {
		char buf[20];
		new_debug_level = debug_level;

		sprintf(buf, "%d", debug_level);
		if (dowrite(buf, "/sys/module/ivtv/parameters/debug") == 0) {
			printf(" set debug level: ");
			print_debug_mask(new_debug_level);
			printf("\n");
		}
	}

	if (options[OptGetDebugLevel]) {
		char *buf = doread("/sys/module/ivtv/parameters/debug");

		gdebug_level = 0;
		if (buf) {
			gdebug_level = atol(buf);
			printf(" debug level: ");
			print_debug_mask(gdebug_level);
			printf("\n");
		}
	}

	if (options[OptPassThrough]) {
		long source = passthrough ? VIDEO_SOURCE_DEMUX : VIDEO_SOURCE_MEMORY;

		doioctl(fd, VIDEO_SELECT_SOURCE, (void *)source,
				"IVTV_IOC_PASSTHROUGH");
	}

	if (options[OptSetAudioMute]) {
		doioctl(fd, AUDIO_SET_MUTE, (void *)audio_mute, "AUDIO_SET_MUTE");
	}

	if (options[OptSetStereoMode]) {
		doioctl(fd, AUDIO_CHANNEL_SELECT,
			(void *)stereo_mode, "AUDIO_CHANNEL_SELECT");
	}

	if (options[OptSetBilingualMode]) {
		doioctl(fd, AUDIO_BILINGUAL_CHANNEL_SELECT,
			(void *)bilingual_mode, "AUDIO_BILINGUAL_CHANNEL_SELECT");
	}

	if (options[OptReset])
		doioctl(fd, VIDIOC_INT_RESET, &reset, "VIDIOC_INT_RESET");

	if (options[OptSetYuvMode]) {
		struct ivtv_dma_frame frame;
		struct v4l2_format fmt;
		const enum v4l2_field map[4] = {
			V4L2_FIELD_INTERLACED_TB,
			V4L2_FIELD_INTERLACED_BT,
			V4L2_FIELD_NONE,
			V4L2_FIELD_ANY,
		};

		printf("set yuv mode\n");
		memset(&frame, 0, sizeof(frame));
		frame.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
		if (ioctl(fd, IVTV_IOC_DMA_FRAME, &frame) < 0) {
			fprintf(stderr, "Unable to switch to user DMA YUV mode\n");
			exit(1);
		}
		fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
		ioctl(fd, VIDIOC_G_FMT, &fmt);
		fmt.fmt.pix.field = map[yuv_mode];
		doioctl(fd, VIDIOC_S_FMT, &fmt, "VIDIOC_S_FMT");
	}

	if (options[OptGetYuvMode]) {
		struct ivtv_dma_frame frame;
		struct v4l2_format fmt;

		memset(&frame, 0, sizeof(frame));
		frame.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
		if (ioctl(fd, IVTV_IOC_DMA_FRAME, &frame) < 0) {
			fprintf(stderr, "Unable to switch to user DMA YUV mode\n");
			exit(1);
		}
		fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
		doioctl(fd, VIDIOC_G_FMT, &fmt, "VIDIOC_G_FMT");
		printf("Current yuv_mode %d %s\n", fmt.fmt.pix.field,
				field2s(fmt.fmt.pix.field));
	}

	close(fd);
	exit(app_result);
}
示例#27
0
void
hostlink(void)
{
	char *p, **argv;
	int c, i, w, n, argc, len;
	Hostobj *h;
	Biobuf *f;
	static char buf[64<<10];

	if(linkmode != LinkExternal || nerrors > 0)
		return;

	c = 0;
	p = extldflags;
	while(p != nil) {
		while(*p == ' ')
			p++;
		if(*p == '\0')
			break;
		c++;
		p = strchr(p + 1, ' ');
	}

	argv = malloc((13+nhostobj+nldflag+c)*sizeof argv[0]);
	argc = 0;
	if(extld == nil)
		extld = "gcc";
	argv[argc++] = extld;
	switch(thechar){
	case '8':
		argv[argc++] = "-m32";
		break;
	case '6':
		argv[argc++] = "-m64";
		break;
	case '5':
		argv[argc++] = "-marm";
		break;
	}
	if(!debug['s'] && !debug_s) {
		argv[argc++] = "-gdwarf-2"; 
	} else {
		argv[argc++] = "-s";
	}
	if(HEADTYPE == Hdarwin)
		argv[argc++] = "-Wl,-no_pie,-pagezero_size,4000000";
	if(HEADTYPE == Hopenbsd)
		argv[argc++] = "-Wl,-nopie";
	
	if(iself && AssumeGoldLinker)
		argv[argc++] = "-Wl,--rosegment";

	if(flag_shared) {
		argv[argc++] = "-Wl,-Bsymbolic";
		argv[argc++] = "-shared";
	}
	argv[argc++] = "-o";
	argv[argc++] = outfile;
	
	if(rpath)
		argv[argc++] = smprint("-Wl,-rpath,%s", rpath);

	// Force global symbols to be exported for dlopen, etc.
	if(iself)
		argv[argc++] = "-rdynamic";

	// already wrote main object file
	// copy host objects to temporary directory
	for(i=0; i<nhostobj; i++) {
		h = &hostobj[i];
		f = Bopen(h->file, OREAD);
		if(f == nil) {
			ctxt->cursym = S;
			diag("cannot reopen %s: %r", h->pn);
			errorexit();
		}
		Bseek(f, h->off, 0);
		p = smprint("%s/%06d.o", tmpdir, i);
		argv[argc++] = p;
		w = create(p, 1, 0775);
		if(w < 0) {
			ctxt->cursym = S;
			diag("cannot create %s: %r", p);
			errorexit();
		}
		len = h->len;
		while(len > 0 && (n = Bread(f, buf, sizeof buf)) > 0){
			if(n > len)
				n = len;
			dowrite(w, buf, n);
			len -= n;
		}
		if(close(w) < 0) {
			ctxt->cursym = S;
			diag("cannot write %s: %r", p);
			errorexit();
		}
		Bterm(f);
	}
	
	argv[argc++] = smprint("%s/go.o", tmpdir);
	for(i=0; i<nldflag; i++)
		argv[argc++] = ldflag[i];

	p = extldflags;
	while(p != nil) {
		while(*p == ' ')
			*p++ = '\0';
		if(*p == '\0')
			break;
		argv[argc++] = p;
		p = strchr(p + 1, ' ');
	}

	argv[argc] = nil;

	quotefmtinstall();
	if(debug['v']) {
		Bprint(&bso, "host link:");
		for(i=0; i<argc; i++)
			Bprint(&bso, " %q", argv[i]);
		Bprint(&bso, "\n");
		Bflush(&bso);
	}

	if(runcmd(argv) < 0) {
		ctxt->cursym = S;
		diag("%s: running %s failed: %r", argv0, argv[0]);
		errorexit();
	}
}
示例#28
0
文件: fsx.c 项目: BillTheBest/ceph
void
test(void)
{
	unsigned long	offset;
	unsigned long	size = maxoplen;
	unsigned long	rv = random();
	unsigned long	op;

	if (simulatedopcount > 0 && testcalls == simulatedopcount)
		writefileimage();

	testcalls++;

	if (closeprob)
		closeopen = (rv >> 3) < (1u << 28) / (unsigned)closeprob;

	if (debugstart > 0 && testcalls >= debugstart)
		debug = 1;

	if (!quiet && testcalls < simulatedopcount && testcalls % 100000 == 0)
		prt("%lu...\n", testcalls);

	offset = random();
	if (randomoplen)
		size = random() % (maxoplen + 1);

	/* calculate appropriate op to run */
	if (lite)
		op = rv % OP_MAX_LITE;
	else
		op = rv % OP_MAX_FULL;

	switch (op) {
	case OP_MAPREAD:
		if (!mapped_reads)
			op = OP_READ;
		break;
	case OP_MAPWRITE:
		if (!mapped_writes)
			op = OP_WRITE;
		break;
	case OP_FALLOCATE:
		if (!fallocate_calls) {
			log4(OP_SKIPPED, OP_FALLOCATE, offset, size);
			goto out;
		}
		break;
	case OP_PUNCH_HOLE:
		if (!punch_hole_calls) {
			log4(OP_SKIPPED, OP_PUNCH_HOLE, offset, size);
			goto out;
		}
		break;
	}

	switch (op) {
	case OP_READ:
		TRIM_OFF_LEN(offset, size, file_size);
		doread(offset, size);
		break;

	case OP_WRITE:
		TRIM_OFF_LEN(offset, size, maxfilelen);
		dowrite(offset, size);
		break;

	case OP_MAPREAD:
		TRIM_OFF_LEN(offset, size, file_size);
		exit(183);
		break;

	case OP_MAPWRITE:
		TRIM_OFF_LEN(offset, size, maxfilelen);
		exit(182);
		break;

	case OP_TRUNCATE:
		if (!style)
			size = random() % maxfilelen;
		dotruncate(size);
		break;

	case OP_PUNCH_HOLE:
		TRIM_OFF_LEN(offset, size, file_size);
		do_punch_hole(offset, size);
		break;
	default:
		prterr("test: unknown operation");
		report_failure(42);
		break;
	}

out:
	if (sizechecks && testcalls > simulatedopcount)
		check_size();
	if (closeopen)
		docloseopen();
}
示例#29
0
文件: psort.c 项目: BWK/os161
static
void
mergebins(void)
{
	int infds[numprocs], outfd;
	int values[numprocs], ready[numprocs];
	const char *name, *outname;
	int i, result;
	int numready, place, val, worknum;

	outname = mergedname(me);
	outfd = doopen(outname, O_WRONLY|O_CREAT|O_TRUNC, 0664);

	for (i=0; i<numprocs; i++) {
		name = binname(i, me);
		infds[i] = doopen(name, O_RDONLY, 0);
		values[i] = 0;
		ready[i] = 0;
	}

	worknum = 0;

	while (1) {
		numready = 0;
		for (i=0; i<numprocs; i++) {
			if (infds[i] < 0) {
				continue;
			}

			if (!ready[i]) {
				result = doread("bin", infds[i], 
						&val, sizeof(int));
				if (result == 0) {
					doclose("bin", infds[i]);
					infds[i] = -1;
					continue;
				}
				if ((size_t) result != sizeof(int)) {
					complainx("%s: read: short count",
						  binname(i, me));
					exit(1);
				}
				values[i] = val;
				ready[i] = 1;
			}
			numready++;
		}
		if (numready == 0) {
			break;
		}

		/* find the smallest */
		place = -1;
		for (i=0; i<numprocs; i++) {
			if (!ready[i]) {
				continue;
			}
			if (place < 0 || values[i] < val) {
				val = values[i];
				place = i;
			}
		}
		assert(place >= 0);

		workspace[worknum++] = val;
		if (worknum >= WORKNUM) {
			assert(worknum == WORKNUM);
			dowrite(outname, outfd, workspace,
				worknum * sizeof(int));
			worknum = 0;
		}
		ready[place] = 0;
	}

	dowrite(outname, outfd, workspace, worknum * sizeof(int));
	doclose(outname, outfd);

	for (i=0; i<numprocs; i++) {
		assert(infds[i] < 0);
	}
}
示例#30
0
文件: sysfile.c 项目: 0intro/vx32
long
sys_write(uint32 *arg)
{
	return dowrite(arg, nil);
}