示例#1
0
int execute_get_load_threshold_handle(struct data_buffer *dbuf, int socket_fd, MEM_POOL_PTR mem_pool)
{
	struct data_buffer rbuf;
	
	//发数据包
	if(socket_write(socket_fd,dbuf->data,dbuf->data_len) <= 0)
		return -1;

	//接受命名
	memset(&rbuf,0,sizeof(struct data_buffer));
	rbuf.data_len = sizeof(uint32_t);
	rbuf.size = rbuf.data_len;
	rbuf.data = (uint8_t *)mem_pool_malloc(mem_pool,sizeof(uint32_t));
	
	if(socket_read(socket_fd,rbuf.data,sizeof(uint32_t)) <= 0)
		return -1;

	rbuf.data_len = read_int32(&rbuf);
	rbuf.data = (uint8_t *)mem_pool_malloc(mem_pool,rbuf.data_len);
	rbuf.rpos = 0;
	rbuf.size = rbuf.data_len;

	if(socket_read(socket_fd,rbuf.data,rbuf.data_len) <= 0)
		return -1;
	rbuf.rpos += MESSAGE_HEAD_LEN;

	uint16_t type = message_type(&rbuf);
	if (type != MT_DC_EXE_RS)
		return -1;

	double load = 0;
	read_bytes(&rbuf, (uint8_t *)&load, sizeof(load));

	fprintf(stderr, "%g\n", load);
	return 0;
}
示例#2
0
    int read_version()
    {
        int sum = 0;
        int bytes_read = 0;

        uint16_t header = read_bytes(2, &bytes_read, &sum); // Always 0x210 (0x10-0x02)
        uint16_t command = read_bytes(2, &bytes_read, &sum);

        if (header == START && command == UNIT_VERSION)
        {
            read_bytes(2, &bytes_read, &sum); // length

            int major_version = read_bytes(1, &bytes_read, &sum);
            int minor_version = read_bytes(2, &bytes_read, &sum);
            int data_version = read_bytes(2, &bytes_read, &sum);

            QString version = QString(minor_version<100?"%1.0%2 (%3)":"%1.%2 (%3)").arg(major_version).arg(minor_version).arg(data_version);
            deviceInfo += rideFile->deviceType()+QString(" Version %1\n").arg(version);

            read_bytes(1, &bytes_read, &sum); // checksum
        }
        return bytes_read;
    }
示例#3
0
    int read_system_info()
    {
        int sum = 0;
        int bytes_read = 0;

        uint16_t header = read_bytes(2, &bytes_read, &sum); // Always (0x10-0x02)
        uint16_t command = read_bytes(2, &bytes_read, &sum);


        if (header == START && command == SYSTEM_INFO)
        {
            read_bytes(2, &bytes_read, &sum); // length

            read_bytes(52, &bytes_read, &sum);
            uint16_t odometer = read_bytes(8, &bytes_read, &sum);
            deviceInfo += QString("Odometer %1km\n").arg(odometer/1000.0);

            read_bytes(1, &bytes_read, &sum); // checksum
        }
        return bytes_read;
    }
示例#4
0
    void read_ride_summary(int *bytes_read = NULL, int *sum = NULL)
    {
        data_version = read_bytes(1, bytes_read, sum); // data_version
        read_bytes(1, bytes_read, sum); // firmware_minor_version

        QDateTime t = read_date(bytes_read, sum);

        rideFile->setStartTime(t);

        if (jouleGPS)
        {
            read_bytes(148, bytes_read, sum);

            if (data_version >= 4)
                read_bytes(8, bytes_read, sum);

            if (data_version >= 6)
                read_bytes(8, bytes_read, sum);
       } else
       {
            read_bytes(84, bytes_read, sum);
       }
    }
static int
read_block(FILE *fp, pcap_t *p, struct block_cursor *cursor, char *errbuf)
{
	int status;
	struct block_header bhdr;

	status = read_bytes(fp, &bhdr, sizeof(bhdr), 0, errbuf);
	if (status <= 0)
		return (status);	/* error or EOF */

	if (p->swapped) {
		bhdr.block_type = SWAPLONG(bhdr.block_type);
		bhdr.total_length = SWAPLONG(bhdr.total_length);
	}

	/*
	 * Is this block "too big"?
	 *
	 * We choose 16MB as "too big", for now, so that we handle
	 * "reasonably" large buffers but don't chew up all the
	 * memory if we read a malformed file.
	 */
	if (bhdr.total_length > 16*1024*1024) {
		snprintf(errbuf, PCAP_ERRBUF_SIZE,
		    "pcap-ng block size %u > maximum %u",
		    bhdr.total_length, 16*1024*1024);
		    return (-1);
	}

	/*
	 * Is this block "too small" - i.e., is it shorter than a block
	 * header plus a block trailer?
	 */
	if (bhdr.total_length < sizeof(struct block_header) +
	    sizeof(struct block_trailer)) {
		snprintf(errbuf, PCAP_ERRBUF_SIZE,
		    "block in pcap-ng dump file has a length of %u < %lu",
		    bhdr.total_length,
		    (unsigned long)(sizeof(struct block_header) + sizeof(struct block_trailer)));
		return (-1);
	}

	/*
	 * Is the buffer big enough?
	 */
	if (p->bufsize < (int)bhdr.total_length) {
		/*
		 * No - make it big enough.
		 */
		p->buffer = realloc(p->buffer, bhdr.total_length);
		if (p->buffer == NULL) {
			snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory");
			return (-1);
		}
	}

	/*
	 * Copy the stuff we've read to the buffer, and read the rest
	 * of the block.
	 */
	memcpy(p->buffer, &bhdr, sizeof(bhdr));
	if (read_bytes(fp, p->buffer + sizeof(bhdr),
	    bhdr.total_length - sizeof(bhdr), 1, errbuf) == -1)
		return (-1);

	/*
	 * Initialize the cursor.
	 */
	cursor->data = p->buffer + sizeof(bhdr);
	cursor->data_remaining = bhdr.total_length - sizeof(bhdr) -
	    sizeof(struct block_trailer);
	cursor->block_type = bhdr.block_type;
	return (1);
}
示例#6
0
文件: ptl_usock.c 项目: dycz0fx/ompi
void pmix_usock_recv_handler(int sd, short flags, void *cbdata)
{
    pmix_status_t rc;
    pmix_peer_t *peer = (pmix_peer_t*)cbdata;
    pmix_ptl_recv_t *msg = NULL;

    /* acquire the object */
    PMIX_ACQUIRE_OBJECT(peer);

    pmix_output_verbose(2, pmix_ptl_base_framework.framework_output,
                        "usock:recv:handler called with peer %s:%d",
                        (NULL == peer) ? "NULL" : peer->info->pname.nspace,
                        (NULL == peer) ? PMIX_RANK_UNDEF : peer->info->pname.rank);

    if (NULL == peer) {
        return;
    }
    /* allocate a new message and setup for recv */
    if (NULL == peer->recv_msg) {
        pmix_output_verbose(2, pmix_ptl_base_framework.framework_output,
                            "usock:recv:handler allocate new recv msg");
        peer->recv_msg = PMIX_NEW(pmix_ptl_recv_t);
        if (NULL == peer->recv_msg) {
            pmix_output(0, "usock_recv_handler: unable to allocate recv message\n");
            goto err_close;
        }
        PMIX_RETAIN(peer);
        peer->recv_msg->peer = peer;  // provide a handle back to the peer object
        /* start by reading the header */
        peer->recv_msg->rdptr = (char*)&peer->recv_msg->hdr;
        peer->recv_msg->rdbytes = sizeof(pmix_usock_hdr_t);
    }
    msg = peer->recv_msg;
    msg->sd = sd;
    /* if the header hasn't been completely read, read it */
    if (!msg->hdr_recvd) {
        pmix_output_verbose(2, pmix_ptl_base_framework.framework_output,
                            "usock:recv:handler read hdr on socket %d", peer->sd);
        if (PMIX_SUCCESS == (rc = read_bytes(peer->sd, &msg->rdptr, &msg->rdbytes))) {
            /* completed reading the header */
            peer->recv_msg->hdr_recvd = true;
            pmix_output_verbose(2, pmix_ptl_base_framework.framework_output,
                                "RECVD MSG FOR TAG %d SIZE %d",
                                (int)peer->recv_msg->hdr.tag,
                                (int)peer->recv_msg->hdr.nbytes);
            /* if this is a zero-byte message, then we are done */
            if (0 == peer->recv_msg->hdr.nbytes) {
                pmix_output_verbose(2, pmix_ptl_base_framework.framework_output,
                                    "RECVD ZERO-BYTE MESSAGE FROM %s:%d for tag %d",
                                    peer->info->pname.nspace, peer->info->pname.rank,
                                    peer->recv_msg->hdr.tag);
                peer->recv_msg->data = NULL;  // make sure
                peer->recv_msg->rdptr = NULL;
                peer->recv_msg->rdbytes = 0;
                /* post it for delivery */
                PMIX_ACTIVATE_POST_MSG(peer->recv_msg);
                peer->recv_msg = NULL;
                PMIX_POST_OBJECT(peer);
                return;
            } else {
                pmix_output_verbose(2, pmix_ptl_base_framework.framework_output,
                                    "usock:recv:handler allocate data region of size %lu",
                                    (unsigned long)peer->recv_msg->hdr.nbytes);
                /* allocate the data region */
                peer->recv_msg->data = (char*)malloc(peer->recv_msg->hdr.nbytes);
                memset(peer->recv_msg->data, 0, peer->recv_msg->hdr.nbytes);
                /* point to it */
                peer->recv_msg->rdptr = peer->recv_msg->data;
                peer->recv_msg->rdbytes = peer->recv_msg->hdr.nbytes;
            }
            /* fall thru and attempt to read the data */
        } else if (PMIX_ERR_RESOURCE_BUSY == rc ||
                   PMIX_ERR_WOULD_BLOCK == rc) {
            /* exit this event and let the event lib progress */
            return;
        } else {
            /* the remote peer closed the connection - report that condition
             * and let the caller know
             */
            pmix_output_verbose(2, pmix_ptl_base_framework.framework_output,
                                "pmix_usock_msg_recv: peer closed connection");
            goto err_close;
        }
    }

    if (peer->recv_msg->hdr_recvd) {
        /* continue to read the data block - we start from
         * wherever we left off, which could be at the
         * beginning or somewhere in the message
         */
        if (PMIX_SUCCESS == (rc = read_bytes(peer->sd, &msg->rdptr, &msg->rdbytes))) {
            /* we recvd all of the message */
            pmix_output_verbose(2, pmix_ptl_base_framework.framework_output,
                                "RECVD COMPLETE MESSAGE FROM SERVER OF %d BYTES FOR TAG %d ON PEER SOCKET %d",
                                (int)peer->recv_msg->hdr.nbytes,
                                peer->recv_msg->hdr.tag, peer->sd);
            /* post it for delivery */
            PMIX_ACTIVATE_POST_MSG(peer->recv_msg);
            peer->recv_msg = NULL;
            /* ensure we post the modified peer object before another thread
             * picks it back up */
            PMIX_POST_OBJECT(peer);
            return;
        } else if (PMIX_ERR_RESOURCE_BUSY == rc ||
                   PMIX_ERR_WOULD_BLOCK == rc) {
            /* exit this event and let the event lib progress */
            /* ensure we post the modified peer object before another thread
             * picks it back up */
            PMIX_POST_OBJECT(peer);
            return;
        } else {
            /* the remote peer closed the connection - report that condition
             * and let the caller know
             */
            pmix_output_verbose(2, pmix_ptl_base_framework.framework_output,
                                "pmix_usock_msg_recv: peer closed connection");
            goto err_close;
        }
    }
    /* success */
    return;

  err_close:
    /* stop all events */
    if (peer->recv_ev_active) {
        pmix_event_del(&peer->recv_event);
        peer->recv_ev_active = false;
    }
    if (peer->send_ev_active) {
        pmix_event_del(&peer->send_event);
        peer->send_ev_active = false;
    }
    if (NULL != peer->recv_msg) {
        PMIX_RELEASE(peer->recv_msg);
        peer->recv_msg = NULL;
    }
    pmix_ptl_base_lost_connection(peer, PMIX_ERR_UNREACH);
    /* ensure we post the modified peer object before another thread
     * picks it back up */
    PMIX_POST_OBJECT(peer);
}
示例#7
0
int main(int argc, char** argv) {
	if( 1 >= argc){
		printf("usage: %s file offset length\n", basename(argv[0]));
		return 0;
	}
	FILE *fh = NULL;
	cmp_ctx_t cmp;
	uint16_t year = 1983;
	uint8_t month = 5;
	uint8_t day = 28;
	int64_t sint = 0;
	uint64_t uint = 0;
	float flt = 0.0f;
	double dbl = 0.0;
	bool boolean = false;
	uint8_t fake_bool = 0;
	uint32_t string_size = 0;
	uint32_t array_size = 0;
	uint32_t binary_size = 0;
	uint32_t map_size = 0;
	int8_t ext_type = 0;
	uint32_t ext_size = 0;
	char sbuf[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

	fh = fopen(argv[1], "rb");
	if (fh == NULL){
		error_and_exit(strerror(errno));
	}

	cmp_init(&cmp, fh, file_reader, file_writer);

	/* Alternately, you can read objects until the stream is empty */
	while (1) {
		cmp_object_t obj;

		if (!cmp_read_object(&cmp, &obj)) {
			if (feof(fh))
				break;

			error_and_exit(cmp_strerror(&cmp));
		}

		switch (obj.type) {
		case CMP_TYPE_POSITIVE_FIXNUM:
		case CMP_TYPE_UINT8:
			//printf("Unsigned Integer: %u\n", obj.as.u8);
			printf("Unsigned Integer: %u\n", obj.as.u8);
			break;
		case CMP_TYPE_FIXMAP:
		case CMP_TYPE_MAP16:
		case CMP_TYPE_MAP32:
			printf("Map: %u\n", obj.as.map_size);
			break;
		case CMP_TYPE_FIXARRAY:
		case CMP_TYPE_ARRAY16:
		case CMP_TYPE_ARRAY32:
			printf("Array: %u\n", obj.as.array_size);
			break;
		case CMP_TYPE_FIXSTR:
		case CMP_TYPE_STR8:
		case CMP_TYPE_STR16:
		case CMP_TYPE_STR32:
			if (!read_bytes(sbuf, obj.as.str_size, fh))
				error_and_exit(strerror(errno));
			sbuf[obj.as.str_size] = 0;
			printf("String: %s\n", sbuf);
			break;
		case CMP_TYPE_BIN8:
		case CMP_TYPE_BIN16:
		case CMP_TYPE_BIN32:
			memset(sbuf, 0, sizeof(sbuf));
			if (!read_bytes(sbuf, obj.as.bin_size, fh))
				error_and_exit(strerror(errno));
			printf("Binary: %s\n", sbuf);
			break;
		case CMP_TYPE_NIL:
			printf("NULL\n");
			break;
		case CMP_TYPE_BOOLEAN:
			if (obj.as.boolean)
				printf("Boolean: true\n");
			else
				printf("Boolean: false\n");
			break;
		case CMP_TYPE_EXT8:
		case CMP_TYPE_EXT16:
		case CMP_TYPE_EXT32:
		case CMP_TYPE_FIXEXT1:
		case CMP_TYPE_FIXEXT2:
		case CMP_TYPE_FIXEXT4:
		case CMP_TYPE_FIXEXT8:
		case CMP_TYPE_FIXEXT16:
			if (obj.as.ext.type == 1) { /* Date object */
				if (!read_bytes(&year, sizeof(uint16_t), fh))
					error_and_exit(strerror(errno));

				if (!read_bytes(&month, sizeof(uint8_t), fh))
					error_and_exit(strerror(errno));

				if (!read_bytes(&day, sizeof(uint8_t), fh))
					error_and_exit(strerror(errno));

				printf("Date: %u/%u/%u\n", year, month, day);
			} else {
				printf("Extended type {%d, %u}: ", obj.as.ext.type, obj.as.ext.size);
				while (obj.as.ext.size--) {
					read_bytes(sbuf, sizeof(uint8_t), fh);
					printf("%02x ", sbuf[0]);
				}
				printf("\n");
			}
			break;
		case CMP_TYPE_FLOAT:
			printf("Float: %f\n", obj.as.flt);
			break;
		case CMP_TYPE_DOUBLE:
			printf("Double: %f\n", obj.as.dbl);
			break;
		case CMP_TYPE_UINT16:
			printf("Unsigned Integer: %u\n", obj.as.u16);
			break;
		case CMP_TYPE_UINT32:
			printf("Unsigned Integer: %u\n", obj.as.u32);
			break;
		case CMP_TYPE_UINT64:
			printf("Unsigned Integer: %" PRIu64 "\n", obj.as.u64);
			break;
		case CMP_TYPE_NEGATIVE_FIXNUM:
		case CMP_TYPE_SINT8:
			printf("Signed Integer: %d\n", obj.as.s8);
			break;
		case CMP_TYPE_SINT16:
			printf("Signed Integer: %d\n", obj.as.s16);
			break;
		case CMP_TYPE_SINT32:
			printf("Signed Integer: %d\n", obj.as.s32);
			break;
		case CMP_TYPE_SINT64:
			printf("Signed Integer: %" PRId64 "\n", obj.as.s64);
			break;
		default:
			printf("Unrecognized object type %u\n", obj.type);
			break;
		}
	}

	fclose(fh);

	return EXIT_SUCCESS;
}
示例#8
0
void pmix_usock_recv_handler(int sd, short flags, void *cbdata)
{
    int rc;

    opal_output_verbose(2, opal_pmix_base_framework.framework_output,
                        "%s usock:recv:handler called",
                        OPAL_NAME_PRINT(OPAL_PROC_MY_NAME));

    switch (mca_pmix_native_component.state) {
    case PMIX_USOCK_CONNECT_ACK:
        if (OPAL_SUCCESS == (rc = usock_recv_connect_ack())) {
            opal_output_verbose(2, opal_pmix_base_framework.framework_output,
                                "%s usock:recv:handler starting send/recv events",
                                OPAL_NAME_PRINT(OPAL_PROC_MY_NAME));
            /* we connected! Start the send/recv events */
            if (!mca_pmix_native_component.recv_ev_active) {
                opal_event_add(&mca_pmix_native_component.recv_event, 0);
                mca_pmix_native_component.recv_ev_active = true;
            }
            if (mca_pmix_native_component.timer_ev_active) {
                opal_event_del(&mca_pmix_native_component.timer_event);
                mca_pmix_native_component.timer_ev_active = false;
            }
            /* if there is a message waiting to be sent, queue it */
            if (NULL == mca_pmix_native_component.send_msg) {
                mca_pmix_native_component.send_msg = (pmix_usock_send_t*)opal_list_remove_first(&mca_pmix_native_component.send_queue);
            }
            if (NULL != mca_pmix_native_component.send_msg && !mca_pmix_native_component.send_ev_active) {
                opal_event_add(&mca_pmix_native_component.send_event, 0);
                mca_pmix_native_component.send_ev_active = true;
            }
            /* update our state */
            mca_pmix_native_component.state = PMIX_USOCK_CONNECTED;
        } else {
            opal_output_verbose(2, opal_pmix_base_framework.framework_output,
                                "%s UNABLE TO COMPLETE CONNECT ACK WITH SERVER",
                                OPAL_NAME_PRINT(OPAL_PROC_MY_NAME));
            opal_event_del(&mca_pmix_native_component.recv_event);
            mca_pmix_native_component.recv_ev_active = false;
            return;
        }
        break;
    case PMIX_USOCK_CONNECTED:
        opal_output_verbose(2, opal_pmix_base_framework.framework_output,
                            "%s usock:recv:handler CONNECTED",
                            OPAL_NAME_PRINT(OPAL_PROC_MY_NAME));
        /* allocate a new message and setup for recv */
        if (NULL == mca_pmix_native_component.recv_msg) {
            opal_output_verbose(2, opal_pmix_base_framework.framework_output,
                                "%s usock:recv:handler allocate new recv msg",
                                OPAL_NAME_PRINT(OPAL_PROC_MY_NAME));
            mca_pmix_native_component.recv_msg = OBJ_NEW(pmix_usock_recv_t);
            if (NULL == mca_pmix_native_component.recv_msg) {
                opal_output(0, "%s usock_recv_handler: unable to allocate recv message\n",
                            OPAL_NAME_PRINT(OPAL_PROC_MY_NAME));
                return;
            }
            /* start by reading the header */
            mca_pmix_native_component.recv_msg->rdptr = (char*)&mca_pmix_native_component.recv_msg->hdr;
            mca_pmix_native_component.recv_msg->rdbytes = sizeof(pmix_usock_hdr_t);
        }
        /* if the header hasn't been completely read, read it */
        if (!mca_pmix_native_component.recv_msg->hdr_recvd) {
            opal_output_verbose(2, opal_pmix_base_framework.framework_output,
                                "usock:recv:handler read hdr");
            if (OPAL_SUCCESS == (rc = read_bytes(mca_pmix_native_component.recv_msg))) {
                /* completed reading the header */
                mca_pmix_native_component.recv_msg->hdr_recvd = true;
                /* if this is a zero-byte message, then we are done */
                if (0 == mca_pmix_native_component.recv_msg->hdr.nbytes) {
                    opal_output_verbose(2, opal_pmix_base_framework.framework_output,
                                        "%s RECVD ZERO-BYTE MESSAGE FROM SERVER for tag %d",
                                        OPAL_NAME_PRINT(OPAL_PROC_MY_NAME),
                                        mca_pmix_native_component.recv_msg->hdr.tag);
                    mca_pmix_native_component.recv_msg->data = NULL;  // make sure
                    mca_pmix_native_component.recv_msg->rdptr = NULL;
                    mca_pmix_native_component.recv_msg->rdbytes = 0;
                } else {
                    opal_output_verbose(2, opal_pmix_base_framework.framework_output,
                                        "%s usock:recv:handler allocate data region of size %lu",
                                        OPAL_NAME_PRINT(OPAL_PROC_MY_NAME),
                                        (unsigned long)mca_pmix_native_component.recv_msg->hdr.nbytes);
                    /* allocate the data region */
                    mca_pmix_native_component.recv_msg->data = (char*)malloc(mca_pmix_native_component.recv_msg->hdr.nbytes);
                    /* point to it */
                    mca_pmix_native_component.recv_msg->rdptr = mca_pmix_native_component.recv_msg->data;
                    mca_pmix_native_component.recv_msg->rdbytes = mca_pmix_native_component.recv_msg->hdr.nbytes;
                }
                /* fall thru and attempt to read the data */
            } else if (OPAL_ERR_RESOURCE_BUSY == rc ||
                       OPAL_ERR_WOULD_BLOCK == rc) {
                /* exit this event and let the event lib progress */
                return;
            } else {
                /* close the connection */
                opal_output_verbose(2, opal_pmix_base_framework.framework_output,
                                    "%s usock:recv:handler error reading bytes - closing connection",
                                    OPAL_NAME_PRINT(OPAL_PROC_MY_NAME));
                CLOSE_THE_SOCKET(mca_pmix_native_component.sd);
                return;
            }
        }

        if (mca_pmix_native_component.recv_msg->hdr_recvd) {
            /* continue to read the data block - we start from
             * wherever we left off, which could be at the
             * beginning or somewhere in the message
             */
            if (OPAL_SUCCESS == (rc = read_bytes(mca_pmix_native_component.recv_msg))) {
                /* we recvd all of the message */
                opal_output_verbose(2, opal_pmix_base_framework.framework_output,
                                    "%s RECVD COMPLETE MESSAGE FROM SERVER OF %d BYTES FOR TAG %d",
                                    OPAL_NAME_PRINT(OPAL_PROC_MY_NAME),
                                    (int)mca_pmix_native_component.recv_msg->hdr.nbytes,
                                    mca_pmix_native_component.recv_msg->hdr.tag);
                /* post it for delivery */
                PMIX_ACTIVATE_POST_MSG(mca_pmix_native_component.recv_msg);
                mca_pmix_native_component.recv_msg = NULL;
            } else if (OPAL_ERR_RESOURCE_BUSY == rc ||
                       OPAL_ERR_WOULD_BLOCK == rc) {
                /* exit this event and let the event lib progress */
                return;
            } else {
                // report the error
                opal_output(0, "%s usock_peer_recv_handler: unable to recv message",
                            OPAL_NAME_PRINT(OPAL_PROC_MY_NAME));
                /* turn off the recv event */
                opal_event_del(&mca_pmix_native_component.recv_event);
                mca_pmix_native_component.recv_ev_active = false;
                CLOSE_THE_SOCKET(mca_pmix_native_component.sd);
                return;
            }
        }
        break;
    default: 
        opal_output(0, "%s usock_peer_recv_handler: invalid socket state(%d)",
                    OPAL_NAME_PRINT(OPAL_PROC_MY_NAME), 
                    mca_pmix_native_component.state);
        CLOSE_THE_SOCKET(mca_pmix_native_component.sd);
        break;
    }
}
示例#9
0
// Parse the user data for captions. The udtype variable denotes
// to which type of data it belongs:
// 0 .. sequence header
// 1 .. GOP header
// 2 .. picture header
// Return TRUE if the data parsing finished, FALSE otherwise.
// estream->pos is advanced. Data is only processed if ustream->error
// is FALSE, parsing can set ustream->error to TRUE.
int user_data(struct lib_cc_decode *ctx, struct bitstream *ustream, int udtype, struct cc_subtitle *sub)
{
	dbg_print(CCX_DMT_VERBOSE, "user_data(%d)\n", udtype);

	// Shall not happen
	if (ustream->error || ustream->bitsleft <= 0)
	{
		// ustream->error=1;
		return 0; // Actually discarded on call.
		// CFS: Seen in a Wobble edited file.
		// fatal(CCX_COMMON_EXIT_BUG_BUG, "user_data: Impossible!");
	}

	// Do something
	ctx->stat_numuserheaders++;
	//header+=4;

	unsigned char *ud_header = next_bytes(ustream, 4);
	if (ustream->error || ustream->bitsleft <= 0)
	{
		return 0;  // Actually discarded on call.
		// CFS: Seen in Stick_VHS.mpg.
		// fatal(CCX_COMMON_EXIT_BUG_BUG, "user_data: Impossible!");
	}

	// DVD CC header, see
	// <http://www.theneitherworld.com/mcpoodle/SCC_TOOLS/DOCS/SCC_FORMAT.HTML>
	if ( !memcmp(ud_header,"\x43\x43", 2 ) )
	{
		ctx->stat_dvdccheaders++;

		// Probably unneeded, but keep looking for extra caption blocks
		int maybeextracb = 1;

		read_bytes(ustream, 4); // "43 43 01 F8"

		unsigned char pattern_flag = (unsigned char) read_bits(ustream,1);
		read_bits(ustream,1);
		int capcount=(int) read_bits(ustream,5);
		int truncate_flag = (int) read_bits(ustream,1); // truncate_flag - one CB extra

		int field1packet = 0; // expect Field 1 first
		if (pattern_flag == 0x00)
			field1packet=1; // expect Field 1 second

		dbg_print(CCX_DMT_VERBOSE, "Reading %d%s DVD CC segments\n",
				capcount, (truncate_flag?"+1":""));

		capcount += truncate_flag;

		// This data comes before the first frame header, so
		// in order to get the correct timing we need to set the
		// current time to one frame after the maximum time of the
		// last GOP.  Only useful when there are frames before
		// the GOP.
		if (ctx->timing->fts_max > 0)
			ctx->timing->fts_now = ctx->timing->fts_max + (LLONG) (1000.0/current_fps);

		int rcbcount = 0;
		for (int i=0; i<capcount; i++)
		{
			for (int j=0;j<2;j++)
			{
				unsigned char data[3];
				data[0]=read_u8(ustream);
				data[1]=read_u8(ustream);
				data[2]=read_u8(ustream);

				// Obey the truncate flag.
				if ( truncate_flag && i == capcount-1 && j == 1 )
				{
					maybeextracb = 0;
					break;
				}
				/* Field 1 and 2 data can be in either order,
				   with marker bytes of \xff and \xfe
				   Since markers can be repeated, use pattern as well */
				if ((data[0]&0xFE) == 0xFE) // Check if valid
				{
					if (data[0]==0xff && j==field1packet)
						data[0]=0x04; // Field 1
					else
						data[0]=0x05; // Field 2
					do_cb(ctx, data, sub);
					rcbcount++;
				}
				else
				{
					dbg_print(CCX_DMT_VERBOSE, "Illegal caption segment - stop here.\n");
					maybeextracb = 0;
					break;
				}
			}
		}
		// Theoretically this should not happen, oh well ...
		// Deal with extra closed captions some DVD have.
		int ecbcount = 0;
		while ( maybeextracb && (next_u8(ustream)&0xFE) == 0xFE )
		{
			for (int j=0;j<2;j++)
			{
				unsigned char data[3];
				data[0]=read_u8(ustream);
				data[1]=read_u8(ustream);
				data[2]=read_u8(ustream);
				/* Field 1 and 2 data can be in either order,
				   with marker bytes of \xff and \xfe
				   Since markers can be repeated, use pattern as well */
				if ((data[0]&0xFE) == 0xFE) // Check if valid
				{
					if (data[0]==0xff && j==field1packet)
						data[0]=0x04; // Field 1
					else
						data[0]=0x05; // Field 2
					do_cb(ctx, data, sub);
					ecbcount++;
				}
				else
				{
					dbg_print(CCX_DMT_VERBOSE, "Illegal (extra) caption segment - stop here.\n");
					maybeextracb = 0;
					break;
				}
			}
		}

		dbg_print(CCX_DMT_VERBOSE, "Read %d/%d DVD CC blocks\n", rcbcount, ecbcount);
	}
	// SCTE 20 user data
	else if (!ctx->noscte20 && ud_header[0] == 0x03)
	{
		if ((ud_header[1]&0x7F) == 0x01)
		{
			unsigned char cc_data[3*31+1]; // Maximum cc_count is 31

			ctx->stat_scte20ccheaders++;
			read_bytes(ustream, 2); // "03 01"

			unsigned cc_count = (unsigned int) read_bits(ustream,5);
			dbg_print(CCX_DMT_VERBOSE, "Reading %d SCTE 20 CC blocks\n", cc_count);

			unsigned field_number;
			unsigned cc_data1;
			unsigned cc_data2;

			for (unsigned j=0;j<cc_count;j++)
			{
				skip_bits(ustream,2); // priority - unused
				field_number = (unsigned int) read_bits(ustream,2);
				skip_bits(ustream,5); // line_offset - unused
				cc_data1 = (unsigned int) read_bits(ustream,8);
				cc_data2 = (unsigned int) read_bits(ustream,8);
				read_bits(ustream,1); // TODO: Add syntax check */

				if (ustream->bitsleft < 0)
					fatal(CCX_COMMON_EXIT_BUG_BUG, "In user_data: ustream->bitsleft < 0. Cannot continue.");

				// Field_number is either
				//  0 .. forbidden
				//  1 .. field 1 (odd)
				//  2 .. field 2 (even)
				//  3 .. repeated, from repeat_first_field, effectively field 1
				if (field_number < 1)
				{
					// 0 is invalid
					cc_data[j*3]=0x00; // Set to invalid
					cc_data[j*3+1]=0x00;
					cc_data[j*3+2]=0x00;
				}
				else
				{
					// Treat field_number 3 as 1
					field_number = (field_number - 1) & 0x01;
					// top_field_first also affects to which field the caption
					// belongs.
					if(!ctx->top_field_first)
						field_number ^= 0x01;
					cc_data[j*3]=0x04|(field_number);
					cc_data[j*3+1]=reverse8(cc_data1);
					cc_data[j*3+2]=reverse8(cc_data2);
				}
			}
			cc_data[cc_count*3]=0xFF;
			store_hdcc(ctx, cc_data, cc_count, ctx->timing->current_tref, ctx->timing->fts_now, sub);

			dbg_print(CCX_DMT_VERBOSE, "Reading SCTE 20 CC blocks - done\n");
		}
		// reserved - unspecified
	}
	// ReplayTV 4000/5000 caption header - parsing information
	// derived from CCExtract.bdl
	else if ( (ud_header[0] == 0xbb     //ReplayTV 4000
				|| ud_header[0] == 0x99) //ReplayTV 5000
			&& ud_header[1] == 0x02 )
	{
		unsigned char data[3];

		if (ud_header[0]==0xbb)
			ctx->stat_replay4000headers++;
		else
			ctx->stat_replay5000headers++;


		read_bytes(ustream, 2); // "BB 02" or "99 02"
		data[0]=0x05; // Field 2
		data[1]=read_u8(ustream);
		data[2]=read_u8(ustream);
		do_cb(ctx, data, sub);
		read_bytes(ustream, 2); // Skip "CC 02" for R4000 or "AA 02" for R5000
		data[0]=0x04; // Field 1
		data[1]=read_u8(ustream);
		data[2]=read_u8(ustream);
		do_cb(ctx, data, sub);
	}
	// HDTV - see A/53 Part 4 (Video)
	else if ( !memcmp(ud_header,"\x47\x41\x39\x34", 4 ) )
	{
		ctx->stat_hdtv++;

		read_bytes(ustream, 4); // "47 41 39 34"

		unsigned char type_code = read_u8(ustream);
		if (type_code==0x03) // CC data.
		{
			skip_bits(ustream,1); // reserved
			unsigned char process_cc_data = (unsigned char) read_bits(ustream,1);
			skip_bits(ustream,1); // additional_data - unused
			unsigned char cc_count = (unsigned char) read_bits(ustream,5);
			read_bytes(ustream, 1); // "FF"
			if (process_cc_data)
			{
				dbg_print(CCX_DMT_VERBOSE, "Reading %d HDTV CC blocks\n", cc_count);

				int proceed = 1;
				unsigned char *cc_data = read_bytes(ustream, cc_count*3);
				if (ustream->bitsleft < 0)
					fatal(CCX_COMMON_EXIT_BUG_BUG, "In user_data: ustream->bitsleft < 0. Cannot continue.\n");

				// Check for proper marker - This read makes sure that
				// cc_count*3+1 bytes are read and available in cc_data.
				if (read_u8(ustream)!=0xFF)
					proceed=0;

				if (!proceed)
				{
					dbg_print(CCX_DMT_VERBOSE, "\rThe following payload is not properly terminated.\n");
					dump (CCX_DMT_VERBOSE, cc_data, cc_count*3+1, 0, 0);
				}
				dbg_print(CCX_DMT_VERBOSE, "Reading %d HD CC blocks\n", cc_count);

				// B-frames might be (temporal) before or after the anchor
				// frame they belong to. Store the buffer until the next anchor
				// frame occurs.  The buffer will be flushed (sorted) in the
				// picture header (or GOP) section when the next anchor occurs.
				// Please note we store the current value of the global
				// fts_now variable (and not get_fts()) as we are going to
				// re-create the timeline in process_hdcc() (Slightly ugly).
				store_hdcc(ctx, cc_data, cc_count, ctx->timing->current_tref, ctx->timing->fts_now, sub);

				dbg_print(CCX_DMT_VERBOSE, "Reading HDTV blocks - done\n");
			}
		}
		// reserved - additional_cc_data
	}
	// DVB closed caption header for Dish Network (Field 1 only) */
	else if ( !memcmp(ud_header,"\x05\x02", 2 ) )
	{
		// Like HDTV (above) Dish Network captions can be stored at each
		// frame, but maximal two caption blocks per frame and only one
		// field is stored.
		// To process this with the HDTV framework we create a "HDTV" caption
		// format compatible array. Two times 3 bytes plus one for the 0xFF
		// marker at the end. Pre-init to field 1 and set the 0xFF marker.
		static unsigned char dishdata[7] = {0x04, 0, 0, 0x04, 0, 0, 0xFF};
		int cc_count;

		dbg_print(CCX_DMT_VERBOSE, "Reading Dish Network user data\n");

		ctx->stat_dishheaders++;

		read_bytes(ustream, 2); // "05 02"

		// The next bytes are like this:
		// header[2] : ID: 0x04 (MPEG?), 0x03 (H264?)
		// header[3-4]: Two byte counter (counting (sub-)GOPs?)
		// header[5-6]: Two bytes, maybe checksum?
		// header[7]: Pattern type
		//            on B-frame: 0x02, 0x04
		//            on I-/P-frame: 0x05
		unsigned char id = read_u8(ustream);
		unsigned dishcount = read_u16(ustream);
		unsigned something = read_u16(ustream);
		unsigned char type = read_u8(ustream);
		dbg_print(CCX_DMT_PARSE, "DN  ID: %02X  Count: %5u  Unknown: %04X  Pattern: %X",
				id, dishcount, something, type);

		unsigned char hi;

		// The following block needs 4 to 6 bytes starting from the
		// current position
		unsigned char *dcd = ustream->pos; // dish caption data
		switch (type)
		{
			case 0x02:
				// Two byte caption - always on B-frame
				// The following 4 bytes are:
				// 0  :  0x09
				// 1-2: caption block
				// 3  : REPEAT - 02: two bytes
				//             - 04: four bytes (repeat first two)
				dbg_print(CCX_DMT_PARSE, "\n02 %02X  %02X:%02X - R:%02X :",
						dcd[0], dcd[1], dcd[2], dcd[3]);

				cc_count = 1;
				dishdata[1]=dcd[1];
				dishdata[2]=dcd[2];

				dbg_print(CCX_DMT_PARSE, "%s", debug_608_to_ASC( dishdata, 0) );

				type=dcd[3];  // repeater (0x02 or 0x04)
				hi = dishdata[1] & 0x7f; // Get only the 7 low bits
				if (type==0x04 && hi<32) // repeat (only for non-character pairs)
				{
					cc_count = 2;
					dishdata[3]=0x04; // Field 1
					dishdata[4]=dishdata[1];
					dishdata[5]=dishdata[2];

					dbg_print(CCX_DMT_PARSE, "%s:\n", debug_608_to_ASC( dishdata+3, 0) );
				}
				else
				{
					dbg_print(CCX_DMT_PARSE, ":\n");
				}

				dishdata[cc_count*3] = 0xFF; // Set end marker

				store_hdcc(ctx, dishdata, cc_count, ctx->timing->current_tref, ctx->timing->fts_now, sub);

				// Ignore 3 (0x0A, followed by two unknown) bytes.
				break;
			case 0x04:
				// Four byte caption - always on B-frame
				// The following 5 bytes are:
				// 0  :  0x09
				// 1-2: caption block
				// 3-4: caption block
				dbg_print(CCX_DMT_PARSE, "\n04 %02X  %02X:%02X:%02X:%02X  :",
						dcd[0], dcd[1], dcd[2], dcd[3], dcd[4]);

				cc_count = 2;
				dishdata[1]=dcd[1];
				dishdata[2]=dcd[2];

				dishdata[3]=0x04; // Field 1
				dishdata[4]=dcd[3];
				dishdata[5]=dcd[4];
				dishdata[6] = 0xFF; // Set end marker

				dbg_print(CCX_DMT_PARSE, "%s", debug_608_to_ASC( dishdata, 0) );
				dbg_print(CCX_DMT_PARSE, "%s:\n", debug_608_to_ASC( dishdata+3, 0) );

				store_hdcc(ctx, dishdata, cc_count, ctx->timing->current_tref, ctx->timing->fts_now, sub);

				// Ignore 4 (0x020A, followed by two unknown) bytes.
				break;
			case 0x05:
				// Buffered caption - always on I-/P-frame
				// The following six bytes are:
				// 0  :  0x04
				// - the following are from previous 0x05 caption header -
				// 1  : prev dcd[2]
				// 2-3: prev dcd[3-4]
				// 4-5: prev dcd[5-6]
				dbg_print(CCX_DMT_PARSE, " - %02X  pch: %02X %5u %02X:%02X\n",
						dcd[0], dcd[1],
						(unsigned)dcd[2]*256+dcd[3],
						dcd[4], dcd[5]);
				dcd+=6; // Skip these 6 bytes

				// Now one of the "regular" 0x02 or 0x04 captions follows
				dbg_print(CCX_DMT_PARSE, "%02X %02X  %02X:%02X",
						dcd[0], dcd[1], dcd[2], dcd[3]);

				type=dcd[0]; // Number of caption bytes (0x02 or 0x04)

				cc_count = 1;
				dishdata[1]=dcd[2];
				dishdata[2]=dcd[3];

				dcd+=4; // Skip the first 4 bytes.
				if (type==0x02)
				{
					type=dcd[0]; // repeater (0x02 or 0x04)
					dcd++; // Skip the repeater byte.

					dbg_print(CCX_DMT_PARSE, " - R:%02X :%s", type, debug_608_to_ASC( dishdata, 0) );

					hi = dishdata[1] & 0x7f; // Get only the 7 low bits
					if (type==0x04 && hi<32)
					{
						cc_count = 2;
						dishdata[3]=0x04; // Field 1
						dishdata[4]=dishdata[1];
						dishdata[5]=dishdata[2];
						dbg_print(CCX_DMT_PARSE, "%s:\n", debug_608_to_ASC( dishdata+3, 0) );
					}
					else
					{
						dbg_print(CCX_DMT_PARSE, ":\n");
					}
					dishdata[cc_count*3] = 0xFF; // Set end marker
				}
				else
				{
					dbg_print(CCX_DMT_PARSE, ":%02X:%02X  ",
							dcd[0], dcd[1]);
					cc_count = 2;
					dishdata[3]=0x04; // Field 1
					dishdata[4]=dcd[0];
					dishdata[5]=dcd[1];
					dishdata[6] = 0xFF; // Set end marker

					dbg_print(CCX_DMT_PARSE, ":%s", debug_608_to_ASC( dishdata, 0) );
					dbg_print(CCX_DMT_PARSE, "%s:\n", debug_608_to_ASC( dishdata+3, 0) );
				}

				store_hdcc(ctx, dishdata, cc_count, ctx->timing->current_tref, ctx->timing->fts_now, sub);

				// Ignore 3 (0x0A, followed by 2 unknown) bytes.
				break;
			default:
				// printf ("Unknown?\n");
				break;
		} // switch

		dbg_print(CCX_DMT_VERBOSE, "Reading Dish Network user data - done\n");
	}
	// CEA 608 / aka "Divicom standard", see:
	// http://www.pixeltools.com/tech_tip_closed_captioning.html
	else if ( !memcmp(ud_header,"\x02\x09", 2 ) )
	{
		// Either a documentation or more examples are needed.
		ctx->stat_divicom++;

		unsigned char data[3];

		read_bytes(ustream, 2); // "02 09"
		read_bytes(ustream, 2); // "80 80" ???
		read_bytes(ustream, 2); // "02 0A" ???
		data[0]=0x04; // Field 1
		data[1]=read_u8(ustream);
		data[2]=read_u8(ustream);
		do_cb(ctx, data, sub);
		// This is probably incomplete!
	}
	// GXF vbi OEM code
	else if ( !memcmp(ud_header,"\x73\x52\x21\x06", 4 ) )
	{
		int udatalen = ustream->end - ustream->pos;
		uint16_t line_nb;
		uint8_t line_type;
		uint8_t field = 1;
		read_bytes(ustream, 4); //skip header code
		read_bytes(ustream, 2); //skip data length
		line_nb = read_bits(ustream, 16);
		line_type = read_u8(ustream);
		field = (line_type & 0x03);
		if(field == 0)
			mprint("MPEG:VBI: Invalid field\n");

		line_type = line_type >> 2;
		if(line_type != 1)
			mprint("MPEG:VBI: only support Luma line\n");

		if (udatalen < 720)
			mprint("MPEG:VBI: Minimum 720 bytes in luma line required\n");

		decode_vbi(ctx, field, ustream->pos, 720, sub);
		dbg_print(CCX_DMT_VERBOSE, "GXF (vbi line %d) user data:\n", line_nb);
	}
示例#10
0
文件: ec_lpc.c 项目: AdriDlu/coreboot
/* Read single byte and return byte read */
static inline u8 read_byte(u16 port)
{
	u8 byte;
	read_bytes(port, 1, &byte, NULL);
	return byte;
}
示例#11
0
static int spin_read_bytes(thread_args *args, char *buf) {
  return read_bytes(args->fds.read_fd, buf, args->msg_size, 1);
}
示例#12
0
static int blocking_read_bytes(thread_args *args, char *buf) {
  return read_bytes(args->fds.read_fd, buf, args->msg_size, 0);
}
示例#13
0
 void read_interval_summary(int *bytes_read = NULL, int *sum = NULL)
 {
     read_bytes(3200, bytes_read, sum);
 }
示例#14
0
 void read_header(uint16_t &header, uint16_t &command, uint16_t &length, int *bytes_read = NULL, int *sum = NULL)
 {
     header = read_bytes(2, bytes_read, sum);
     command = read_bytes(2, bytes_read, sum);
     length = read_bytes(2, bytes_read, sum);
 }
示例#15
0
    void read_detail_record(double *secs, int *bytes_read = NULL, int *sum = NULL)
    {
        int cad = read_bytes(1, bytes_read, sum);
        read_bytes(1, bytes_read, sum); // pedal_smoothness
        int lrbal = read_bytes(1, bytes_read, sum);
        int hr = read_bytes(1, bytes_read, sum);
        read_bytes(1, bytes_read, sum); // dummy
        int watts = read_bytes(2, bytes_read, sum);
        int nm = read_bytes(2, bytes_read, sum);
        double kph = read_bytes(2, bytes_read, sum);
        int alt = read_bytes(2, bytes_read, sum);
        double temp = read_bytes(2, bytes_read, sum)/10.0;
        double lat = read_bytes(4, bytes_read, sum);
        double lng = read_bytes(4, bytes_read, sum);
        double km = read_bytes(8, bytes_read, sum)/1000.0/1000.0;

        // Validations
        if (lrbal == 0xFF)
            lrbal = 0;
        else if ((lrbal & 0x200) == 0x200)
            lrbal = 100-lrbal;

        if (cad == 0xFF)
            cad = 0;

        if (hr == 0xFF)
            hr = 0;

        if (watts == 0xFFFF) // 65535
            watts = 0;

        if (kph == 0xFFFF) // 65535
            kph = 0;
        else
            kph = kph/10.0;

        if (temp == 0x8000)
            temp = 0;

        if (alt == 0x8000)
            alt = 0;

        if (lat == -2147483648) //2147483648
            lat = 0;
        else
            lat = lat/10000000.0;

        if (lng == -2147483648) //0x80000000
            lng = 0;
        else
            lng = lng/10000000.0;

        rideFile->appendPoint(*secs, cad, hr, km, kph, nm, watts, alt, lng, lat, 0.0, 0, temp, lrbal, interval);
        (*secs)++;
    }
示例#16
0
文件: ec_lpc.c 项目: AdriDlu/coreboot
static int google_chromeec_command_v3(struct chromeec_command *cec_command)
{
	struct ec_host_request rq;
	struct ec_host_response rs;
	const u8 *d;
	u8 csum = 0;
	int i;

	if (cec_command->cmd_size_in + sizeof(rq) > EC_LPC_HOST_PACKET_SIZE) {
		printk(BIOS_ERR, "EC cannot send %zu bytes\n",
		       cec_command->cmd_size_in + sizeof(rq));
		return -1;
	}

	if (cec_command->cmd_size_out > EC_LPC_HOST_PACKET_SIZE) {
		printk(BIOS_ERR, "EC cannot receive %d bytes\n",
		       cec_command->cmd_size_out);
		return -1;
	}

	if (google_chromeec_wait_ready(EC_LPC_ADDR_HOST_CMD)) {
		printk(BIOS_ERR, "Timeout waiting for EC start command %d!\n",
		       cec_command->cmd_code);
		return -1;
	}

	/* Fill in request packet */
	rq.struct_version = EC_HOST_REQUEST_VERSION;
	rq.checksum = 0;
	rq.command = cec_command->cmd_code |
		EC_CMD_PASSTHRU_OFFSET(cec_command->cmd_dev_index);
	rq.command_version = cec_command->cmd_version;
	rq.reserved = 0;
	rq.data_len = cec_command->cmd_size_in;

	/* Copy data and start checksum */
	write_bytes(EC_LPC_ADDR_HOST_PACKET + sizeof(rq),
		    cec_command->cmd_size_in,
		    (u8*)cec_command->cmd_data_in,
		    &csum);

	/* Finish checksum */
	for (i = 0, d = (const u8 *)&rq; i < sizeof(rq); i++, d++)
		csum += *d;

	/* Write checksum field so the entire packet sums to 0 */
	rq.checksum = -csum;

	/* Copy header */
	write_bytes(EC_LPC_ADDR_HOST_PACKET, sizeof(rq), (u8*)&rq, NULL);

	/* Start the command */
	write_byte(EC_COMMAND_PROTOCOL_3, EC_LPC_ADDR_HOST_CMD);

	if (google_chromeec_wait_ready(EC_LPC_ADDR_HOST_CMD)) {
		printk(BIOS_ERR, "Timeout waiting for EC process command %d!\n",
		       cec_command->cmd_code);
		return -1;
	}

	/* Check result */
	cec_command->cmd_code = read_byte(EC_LPC_ADDR_HOST_DATA);
	if (cec_command->cmd_code) {
		printk(BIOS_ERR, "EC returned error result code %d\n",
			cec_command->cmd_code);
		return -i;
	}

	/* Read back response header and start checksum */
	csum = 0;
	read_bytes(EC_LPC_ADDR_HOST_PACKET, sizeof(rs), (u8*)&rs, &csum);

	if (rs.struct_version != EC_HOST_RESPONSE_VERSION) {
		printk(BIOS_ERR, "EC response version mismatch (%d != %d)\n",
		       rs.struct_version, EC_HOST_RESPONSE_VERSION);
		return -1;
	}

	if (rs.reserved) {
		printk(BIOS_ERR, "EC response reserved is %d, should be 0\n",
			rs.reserved);
		return -1;
	}

	if (rs.data_len > cec_command->cmd_size_out) {
		printk(BIOS_ERR, "EC returned too much data (%d > %d)\n",
		       rs.data_len, cec_command->cmd_size_out);
		return -1;
	}

	/* Read back data and update checksum */
	read_bytes(EC_LPC_ADDR_HOST_PACKET + sizeof(rs),
		   rs.data_len,
		   cec_command->cmd_data_out,
		   &csum);

	/* Verify checksum */
	if (csum) {
		printk(BIOS_ERR, "EC response has invalid checksum\n");
		return -1;
	}

	return 0;
}
示例#17
0
文件: ec_lpc.c 项目: AdriDlu/coreboot
static int google_chromeec_command_v1(struct chromeec_command *cec_command)
{
	struct ec_lpc_host_args args;
	u8 cmd_code = cec_command->cmd_code;
	u8 csum;

	/* Fill in args */
	args.flags = EC_HOST_ARGS_FLAG_FROM_HOST;
	args.command_version = cec_command->cmd_version;
	args.data_size = cec_command->cmd_size_in;

	/* Initialize checksum */
	csum = cmd_code + args.flags + args.command_version + args.data_size;

	write_bytes(EC_LPC_ADDR_HOST_PARAM,
		    cec_command->cmd_size_in,
		    (u8*)cec_command->cmd_data_in,
		    &csum);

	/* Finalize checksum and write args */
	args.checksum = csum;
	write_bytes(EC_LPC_ADDR_HOST_ARGS, sizeof(args), (u8*)&args, NULL);


	/* Issue the command */
	write_byte(cmd_code, EC_LPC_ADDR_HOST_CMD);

	if (google_chromeec_wait_ready(EC_LPC_ADDR_HOST_CMD)) {
		printk(BIOS_ERR, "Timeout waiting for EC process command %d!\n",
		       cec_command->cmd_code);
		return 1;
	}

	/* Check result */
	cec_command->cmd_code = read_byte(EC_LPC_ADDR_HOST_DATA);
	if (cec_command->cmd_code)
		return 1;

	/* Read back args */
	read_bytes(EC_LPC_ADDR_HOST_ARGS, sizeof(args), (u8*)&args, NULL);

	/*
	 * If EC didn't modify args flags, then somehow we sent a new-style
	 * command to an old EC, which means it would have read its params
	 * from the wrong place.
	 */
	if (!(args.flags & EC_HOST_ARGS_FLAG_TO_HOST)) {
		printk(BIOS_ERR, "EC protocol mismatch\n");
		return 1;
	}

	if (args.data_size > cec_command->cmd_size_out) {
		printk(BIOS_ERR, "EC returned too much data\n");
		return 1;
	}
	cec_command->cmd_size_out = args.data_size;

	/* Start calculating response checksum */
	csum = cmd_code + args.flags + args.command_version + args.data_size;

	/* Read data, if any */
	read_bytes(EC_LPC_ADDR_HOST_PARAM,
		   args.data_size,
		   cec_command->cmd_data_out,
		   &csum);

	/* Verify checksum */
	if (args.checksum != csum) {
		printk(BIOS_ERR, "EC response has invalid checksum\n");
		return 1;
	}

	return 0;
}
示例#18
0
文件: savegame.c 项目: UIKit0/sarien
int load_game(char* s)
{
	int i, ver, vt_entries = MAX_VIEWTABLE;
	UINT8 t;
	SINT16 parm[7];
	char sig[8];
	char id[8];
	char description[256];
	FILE *f = fopen(s, "rb");

	if(!f)
		return err_BadFileOpen;

	read_bytes(f, sig, 8);
	if (strncmp (sig, strSig, 8)) {
		fclose(f);
		return err_BadFileOpen;
	}

	read_string (f, description);

	ver = read_uint8(f);
	if (ver == 0)
		vt_entries = 64;
	game.state = read_uint8(f);
	/* game.name - not saved */
	read_string(f, id);
	if(strcmp(id, game.id)) {
		fclose(f);
		return err_BadFileOpen;
	}
	/* game.crc - not saved */

	for (i = 0; i < MAX_FLAGS; i++)
		game.flags[i] = read_uint8(f);
	for (i = 0; i < MAX_VARS; i++)
		game.vars[i] = read_uint8(f);

	game.horizon = read_sint16(f);
	game.line_status = read_sint16(f);
	game.line_user_input = read_sint16(f);
	game.line_min_print = read_sint16(f);

	/* These are never saved */
	game.cursor_pos = 0;
	game.input_buffer[0] = 0;
	game.echo_buffer[0] = 0;
	game.keypress = 0;

	game.input_mode = read_sint16(f);
	game.lognum = read_sint16(f);

	game.player_control = read_sint16(f);
	game.quit_prog_now = read_sint16(f);
	game.status_line = read_sint16(f);
	game.clock_enabled = read_sint16(f);
	game.exit_all_logics = read_sint16(f);
	game.picture_shown = read_sint16(f);
	game.has_prompt = read_sint16(f);
	game.game_flags = read_sint16(f);
	game.input_enabled = !read_sint16(f);

	for (i = 0; i < _HEIGHT; i++)
		game.pri_table[i] = read_uint8(f);

	if(game.has_window)
		close_window();
	game.msg_box_ticks = 0;
	game.block.active = FALSE;
	/* game.window - fixed by close_window() */
	/* game.has_window - fixed by close_window() */

	game.gfx_mode = read_sint16(f);
	game.cursor_char = read_uint8(f);
	game.color_fg = read_sint16(f);
	game.color_bg = read_sint16(f);

	/* game.hires (#ifdef USE_HIRES) - rebuilt from image stack */
	/* game.sbuf - rebuilt from image stack */

	/* game.ego_words - fixed by clean_input */
	/* game.num_ego_words - fixed by clean_input */

	game.num_objects = read_sint16(f);
	for(i = 0; i < (SINT16)game.num_objects; i++)
		object_set_location(i, read_sint16(f));

	/* Those are not serialized */
	for (i = 0; i < MAX_DIRS; i++) {
		game.ev_keyp[i].occured = FALSE;
	}

	for (i = 0; i < MAX_STRINGS; i++)
		read_string (f, game.strings[i]);

	for (i = 0; i < MAX_DIRS; i++) {
		if(read_uint8(f) & RES_LOADED)
			agi_load_resource (rLOGIC, i);
		else
			agi_unload_resource (rLOGIC, i);
		game.logics[i].sIP = read_sint16(f);
		game.logics[i].cIP = read_sint16(f);
	}

	for (i = 0; i < MAX_DIRS; i++) {
		if(read_uint8(f) & RES_LOADED)
			agi_load_resource(rPICTURE, i);
		else
			agi_unload_resource(rPICTURE, i);
	}

	for (i = 0; i < MAX_DIRS; i++) {
		if(read_uint8(f) & RES_LOADED)
			agi_load_resource(rVIEW, i);
		else
			agi_unload_resource(rVIEW, i);
	}

	for(i = 0; i < MAX_DIRS; i++) {
		if(read_uint8(f) & RES_LOADED)
			agi_load_resource(rSOUND, i);
		else
			agi_unload_resource(rSOUND, i);
	}

	/* game.pictures - loaded above */
	/* game.logics - loaded above */
	/* game.views - loaded above */
	/* game.sounds - loaded above */

	for (i = 0; i < vt_entries; i++) {
		struct vt_entry* v = &game.view_table[i];

		v->step_time = read_uint8(f);
		v->step_time_count = read_uint8(f);
		v->entry = read_uint8(f);
		v->x_pos = read_sint16(f);
		v->y_pos = read_sint16(f);
		v->current_view = read_uint8(f);

		/* v->view_data - fixed below  */

		v->current_loop = read_uint8(f);
		v->num_loops = read_uint8(f);

		/* v->loop_data - fixed below  */

		v->current_cel = read_uint8(f);
		v->num_cels = read_uint8(f);

		/* v->cel_data - fixed below  */
		/* v->cel_data_2 - fixed below  */
		
		v->x_pos2 = read_sint16(f);
		v->y_pos2 = read_sint16(f);

		/* v->s - fixed below */

		v->x_size = read_sint16(f);
		v->y_size = read_sint16(f);
		v->step_size = read_uint8(f);
		v->cycle_time = read_uint8(f);
		v->cycle_time_count = read_uint8(f);
		v->direction = read_uint8(f);

		v->motion = read_uint8(f);
		v->cycle = read_uint8(f);
		v->priority = read_uint8(f);

		v->flags = read_uint16(f);
		
		v->parm1 = read_uint8(f);
		v->parm2 = read_uint8(f);
		v->parm3 = read_uint8(f);
		v->parm4 = read_uint8(f);
	}
	for (i = vt_entries; i < MAX_VIEWTABLE; i++) {
		memset (&game.view_table[i], 0, sizeof (struct vt_entry));
	}

	/* Fix some pointers in viewtable */

	for (i = 0; i < MAX_VIEWTABLE; i++) {
		struct vt_entry* v = &game.view_table[i];

		if(game.dir_view[v->current_view].offset == _EMPTY)
			continue;

		if(!(game.dir_view[v->current_view].flags & RES_LOADED))
			agi_load_resource(rVIEW, v->current_view);

		set_view(v, v->current_view); /* Fix v->view_data */
		set_loop(v, v->current_loop); /* Fix v->loop_data */
		set_cel(v, v->current_cel);   /* Fix v->cel_data */
		v->cel_data_2 = v->cel_data;
		v->s = NULL;		/* not sure if it is used... */
	}

	erase_both();

	/* Clear input line */
	clear_screen(0);
	write_status();

	/* Recreate background from saved image stack */
	clear_image_stack();
	while ((t = read_uint8(f)) != 0) {
		for (i = 0; i < 7; i++)
			parm[i] = read_sint16(f);
		replay_image_stack_call (t, parm[0], parm[1], parm[2],
			parm[3], parm[4], parm[5], parm[6]);
	}

	fclose(f);

	setflag(F_restore_just_ran, TRUE);

	game.has_prompt = 0;	/* force input line repaint if necessary*/
	clean_input();
	
	erase_both();
	blit_both();
	commit_both();
	show_pic();
	do_update();

	return err_OK;
}
示例#19
0
    int read_page()
    {
        int sum = 0;
        int bytes_read = 0;

        char record_command = read_bytes(1, &bytes_read, &sum); // Always 0x89

        if ((0xff & record_command) == 0x89)
        {
            // 1. page # data
            int page_number = read_bytes(2, &bytes_read, &sum); // Page #
            int data_number = read_bytes(1, &bytes_read, &sum); // # of data in page



            if (page_number == 1 || (page_number == 64010 and secs == 0.0)) {
                // 2. Training Summary data (60 bytes)";
                read_bytes(39, &bytes_read, &sum);

                int record_training_flag = read_bytes(1, &bytes_read, &sum); // Training Flag

                if ((record_training_flag & 0x01) == 0) {
                    // Only new lap
                    rideFile->addInterval(last_interval_secs, secs, QString("%1").arg(interval));
                    last_interval_secs = secs;
                    interval ++;
                }

                read_bytes(20, &bytes_read, &sum); // Don't care
            }

            if (page_number == 1 || (page_number == 64010 and secs == 0.0)) {
                // Section Start time and date data (12 byte)

                int sec = read_bsd_byte(&bytes_read, &sum); // Section start time sec
                int min = read_bsd_byte(&bytes_read, &sum); // Section start time min
                int hour = read_bsd_byte(&bytes_read, &sum); // Section start time hour
                int day = read_bsd_byte(&bytes_read, &sum); // Section start time day
                int month = read_bytes(1, &bytes_read, &sum); // Section start time month
                int year = read_bsd_byte(&bytes_read, &sum); // Section start time year

                QDateTime t = QDateTime(QDate(2000+year,month,day), QTime(hour,min,sec));

                if (secs == 0.0 || rideFile->startTime().toTime_t()<0) {
                    rideFile->setStartTime(t);
                }
                else {
                    int gap = (t.toTime_t() - rideFile->startTime().toTime_t()) - secs;
                    secs += gap;
                }

                read_bytes(5, &bytes_read, &sum); // Don't care

                read_bytes(1, &bytes_read, &sum); // Data Flag
                data_number--;
            }

            for (int i = 0; i < data_number; ++i) {
                read_graph_data(&secs, &bytes_read, &sum);
            }

            int finish = 259-bytes_read;

            for (int i = 0; i < finish; i++) {
                read_bytes(1, &bytes_read, &sum); // to finish
            }

            read_bytes(1, &bytes_read, &sum); // Checksum
        }

        return bytes_read;
    }
示例#20
0
文件: savegame.c 项目: UIKit0/sarien
static int select_slot (char *path)
{
	int i, key, active = 0;
	int rc = -1;
	int hm = 2, vm = 3;			/* box margins */
	char desc[NUM_SLOTS][40];

	for (i = 0; i < NUM_SLOTS; i++) {
		char name[MAX_PATH];
		FILE *f;
		char sig[8];
		sprintf (name, "%s/%08d.sav", path, i);
		f = fopen (name, "rb");
		if (f == NULL) {
			strcpy (desc[i], "          (empty slot)");
		} else {
			read_bytes (f, sig, 8);
			if (strncmp (sig, strSig, 8)) {
				strcpy (desc[i], "(corrupt file)");
			} else {
				read_string (f, desc[i]);
			}
			fclose(f);
		}
	}

	while (42) {
		char dstr[64];
		for (i = 0; i < NUM_SLOTS; i++) {
			sprintf (dstr, "[%-32.32s]", desc[i]);
			print_text (dstr, 0, hm + 1, vm + 4 + i,
				(40 - 2 * hm) - 1,
				i == active ? MSG_BOX_COLOUR : MSG_BOX_TEXT,
				i == active ? MSG_BOX_TEXT : MSG_BOX_COLOUR);

		}

		poll_timer ();		/* msdos driver -> does nothing */
		key = do_poll_keyboard ();
		if (!console_keyhandler (key)) {
			switch (key) {
			case KEY_ENTER:
				rc = active;
				strncpy (game.strings[MAX_STRINGS],
					desc[i], MAX_STRINGLEN);
				goto press;
			case KEY_ESCAPE:
				rc = -1;
				goto getout;
#ifdef USE_MOUSE
			case BUTTON_LEFT:
				break;
#endif
			case KEY_DOWN:
				active++;
				active %= NUM_SLOTS;
				break;
			case KEY_UP:
				active--;
				if (active < 0)
					active = NUM_SLOTS - 1;
				break;
			}
		}
		console_cycle ();
	}

press:
	_D (_D_WARN "Button pressed: %d", rc);

getout:
	close_window();
	return rc;
}
示例#21
0
unsigned char *read_den(char *filename,int *xptr,int *yptr,int *zptr)
{
    FILE *fd;			/* file descriptor */
    unsigned char *data;	/* data array */
    int swapbytes;		/* true if header must be byte-swapped */
    short map_version;		/* Version of this .den file                 */
    short orig_min[3];		/* Dimensions of original data file          */
    short orig_max[3];
    short orig_len[3];
    short extr_min[3];		/* Extracted portion of original file        */
    short extr_max[3];		/*   (mins and maxes will be subset of       */
    short extr_len[3];		/*    orig and lengths will be <= orig)      */
    short map_min[3];		/* Dimensions of this map                    */
    short map_max[3];		/*   (mins will be 0 in this program and     */
    short map_len[3];		/*    lens may be != extr if warps > 0)      */
    short map_warps;		/* Number of warps since extraction          */
				/*   (0 = none)                              */
    int map_length;		/* Total number of densities in map          */
				/*   (= product of lens)                     */
	
    /* open the file */
    if ((fd = fopen(filename, "rb")) == NULL) {
		fprintf(stderr, "cannot open file %s\n", filename);
		return(NULL);
    }
	
    /* read the magic number */
    if (!read_shorts(fd, &map_version, 1, 0)) {
		fprintf(stderr, "read failed on file %s (empty file?)\n", filename);
		return(NULL);
    }
    if (map_version == MAP_CUR_VERSION) {
		swapbytes = 0;
    } else if (map_version == MAP_CUR_VERSION_SWAB) {
		swapbytes = 1;
    } else {
		fprintf(stderr, "file %s is not a density file\n", filename);
		return(NULL);
    }
	
    /* read the volume size information */
    if (!read_shorts(fd, orig_min, 3, swapbytes) ||
		!read_shorts(fd, orig_max, 3, swapbytes) ||
		!read_shorts(fd, orig_len, 3, swapbytes) ||
		!read_shorts(fd, extr_min, 3, swapbytes) ||
		!read_shorts(fd, extr_max, 3, swapbytes) ||
		!read_shorts(fd, extr_len, 3, swapbytes) ||
		!read_shorts(fd, map_min, 3, swapbytes) ||
		!read_shorts(fd, map_max, 3, swapbytes) ||
		!read_shorts(fd, map_len, 3, swapbytes) ||
		!read_shorts(fd, &map_warps, 1, swapbytes) ||
		!read_words(fd, &map_length, 1, swapbytes)) {
		fprintf(stderr, "read failed on file %s (truncated file?)\n",filename);
		return(NULL);
    }
    if (map_length != map_len[0]*map_len[1]*map_len[2]) {
		fprintf(stderr, "density file %s has an inconsistent header\n",
			filename);
		return(NULL);
    }
	
    /* allocate array for data */
    data = (unsigned char *)malloc(map_length);
    if (data == NULL) {
		fprintf(stderr, "out of memory\n");
		return(NULL);
    }
	
    /* copy the data from the file */
    if (!read_bytes(fd, (char *)data, map_length)) {
		fprintf(stderr, "read failed on file %s\n", filename);
		fclose(fd);
		free(data);
		return(NULL);
    }
	
    /* finish up */
    fclose(fd);
    *xptr = map_len[0];
    *yptr = map_len[1];
    *zptr = map_len[2];
    return(data);
}
示例#22
0
static bool
read_s8(struct dwbuf *d, int8_t *v)
{
	return (read_bytes(d, v, sizeof(*v)));
}
示例#23
0
static bool file_reader(cmp_ctx_t *ctx, void *data, size_t limit) {
	return read_bytes(data, limit, (FILE *) ctx->buf);
}
示例#24
0
static bool
read_u64(struct dwbuf *d, uint64_t *v)
{
	return (read_bytes(d, v, sizeof(*v)));
}
示例#25
0
int read_fragment_table_3()
{
	int res, i, indexes = SQUASHFS_FRAGMENT_INDEXES_3(sBlk.fragments);
	squashfs_fragment_index fragment_table_index[indexes];

	TRACE("read_fragment_table: %d fragments, reading %d fragment indexes "
		"from 0x%llx\n", sBlk.fragments, indexes,
		sBlk.fragment_table_start);

	if(sBlk.fragments == 0)
		return -1;

	if((fragment_table = malloc(sBlk.fragments *
			sizeof(squashfs_fragment_entry_3))) == NULL)
		EXIT_UNSQUASH("read_fragment_table: failed to allocate "
			"fragment table\n");

	if(swap) {
		squashfs_fragment_index sfragment_table_index[indexes];

		res = read_bytes(sBlk.fragment_table_start,
			SQUASHFS_FRAGMENT_INDEX_BYTES_3(sBlk.fragments),
			(char *) sfragment_table_index);
		if(res == FALSE) {
			ERROR("read_fragment_table: failed to read fragment "
				"table index\n");       
			return FALSE;
		}
		SQUASHFS_SWAP_FRAGMENT_INDEXES_3(fragment_table_index,
			sfragment_table_index, indexes);
	} else {
		res = read_bytes(sBlk.fragment_table_start,
			SQUASHFS_FRAGMENT_INDEX_BYTES_3(sBlk.fragments),
			(char *) fragment_table_index);
		if(res == FALSE) {
			ERROR("read_fragment_table: failed to read fragment "
				"table index\n");       
			return FALSE;
		}
	}

	for(i = 0; i < indexes; i++) {
		int length = read_block(fragment_table_index[i], NULL,
			((char *) fragment_table) + (i *
			SQUASHFS_METADATA_SIZE));
		TRACE("Read fragment table block %d, from 0x%llx, length %d\n",
			i, fragment_table_index[i], length);
		if(length == FALSE) {
			ERROR("read_fragment_table: failed to read fragment "
				"table block\n");       
			return FALSE;
		}
	}

	if(swap) {
		squashfs_fragment_entry_3 sfragment;
		for(i = 0; i < sBlk.fragments; i++) {
			SQUASHFS_SWAP_FRAGMENT_ENTRY_3((&sfragment),
				(&fragment_table[i]));
			memcpy((char *) &fragment_table[i], (char *) &sfragment,
				sizeof(squashfs_fragment_entry_3));
		}
	}

	return TRUE;
}
示例#26
0
/*
 * Check whether this is a pcap-ng savefile and, if it is, extract the
 * relevant information from the header.
 */
int
pcap_ng_check_header(pcap_t *p, bpf_u_int32 magic, FILE *fp, char *errbuf, int isng)
{
	size_t amt_read;
	bpf_u_int32 total_length;
	bpf_u_int32 byte_order_magic;
	struct pcapng_block_header *bhdrp;
	struct pcapng_section_header_fields *shbp;
	int status;
	struct block_cursor cursor;
	struct pcapng_interface_description_fields *idbp;
	long file_offset = ftell(fp);
	
	/*
	 * Check whether the first 4 bytes of the file are the block
	 * type for a pcap-ng savefile.
	 */
	if (magic != PCAPNG_BT_SHB) {
		/*
		 * XXX - check whether this looks like what the block
		 * type would be after being munged by mapping between
		 * UN*X and DOS/Windows text file format and, if it
		 * does, look for the byte-order magic number in
		 * the appropriate place and, if we find it, report
		 * this as possibly being a pcap-ng file transferred
		 * between UN*X and Windows in text file format?
		 */
		return (0);	/* nope */
	}
	
	/*
	 * OK, they are.  However, that's just \n\r\r\n, so it could,
	 * conceivably, be an ordinary text file.
	 *
	 * It could not, however, conceivably be any other type of
	 * capture file, so we can read the rest of the putative
	 * Section Header Block; put the block type in the common
	 * header, read the rest of the common header and the
	 * fixed-length portion of the SHB, and look for the byte-order
	 * magic value.
	 */
	amt_read = fread(&total_length, 1, sizeof(total_length), fp);
	if (amt_read < sizeof(total_length)) {
		if (ferror(fp)) {
			snprintf(errbuf, PCAP_ERRBUF_SIZE,
					 "error reading dump file: %s",
					 pcap_strerror(errno));
			return (-1);	/* fail */
		}
		
		/*
		 * Possibly a weird short text file, so just say
		 * "not pcap-ng".
		 */
		return (0);
	}
	amt_read = fread(&byte_order_magic, 1, sizeof(byte_order_magic), fp);
	if (amt_read < sizeof(byte_order_magic)) {
		if (ferror(fp)) {
			snprintf(errbuf, PCAP_ERRBUF_SIZE,
					 "error reading dump file: %s",
					 pcap_strerror(errno));
			return (-1);	/* fail */
		}
		
		/*
		 * Possibly a weird short text file, so just say
		 * "not pcap-ng".
		 */
		return (0);
	}
	if (byte_order_magic != PCAPNG_BYTE_ORDER_MAGIC) {
		byte_order_magic = SWAPLONG(byte_order_magic);
		if (byte_order_magic != PCAPNG_BYTE_ORDER_MAGIC) {
			/*
			 * Not a pcap-ng file.
			 */
			return (0);
		}
		p->sf.swapped = 1;
		total_length = SWAPLONG(total_length);
	}
	
	/*
	 * Check the sanity of the total length.
	 */
	if (total_length < sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct pcapng_block_trailer)) {
		snprintf(errbuf, PCAP_ERRBUF_SIZE,
				 "Section Header Block in pcap-ng dump file has a length of %u < %lu",
				 total_length,
				 (unsigned long)(sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct pcapng_block_trailer)));
		return (-1);
	}
	
	/*
	 * Allocate a buffer into which to read blocks.  We default to
	 * the maximum of:
	 *
	 *	the total length of the SHB for which we read the header;
	 *
	 *	2K, which should be more than large enough for an Enhanced
	 *	Packet Block containing a full-size Ethernet frame, and
	 *	leaving room for some options.
	 *
	 * If we find a bigger block, we reallocate the buffer.
	 */
	p->bufsize = 2048;
	if (p->bufsize < total_length)
		p->bufsize = total_length;
	p->buffer = malloc(p->bufsize);
	if (p->buffer == NULL) {
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory");
		return (-1);
	}
	
	/*
	 * Copy the stuff we've read to the buffer, and read the rest
	 * of the SHB.
	 */
	bhdrp = (struct pcapng_block_header *)p->buffer;
	shbp = (struct pcapng_section_header_fields *)(p->buffer + sizeof(struct pcapng_block_header));
	bhdrp->block_type = magic;
	bhdrp->total_length = total_length;
	shbp->byte_order_magic = byte_order_magic;
	if (read_bytes(fp,
				   p->buffer + (sizeof(magic) + sizeof(total_length) + sizeof(byte_order_magic)),
				   total_length - (sizeof(magic) + sizeof(total_length) + sizeof(byte_order_magic)),
				   1, errbuf) == -1)
		goto fail;
	
	if (p->sf.swapped) {
		/*
		 * Byte-swap the fields we've read.
		 */
		shbp->major_version = SWAPSHORT(shbp->major_version);
		shbp->minor_version = SWAPSHORT(shbp->minor_version);
		
		/*
		 * XXX - we don't care about the section length.
		 */
	}
	if (shbp->major_version != PCAPNG_VERSION_MAJOR) {
		snprintf(errbuf, PCAP_ERRBUF_SIZE,
				 "unknown pcap-ng savefile major version number %u",
				 shbp->major_version);
		goto fail;
	}
	p->sf.version_major = shbp->major_version;
	p->sf.version_minor = shbp->minor_version;
	
	/*
	 * Set the default time stamp resolution and offset.
	 */
	p->sf.tsresol = 1000000;	/* microsecond resolution */
	p->sf.tsscale = 1;		/* multiply by 1 to scale to microseconds */
	p->sf.tsoffset = 0;		/* absolute timestamps */
	
	/*
	 * Now start looking for an Interface Description Block.
	 */
	for (;;) {
		/*
		 * Read the next block.
		 */
		status = read_block(fp, p, &cursor, errbuf);
		if (status == 0) {
			/* EOF - no IDB in this file */
			snprintf(errbuf, PCAP_ERRBUF_SIZE,
					 "the capture file has no Interface Description Blocks");
			goto fail;
		}
		if (status == -1)
			goto fail;	/* error */
		switch (cursor.block_type) {
				
			case PCAPNG_BT_IDB:
				/*
				 * Get a pointer to the fixed-length portion of the
				 * IDB.
				 */
				idbp = get_from_block_data(&cursor, sizeof(*idbp),
										   errbuf);
				if (idbp == NULL)
					goto fail;	/* error */
				
				/*
				 * Byte-swap it if necessary.
				 */
				if (p->sf.swapped) {
					idbp->linktype = SWAPSHORT(idbp->linktype);
					idbp->snaplen = SWAPLONG(idbp->snaplen);
				}
				
				/*
				 * Now look for various time stamp options, so
				 * we know how to interpret the time stamps.
				 */
				if (process_idb_options(p, idbp, &cursor, &p->sf.tsresol,
										&p->sf.tsoffset, errbuf) == -1)
					goto fail;
				
				/*
				 * Compute the scaling factor to convert the
				 * sub-second part of the time stamp to
				 * microseconds.
				 */
				if (p->sf.tsresol > 1000000) {
					/*
					 * Higher than microsecond resolution;
					 * scale down to microseconds.
					 */
					p->sf.tsscale = (p->sf.tsresol / 1000000);
				} else {
					/*
					 * Lower than microsecond resolution;
					 * scale up to microseconds.
					 */
					p->sf.tsscale = (1000000 / p->sf.tsresol);
				}
				p->tzoff = 0;	/* XXX - not used in pcap */
				p->snapshot = idbp->snaplen;
				p->linktype = linktype_to_dlt(idbp->linktype);
				p->linktype_ext = 0;
				goto done;
				
			case PCAPNG_BT_EPB:
			case PCAPNG_BT_SPB:
			case PCAPNG_BT_PB:
				/*
				 * Saw a packet before we saw any IDBs.  That's
				 * not valid, as we don't know what link-layer
				 * encapsulation the packet has.
				 */
				snprintf(errbuf, PCAP_ERRBUF_SIZE,
						 "the capture file has a packet block before any Interface Description Blocks");
				goto fail;
				
			default:
				/*
				 * Just ignore it.
				 */
				break;
		}
	}
	
done:
	p->sf.next_packet_op = isng ? pcap_ng_next_block : pcap_ng_next_packet;
	
	/*
	 * Special using block based API
	 */
	if (isng) {
		/*
		 * Rewind to begining of Section Header Block
		 */
		if (file_offset < 4) {
			snprintf(errbuf, PCAP_ERRBUF_SIZE, "bad file offset");
			goto fail;
		}
		file_offset -= 4;
		fseek(fp, file_offset, SEEK_SET);
		
		p->linktype = DLT_PCAPNG;
	}
	
	return (1);
	
fail:
	free(p->buffer);
	return (-1);
}
示例#27
0
dsk_err_t w32serial_call(DSK_PDRIVER pDriver, unsigned char *input, 
		int inp_len, unsigned char *output, int *out_len)
{
	word16 wire_len;
	word16 crc;
	byte var;
	byte wvar[2];
	int n;
	dsk_err_t err;
	unsigned char *tmpbuf;

	W32SERIAL_REMOTE_DATA *self = (W32SERIAL_REMOTE_DATA *)pDriver->dr_remote;	
	if (!self || self->super.rd_class != &rpc_w32serial) return DSK_ERR_BADPTR;
	/* CRC tbe input... */
	wire_len = inp_len;
	CRC_Clear();
	for (n = 0; n < inp_len; n++) CRC_Update(input[n]);
	crc = CRC_Done();
/* 
	printf("rpc_w32serial: Input packet: ");
	for (n = 0; n < inp_len; n++) printf("%02x ", input[n]);
	printf("\n");
*/
	while (1)
	{
		/* Write SOH (start of request) */
		err = wrbyte(self, SOH); if (err) return err;
		/* Write packet length (network byte order) */
		wvar[0] = wire_len >> 8; 
		wvar[1] = wire_len & 0xFF;
		err = write_bytes(self, 2, wvar); 
		if (err) return err;
		err = write_bytes(self, inp_len, input);
		if (err) return err;
		wvar[0] = crc >> 8; 
		wvar[1] = crc & 0xFF;
		err = write_bytes(self, 2, wvar); 
		if (err) return err;

/*
		err = read_bytes(self, 1, &var); if (err) return err;
*/
/* Wait 'til we get an ACK or a NAK. */
		do
		{
			err = read_bytes(self, 1, &var); 
			if (err) return err;
		}
		while(var != ACK && var != NAK);
		if (var == ACK) break;
		if (var == NAK) continue;
	}
	/* Outgoing packet sent. Await response */
	while (1)
	{
		/* First byte of response must be STX. */
		err = read_bytes(self, 1, &var); if (err) return err;
		if (var != STX) continue;
		err = read_bytes(self, 2, wvar); if (err) return err;
		wire_len   = wvar[0];
		wire_len   = (wire_len << 8) | wvar[1];
		tmpbuf = dsk_malloc(wire_len + 2);
		if (!tmpbuf) return DSK_ERR_NOMEM;
		CRC_Clear();
		err = read_bytes(self, wire_len + 2, tmpbuf); 
		if (err) { dsk_free(tmpbuf); return err; }
		for (n = 0; n < wire_len; n++)
		{
			CRC_Update(tmpbuf[n]);
		}
		crc = tmpbuf[wire_len];
		crc = (crc << 8) | tmpbuf[wire_len + 1];
		/* If CRC matches, send ACK and return. Else send NAK. */
		if (crc == CRC_Done())
		{
/*
	printf("rpc_w32serial: Result packet: ");
	for (n = 0; n < wire_len; n++) printf("%02x ", tmpbuf[n]);
	printf("\n");
*/
			err = wrbyte(self, ACK);
			if (err) { dsk_free(tmpbuf); return err; }
/* Copy packet to waiting output buffer */
			if (wire_len < *out_len) *out_len = wire_len;
			memcpy(output, tmpbuf, *out_len);
			dsk_free(tmpbuf);
			return DSK_ERR_OK;
		}
/* Packet was garbled. NAK it and try again. */
		dsk_free(tmpbuf);
		err = wrbyte(self, NAK);
		if (err) return err;
	}
	/* Should never happen */
	return DSK_ERR_NOTIMPL;
}
示例#28
0
int read_super(int fd, squashfs_super_block *sBlk, int *be, char *source)
{
	squashfs_super_block sblk;

	read_bytes(fd, SQUASHFS_START, sizeof(squashfs_super_block), (char *) sBlk);

	/* Check it is a SQUASHFS superblock */
	swap = 0;
	switch (sBlk->s_magic) {
	case SQUASHFS_MAGIC_LZMA:
		if (!lzma)
			goto bad;
		break;
	case SQUASHFS_MAGIC:
		break;
	case SQUASHFS_MAGIC_SWAP:
	case SQUASHFS_MAGIC_LZMA_SWAP:
		ERROR("Reading a different endian SQUASHFS filesystem on %s - ignoring -le/-be options\n", source);
		SQUASHFS_SWAP_SUPER_BLOCK(&sblk, sBlk);
		memcpy(sBlk, &sblk, sizeof(squashfs_super_block));
		swap = 1;
		break;
	bad:
	default:
		ERROR("Can't find a SQUASHFS superblock on %s\n", source);
		goto failed_mount;
 	}

	/* Check the MAJOR & MINOR versions */
	if(sBlk->s_major != SQUASHFS_MAJOR || sBlk->s_minor > SQUASHFS_MINOR) {
		if(sBlk->s_major < 3)
			ERROR("Filesystem on %s is a SQUASHFS %d.%d filesystem.  Appending\nto SQUASHFS %d.%d filesystems is not supported.  Please convert it to a SQUASHFS 3.0 filesystem\n", source, sBlk->s_major, sBlk->s_minor, sBlk->s_major, sBlk->s_minor);
		else
			ERROR("Major/Minor mismatch, filesystem on %s is %d.%d, I support 3.0\n",
				source, sBlk->s_major, sBlk->s_minor);
		goto failed_mount;
	}

#if __BYTE_ORDER == __BIG_ENDIAN
	*be = !swap;
#else
	*be = swap;
#endif

	printf("Found a valid %s%s SQUASHFS superblock on %s.\n", SQUASHFS_EXPORTABLE(sBlk->flags) ? "exportable " : "", *be ? "big endian" : "little endian", source);
	printf("\tInodes are %scompressed\n", SQUASHFS_UNCOMPRESSED_INODES(sBlk->flags) ? "un" : "");
	printf("\tData is %scompressed\n", SQUASHFS_UNCOMPRESSED_DATA(sBlk->flags) ? "un" : "");
	printf("\tFragments are %scompressed\n", SQUASHFS_UNCOMPRESSED_FRAGMENTS(sBlk->flags) ? "un" : "");
	printf("\tCheck data is %spresent in the filesystem\n", SQUASHFS_CHECK_DATA(sBlk->flags) ? "" : "not ");
	printf("\tFragments are %spresent in the filesystem\n", SQUASHFS_NO_FRAGMENTS(sBlk->flags) ? "not " : "");
	printf("\tAlways_use_fragments option is %sspecified\n", SQUASHFS_ALWAYS_FRAGMENTS(sBlk->flags) ? "" : "not ");
	printf("\tDuplicates are %sremoved\n", SQUASHFS_DUPLICATES(sBlk->flags) ? "" : "not ");
	printf("\tFilesystem size %.2f Kbytes (%.2f Mbytes)\n", sBlk->bytes_used / 1024.0, sBlk->bytes_used / (1024.0 * 1024.0));
	printf("\tBlock size %d\n", sBlk->block_size);
	printf("\tNumber of fragments %d\n", sBlk->fragments);
	printf("\tNumber of inodes %d\n", sBlk->inodes);
	printf("\tNumber of uids %d\n", sBlk->no_uids);
	printf("\tNumber of gids %d\n", sBlk->no_guids);
	TRACE("sBlk->inode_table_start %llx\n", sBlk->inode_table_start);
	TRACE("sBlk->directory_table_start %llx\n", sBlk->directory_table_start);
	TRACE("sBlk->uid_start %llx\n", sBlk->uid_start);
	TRACE("sBlk->fragment_table_start %llx\n", sBlk->fragment_table_start);
	TRACE("sBlk->lookup_table_start %xllx\n", sBlk->lookup_table_start);
	printf("\n");

	return TRUE;

failed_mount:
	return FALSE;
}
/*
 * Check whether this is a pcap-ng savefile and, if it is, extract the
 * relevant information from the header.
 */
pcap_t *
pcap_ng_check_header(bpf_u_int32 magic, FILE *fp, u_int precision, char *errbuf,
    int *err)
{
	size_t amt_read;
	bpf_u_int32 total_length;
	bpf_u_int32 byte_order_magic;
	struct block_header *bhdrp;
	struct section_header_block *shbp;
	pcap_t *p;
	int swapped = 0;
	struct pcap_ng_sf *ps;
	int status;
	struct block_cursor cursor;
	struct interface_description_block *idbp;

	/*
	 * Assume no read errors.
	 */
	*err = 0;

	/*
	 * Check whether the first 4 bytes of the file are the block
	 * type for a pcap-ng savefile.
	 */
	if (magic != BT_SHB) {
		/*
		 * XXX - check whether this looks like what the block
		 * type would be after being munged by mapping between
		 * UN*X and DOS/Windows text file format and, if it
		 * does, look for the byte-order magic number in
		 * the appropriate place and, if we find it, report
		 * this as possibly being a pcap-ng file transferred
		 * between UN*X and Windows in text file format?
		 */
		return (NULL);	/* nope */
	}

	/*
	 * OK, they are.  However, that's just \n\r\r\n, so it could,
	 * conceivably, be an ordinary text file.
	 *
	 * It could not, however, conceivably be any other type of
	 * capture file, so we can read the rest of the putative
	 * Section Header Block; put the block type in the common
	 * header, read the rest of the common header and the
	 * fixed-length portion of the SHB, and look for the byte-order
	 * magic value.
	 */
	amt_read = fread(&total_length, 1, sizeof(total_length), fp);
	if (amt_read < sizeof(total_length)) {
		if (ferror(fp)) {
			snprintf(errbuf, PCAP_ERRBUF_SIZE,
			    "error reading dump file: %s",
			    pcap_strerror(errno));
			*err = 1;
			return (NULL);	/* fail */
		}

		/*
		 * Possibly a weird short text file, so just say
		 * "not pcap-ng".
		 */
		return (NULL);
	}
	amt_read = fread(&byte_order_magic, 1, sizeof(byte_order_magic), fp);
	if (amt_read < sizeof(byte_order_magic)) {
		if (ferror(fp)) {
			snprintf(errbuf, PCAP_ERRBUF_SIZE,
			    "error reading dump file: %s",
			    pcap_strerror(errno));
			*err = 1;
			return (NULL);	/* fail */
		}

		/*
		 * Possibly a weird short text file, so just say
		 * "not pcap-ng".
		 */
		return (NULL);
	}
	if (byte_order_magic != BYTE_ORDER_MAGIC) {
		byte_order_magic = SWAPLONG(byte_order_magic);
		if (byte_order_magic != BYTE_ORDER_MAGIC) {
			/*
			 * Not a pcap-ng file.
			 */
			return (NULL);
		}
		swapped = 1;
		total_length = SWAPLONG(total_length);
	}

	/*
	 * Check the sanity of the total length.
	 */
	if (total_length < sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer)) {
		snprintf(errbuf, PCAP_ERRBUF_SIZE,
		    "Section Header Block in pcap-ng dump file has a length of %u < %lu",
		    total_length,
		    (unsigned long)(sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer)));
		*err = 1;
		return (NULL);
	}

	/*
	 * OK, this is a good pcap-ng file.
	 * Allocate a pcap_t for it.
	 */
	p = pcap_open_offline_common(errbuf, sizeof (struct pcap_ng_sf));
	if (p == NULL) {
		/* Allocation failed. */
		*err = 1;
		return (NULL);
	}
	p->swapped = swapped;
	ps = p->priv;

	/*
	 * What precision does the user want?
	 */
	switch (precision) {

	case PCAP_TSTAMP_PRECISION_MICRO:
		ps->user_tsresol = 1000000;
		break;

	case PCAP_TSTAMP_PRECISION_NANO:
		ps->user_tsresol = 1000000000;
		break;

	default:
		snprintf(errbuf, PCAP_ERRBUF_SIZE,
		    "unknown time stamp resolution %u", precision);
		free(p);
		*err = 1;
		return (NULL);
	}

	p->opt.tstamp_precision = precision;

	/*
	 * Allocate a buffer into which to read blocks.  We default to
	 * the maximum of:
	 *
	 *	the total length of the SHB for which we read the header;
	 *
	 *	2K, which should be more than large enough for an Enhanced
	 *	Packet Block containing a full-size Ethernet frame, and
	 *	leaving room for some options.
	 *
	 * If we find a bigger block, we reallocate the buffer.
	 */
	p->bufsize = 2048;
	if (p->bufsize < (int)total_length)
		p->bufsize = total_length;
	p->buffer = malloc(p->bufsize);
	if (p->buffer == NULL) {
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory");
		free(p);
		*err = 1;
		return (NULL);
	}

	/*
	 * Copy the stuff we've read to the buffer, and read the rest
	 * of the SHB.
	 */
	bhdrp = (struct block_header *)(void *)p->buffer;
	shbp = (struct section_header_block *)(void *)(p->buffer + sizeof(struct block_header));
	bhdrp->block_type = magic;
	bhdrp->total_length = total_length;
	shbp->byte_order_magic = byte_order_magic;
	if (read_bytes(fp,
	    p->buffer + (sizeof(magic) + sizeof(total_length) + sizeof(byte_order_magic)),
	    total_length - (sizeof(magic) + sizeof(total_length) + sizeof(byte_order_magic)),
	    1, errbuf) == -1)
		goto fail;

	if (p->swapped) {
		/*
		 * Byte-swap the fields we've read.
		 */
		shbp->major_version = SWAPSHORT((uint32_t)shbp->major_version);
		shbp->minor_version = SWAPSHORT((uint32_t)shbp->minor_version);

		/*
		 * XXX - we don't care about the section length.
		 */
	}
	if (shbp->major_version != PCAP_NG_VERSION_MAJOR) {
		snprintf(errbuf, PCAP_ERRBUF_SIZE,
		    "unknown pcap-ng savefile major version number %u",
		    shbp->major_version);
		goto fail;
	}
	p->version_major = shbp->major_version;
	p->version_minor = shbp->minor_version;

	/*
	 * Save the time stamp resolution the user requested.
	 */
	p->opt.tstamp_precision = precision;

	/*
	 * Now start looking for an Interface Description Block.
	 */
	for (;;) {
		/*
		 * Read the next block.
		 */
		status = read_block(fp, p, &cursor, errbuf);
		if (status == 0) {
			/* EOF - no IDB in this file */
			snprintf(errbuf, PCAP_ERRBUF_SIZE,
			    "the capture file has no Interface Description Blocks");
			goto fail;
		}
		if (status == -1)
			goto fail;	/* error */
		switch (cursor.block_type) {

		case BT_IDB:
			/*
			 * Get a pointer to the fixed-length portion of the
			 * IDB.
			 */
			idbp = get_from_block_data(&cursor, sizeof(*idbp),
			    errbuf);
			if (idbp == NULL)
				goto fail;	/* error */

			/*
			 * Byte-swap it if necessary.
			 */
			if (p->swapped) {
				idbp->linktype = SWAPSHORT((uint16_t)idbp->linktype);
				idbp->snaplen = SWAPLONG(idbp->snaplen);
			}

			/*
			 * Try to add this interface.
			 */
			if (!add_interface(p, &cursor, errbuf))
				goto fail;
			goto done;

		case BT_EPB:
		case BT_SPB:
		case BT_PB:
			/*
			 * Saw a packet before we saw any IDBs.  That's
			 * not valid, as we don't know what link-layer
			 * encapsulation the packet has.
			 */
			snprintf(errbuf, PCAP_ERRBUF_SIZE,
			    "the capture file has a packet block before any Interface Description Blocks");
			goto fail;

		default:
			/*
			 * Just ignore it.
			 */
			break;
		}
	}

done:
	p->tzoff = 0;	/* XXX - not used in pcap */
	p->snapshot = idbp->snaplen;
	p->linktype = linktype_to_dlt(idbp->linktype);
	p->linktype_ext = 0;

	p->next_packet_op = pcap_ng_next_packet;
	p->cleanup_op = pcap_ng_cleanup;

	return (p);

fail:
	free(ps->ifaces);
	free(p->buffer);
	free(p);
	*err = 1;
	return (NULL);
}
示例#30
0
long long read_filesystem(char *root_name, int fd, squashfs_super_block *sBlk, char **cinode_table,
		char **data_cache, char **cdirectory_table, char **directory_data_cache,
		unsigned int *last_directory_block, unsigned int *inode_dir_offset, unsigned int *inode_dir_file_size,
		unsigned int *root_inode_size, unsigned int *inode_dir_start_block, int *file_count, int *sym_count,
		int *dev_count, int *dir_count, int *fifo_count, int *sock_count, squashfs_uid *uids,
		unsigned short *uid_count, squashfs_uid *guids, unsigned short *guid_count,
		long long *uncompressed_file, unsigned int *uncompressed_inode, unsigned int *uncompressed_directory,
		unsigned int *inode_dir_inode_number, unsigned int *inode_dir_parent_inode,
		void (push_directory_entry)(char *, squashfs_inode, int, int), squashfs_fragment_entry **fragment_table,
		squashfs_inode **inode_lookup_table)
{
	unsigned char *inode_table = NULL, *directory_table;
	long long start = sBlk->inode_table_start, end = sBlk->directory_table_start, root_inode_start = start +
		SQUASHFS_INODE_BLK(sBlk->root_inode);
	unsigned int root_inode_offset = SQUASHFS_INODE_OFFSET(sBlk->root_inode), root_inode_block, files;
	squashfs_inode_header inode;

	printf("Scanning existing filesystem...\n");

	if(read_fragment_table(fd, sBlk, fragment_table) == 0)
		goto error;

	if(read_inode_lookup_table(fd, sBlk, inode_lookup_table) == 0)
		goto error;

	if((files = scan_inode_table(fd, start, end, root_inode_start, root_inode_offset, sBlk, &inode, &inode_table,
			&root_inode_block, root_inode_size, uncompressed_file, uncompressed_directory, file_count, sym_count,
			dev_count, dir_count, fifo_count, sock_count)) == 0) {
		ERROR("read_filesystem: inode table read failed\n");
		goto error;
	}

	*uncompressed_inode = root_inode_block;

	printf("Read existing filesystem, %d inodes scanned\n", files);

	if(inode.base.inode_type == SQUASHFS_DIR_TYPE || inode.base.inode_type == SQUASHFS_LDIR_TYPE) {
		if(inode.base.inode_type == SQUASHFS_DIR_TYPE) {
			*inode_dir_start_block = inode.dir.start_block;
			*inode_dir_offset = inode.dir.offset;
			*inode_dir_file_size = inode.dir.file_size - 3;
			*inode_dir_inode_number = inode.dir.inode_number;
			*inode_dir_parent_inode = inode.dir.parent_inode;
		} else {
			*inode_dir_start_block = inode.ldir.start_block;
			*inode_dir_offset = inode.ldir.offset;
			*inode_dir_file_size = inode.ldir.file_size - 3;
			*inode_dir_inode_number = inode.ldir.inode_number;
			*inode_dir_parent_inode = inode.ldir.parent_inode;
		}

		if((directory_table = squashfs_readdir(fd, !root_name, *inode_dir_start_block, *inode_dir_offset,
				*inode_dir_file_size, last_directory_block, sBlk, push_directory_entry)) == NULL) {
			ERROR("read_filesystem: Could not read root directory\n");
			goto error;
		}

		root_inode_start -= start;
		if((*cinode_table = (char *) malloc(root_inode_start)) == NULL) {
			ERROR("read_filesystem: failed to alloc space for existing filesystem inode table\n");
			goto error;
		}
	       	read_bytes(fd, start, root_inode_start, *cinode_table);

		if((*cdirectory_table = (char *) malloc(*last_directory_block)) == NULL) {
			ERROR("read_filesystem: failed to alloc space for existing filesystem directory table\n");
			goto error;
		}
		read_bytes(fd, sBlk->directory_table_start, *last_directory_block, *cdirectory_table);

		if((*data_cache = (char *) malloc(root_inode_offset + *root_inode_size)) == NULL) {
			ERROR("read_filesystem: failed to alloc inode cache\n");
			goto error;
		}
		memcpy(*data_cache, inode_table + root_inode_block, root_inode_offset + *root_inode_size);

		if((*directory_data_cache = (char *) malloc(*inode_dir_offset + *inode_dir_file_size)) == NULL) {
			ERROR("read_filesystem: failed to alloc directory cache\n");
			goto error;
		}
		memcpy(*directory_data_cache, directory_table, *inode_dir_offset + *inode_dir_file_size);

		if(!swap)
			read_bytes(fd, sBlk->uid_start, sBlk->no_uids * sizeof(squashfs_uid), (char *) uids);
		else {
			squashfs_uid uids_copy[sBlk->no_uids];

			read_bytes(fd, sBlk->uid_start, sBlk->no_uids * sizeof(squashfs_uid), (char *) uids_copy);
			SQUASHFS_SWAP_DATA(uids, uids_copy, sBlk->no_uids, sizeof(squashfs_uid) * 8);
		}

		if(!swap)
			read_bytes(fd, sBlk->guid_start, sBlk->no_guids * sizeof(squashfs_uid), (char *) guids);
		else {
			squashfs_uid guids_copy[sBlk->no_guids];

			read_bytes(fd, sBlk->guid_start, sBlk->no_guids * sizeof(squashfs_uid), (char *) guids_copy);
			SQUASHFS_SWAP_DATA(guids, guids_copy, sBlk->no_guids, sizeof(squashfs_uid) * 8);
		}
		*uid_count = sBlk->no_uids;
		*guid_count = sBlk->no_guids;

		free(inode_table);
		free(directory_table);
		return sBlk->inode_table_start;
	}

error:
	return 0;
}