int sh_speed(int argc, char ** argv) { uint16_t timeout = 0; int left; int right; int ok; if (argc < 3) { cprintf("correct usage:\r\n"); cprintf("\t%c [o] LEFT RIGHT <TIMEOUT>\r\n", argv[0]); return -1; } if (argc > 3) { timeout = read_uint16(argv[3], &ok); timer_start_cb(timer_id, timeout, 1); } left = read_int16(argv[1], &ok); right = read_int16(argv[2], &ok); cprintf("%d %d\r\n",left, right); // speed_start(speed_l); // speed_start(speed_r); speed_setPoint(speed_l, left); speed_setPoint(speed_r, right); return 0; }
/* Finishes up reading and exploding of a frame. */ void MVM_bytecode_finish_frame(MVMThreadContext *tc, MVMCompUnit *cu, MVMStaticFrame *sf, MVMint32 dump_only) { MVMuint32 j; MVMuint8 *pos; MVMuint16 slvs; /* Ensure we've not already done this. */ if (sf->body.fully_deserialized) return; /* Acquire the update mutex on the CompUnit. */ MVM_reentrantmutex_lock(tc, (MVMReentrantMutex *)cu->body.update_mutex); /* Ensure no other thread has done this for us in the mean time. */ if (sf->body.fully_deserialized) { MVM_reentrantmutex_unlock(tc, (MVMReentrantMutex *)cu->body.update_mutex); return; } /* Locate start of frame body. */ pos = sf->body.frame_data_pos; /* Get the number of static lex values we'll need to apply. */ slvs = read_int16(pos, 40); /* Skip past header. */ pos += FRAME_HEADER_SIZE; /* Read the local types. */ if (sf->body.num_locals) { sf->body.local_types = MVM_malloc(sizeof(MVMuint16) * sf->body.num_locals); for (j = 0; j < sf->body.num_locals; j++) sf->body.local_types[j] = read_int16(pos, 2 * j); pos += 2 * sf->body.num_locals; } /* Read the lexical types. */ if (sf->body.num_lexicals) { /* Allocate names hash and types list. */ sf->body.lexical_types = MVM_malloc(sizeof(MVMuint16) * sf->body.num_lexicals); /* Read in data. */ if (sf->body.num_lexicals) { sf->body.lexical_names_list = MVM_malloc(sizeof(MVMLexicalRegistry *) * sf->body.num_lexicals); } for (j = 0; j < sf->body.num_lexicals; j++) { MVMString *name = get_heap_string(tc, cu, NULL, pos, 6 * j + 2); MVMLexicalRegistry *entry = MVM_calloc(1, sizeof(MVMLexicalRegistry)); MVM_ASSIGN_REF(tc, &(sf->common.header), entry->key, name); sf->body.lexical_names_list[j] = entry; entry->value = j; sf->body.lexical_types[j] = read_int16(pos, 6 * j); MVM_string_flatten(tc, name); MVM_HASH_BIND(tc, sf->body.lexical_names, name, entry) } pos += 6 * sf->body.num_lexicals; }
struct slave_sync_res *parse_master_response(struct mile_packet *packet) { struct data_buffer* rbuf = packet->rbuf; struct mile_message_header header; if (NULL == rbuf) { log_error( "read buffer is empty"); return NULL; } header.version_major = read_int8(rbuf); header.version_minor = read_int8(rbuf); header.message_type = read_int16(rbuf); header.message_id = read_int32(rbuf); log_debug( "数据包包头信息 -- 主版本号: %d, 小版本号: %d, 消息类型: 0x%x, 消息id: %d", header.version_major, header.version_minor, header.message_type, header.message_id); if (MT_DM_RS != header.message_type) { log_error( "unknown message type: %hu", header.message_type); return NULL; } // read body struct slave_sync_res *res = (struct slave_sync_res *) (rbuf->data + rbuf->rpos); rbuf->rpos += res->len + sizeof(struct slave_sync_res); if (rbuf->rpos > rbuf->data_len) { log_error( "wrong packet lenght."); return NULL; } return res; }
static int16_t SPICE_GNUC_UNUSED consume_int16(uint8_t **ptr) { int16_t val; val = read_int16(*ptr); *ptr += 2; return val; }
int32_t execute_segment_stat_handle(struct data_buffer* dbuf,int socket_fd,MEM_POOL* 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,rbuf.data_len) <= 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_STAT_RS) return -1; uint16_t segment_count = read_int16(&rbuf); uint16_t i; fprintf(stderr,"%-20s%-20s%-20s%-20s%-20s%-20s%-20s\n","SEGMENT_ID","CREATE_TIME","MODIFY_TIME","CHECKPOINT_TIME","FLAG","ROW_COUNT","DEL_COUNT"); for(i=0; i<segment_count; i++) { fprintf(stderr,"%-20u",read_int16(&rbuf)); fprintf(stderr,"%-20llu",read_int64(&rbuf)); fprintf(stderr,"%-20llu",read_int64(&rbuf)); fprintf(stderr,"%-20llu",read_int64(&rbuf)); fprintf(stderr,"%-20u",read_int8(&rbuf)); fprintf(stderr,"%-20u",read_int32(&rbuf)); fprintf(stderr,"%-20u\n",read_int32(&rbuf)); } return 0; }
static uint16_t message_type(const struct data_buffer *buf) { // make a copy struct data_buffer copy = *buf; // no length in header copy.rpos = 2; uint16_t type = read_int16(©); return type; }
int Linker::fread_int16(FILE *f) { // read a 2-byte integer -- if you can't then blow up aINT16 i; if (!read_int16(&i, f)) // if (0 == fread((aBYTE *) &i, 2, 1, f)) aborteof(aS("while processing")); return((int) i); }
void load_exceptions() { dbFILE *f; int i; uint16 n; uint16 tmp16; uint32 tmp32; if (! (f = open_db(s_OperServ, ExceptionDBName, "r", EXCEPTION_VERSION))) return; switch (i = get_file_version(f)) { case 9: case 8: case 7: SAFE(read_int16(&n, f)); nexceptions = n; exceptions = scalloc(sizeof(Exception) * nexceptions, 1); if (!nexceptions) { close_db(f); return; } for (i = 0; i < nexceptions; i++) { SAFE(read_string(&exceptions[i].mask, f)); SAFE(read_int16(&tmp16, f)); exceptions[i].limit = tmp16; SAFE(read_buffer(exceptions[i].who, f)); SAFE(read_string(&exceptions[i].reason, f)); SAFE(read_int32(&tmp32, f)); exceptions[i].time = tmp32; SAFE(read_int32(&tmp32, f)); exceptions[i].expires = tmp32; } break; default: fatal("Unsupported version (%d) on %s", i, ExceptionDBName); } /* switch (ver) */ close_db(f); }
int32_t execute_index_stat_handle(struct data_buffer* dbuf,int socket_fd,MEM_POOL* 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,rbuf.data_len) <= 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_STAT_RS) return -1; uint16_t field_count = read_int16(&rbuf); uint16_t i; char* field_name = NULL; fprintf(stderr,"%-20s%-20s%-20s%-20s\n","FIELD_NAME","INDEX_TYPE","DATA_TYPE","FLAG"); uint8_t j; uint8_t index_num; for(i=0; i<field_count; i++) { field_name = read_cstring(&rbuf,mem_pool); index_num = read_int8(&rbuf); for(j=0;j < index_num; j++) { fprintf(stderr,"%-20s",field_name); fprintf(stderr,"%-20u",read_int8(&rbuf)); fprintf(stderr,"%-20u",read_int8(&rbuf)); fprintf(stderr,"%-20u\n",read_int8(&rbuf)); } } return 0; }
int read_string(char **ret, dbFILE * f) { char *s; uint16 len; if (read_int16(&len, f) < 0) return -1; if (len == 0) { *ret = NULL; return 0; } s = scalloc(len, 1); if (len != fread(s, 1, len, f->fp)) { free(s); return -1; } *ret = s; return 0; }
TEST(DATA_BUFFER_TEST, READ_AND_WRITE){ MEM_POOL_PTR pMemPool = mem_pool_init(MB_SIZE); struct data_buffer* buffer = init_data_buffer(); buffer->data_len = 256; buffer->data = (uint8*) mem_pool_malloc(pMemPool, 256); uint8 tmp8; uint16 tmp16; uint32 tmp32; uint64 tmp64; char* str = (char*) mem_pool_malloc(pMemPool, 100); char* result = (char*) mem_pool_malloc(pMemPool, 100); strcpy(str, "hello world!"); write_int8(122, buffer); write_int16(1111, buffer); write_int32(324, buffer); write_int64(2321, buffer); write_bytes((uint8*)str, strlen(str)+1, buffer); tmp8 = read_int8(buffer); ASSERT_EQ(tmp8, 122); tmp16 = read_int16(buffer); ASSERT_EQ(tmp16, 1111); tmp32 = read_int32(buffer); ASSERT_EQ(tmp32, 324); tmp64 = read_int64(buffer); ASSERT_EQ(tmp64, 2321); read_bytes(buffer, (uint8*)result, strlen(str)+1); ASSERT_EQ(0, strcmp(str, result)); destroy_data_buffer(buffer); mem_pool_destroy(pMemPool); }
//int ape_parseheader(int fd, struct ape_parser_ctx_t* ape_ctx) int ape_parseheader(FILE* fp, struct ape_parser_ctx_t* ape_ctx) { int i,n; /* Skip any leading junk such as id3v2 tags */ memset(ape_ctx, 0, sizeof(struct ape_parser_ctx_t)); while (1) { char sync[5]; if (4 != fread(sync, 1, 4, fp)) return -1; sync[4] = 0; if (strcmp(sync,"MAC ") == 0) break; else if (strcmp(sync + 1,"MAC") == 0) { fseek(fp, -1, SEEK_CUR); ape_ctx->junklength += 1; } else if (strcmp(sync + 2, "MA") == 0) { fseek(fp, -2, SEEK_CUR); ape_ctx->junklength += 2; } else if (sync[3]=='M') { fseek(fp, -3, SEEK_CUR); ape_ctx->junklength += 3; } else { ape_ctx->junklength += 4; } } fseek(fp, ape_ctx->junklength, SEEK_SET); n = fread(&ape_ctx->magic,1, 4, fp); if (n != 4) return -1; if (memcmp(ape_ctx->magic,"MAC ",4)!=0) { return -1; } if (read_int16(fp,&ape_ctx->fileversion) < 0) return -1; if (ape_ctx->fileversion >= 3980) { if (read_int16(fp,&ape_ctx->padding1) < 0) return -1; if (read_uint32(fp,&ape_ctx->descriptorlength) < 0) return -1; if (read_uint32(fp,&ape_ctx->headerlength) < 0) return -1; if (read_uint32(fp,&ape_ctx->seektablelength) < 0) return -1; if (read_uint32(fp,&ape_ctx->wavheaderlength) < 0) return -1; if (read_uint32(fp,&ape_ctx->audiodatalength) < 0) return -1; if (read_uint32(fp,&ape_ctx->audiodatalength_high) < 0) return -1; if (read_uint32(fp,&ape_ctx->wavtaillength) < 0) return -1; if (fread(&ape_ctx->md5,1, 16, fp) != 16) return -1; /* Skip any unknown bytes at the end of the descriptor. This is for future compatibility */ if (ape_ctx->descriptorlength > 52) fseek(fp, ape_ctx->descriptorlength - 52, SEEK_CUR); /* Read header data */ if (read_uint16(fp,&ape_ctx->compressiontype) < 0) return -1; if (read_uint16(fp,&ape_ctx->formatflags) < 0) return -1; if (read_uint32(fp,&ape_ctx->blocksperframe) < 0) return -1; if (read_uint32(fp,&ape_ctx->finalframeblocks) < 0) return -1; if (read_uint32(fp,&ape_ctx->totalframes) < 0) return -1; if (read_uint16(fp,&ape_ctx->bps) < 0) return -1; if (read_uint16(fp,&ape_ctx->channels) < 0) return -1; if (read_uint32(fp,&ape_ctx->samplerate) < 0) return -1; } else { ape_ctx->descriptorlength = 0; ape_ctx->headerlength = 32; if (read_uint16(fp,&ape_ctx->compressiontype) < 0) return -1; if (read_uint16(fp,&ape_ctx->formatflags) < 0) return -1; if (read_uint16(fp,&ape_ctx->channels) < 0) return -1; if (read_uint32(fp,&ape_ctx->samplerate) < 0) return -1; if (read_uint32(fp,&ape_ctx->wavheaderlength) < 0) return -1; if (read_uint32(fp,&ape_ctx->wavtaillength) < 0) return -1; if (read_uint32(fp,&ape_ctx->totalframes) < 0) return -1; if (read_uint32(fp,&ape_ctx->finalframeblocks) < 0) return -1; if (ape_ctx->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) { fseek(fp, 4, SEEK_CUR); ape_ctx->headerlength += 4; } if (ape_ctx->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) { if (read_uint32(fp,&ape_ctx->seektablelength) < 0) return -1; ape_ctx->headerlength += 4; ape_ctx->seektablelength *= sizeof(ape_parser_int32_t); } else { ape_ctx->seektablelength = ape_ctx->totalframes * sizeof(ape_parser_int32_t); } if (ape_ctx->formatflags & MAC_FORMAT_FLAG_8_BIT) ape_ctx->bps = 8; else if (ape_ctx->formatflags & MAC_FORMAT_FLAG_24_BIT) ape_ctx->bps = 24; else ape_ctx->bps = 16; if (ape_ctx->fileversion >= 3950) ape_ctx->blocksperframe = 73728 * 4; else if ((ape_ctx->fileversion >= 3900) || (ape_ctx->fileversion >= 3800 && ape_ctx->compressiontype >= 4000)) ape_ctx->blocksperframe = 73728; else ape_ctx->blocksperframe = 9216; /* Skip any stored wav header */ if (!(ape_ctx->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER)) { fseek(fp, ape_ctx->wavheaderlength, SEEK_CUR); } } ape_ctx->totalsamples = ape_ctx->finalframeblocks; if (ape_ctx->totalframes > 1) ape_ctx->totalsamples += ape_ctx->blocksperframe * (ape_ctx->totalframes-1); if (ape_ctx->seektablelength > 0) { ape_ctx->seektable = malloc(ape_ctx->seektablelength); if (ape_ctx->seektable == NULL) return -1; for (i=0; i < ape_ctx->seektablelength / sizeof(ape_parser_uint32_t); i++) { if (read_uint32(fp,&ape_ctx->seektable[i]) < 0) { free(ape_ctx->seektable); return -1; } } } ape_ctx->firstframe = ape_ctx->junklength + ape_ctx->descriptorlength + ape_ctx->headerlength + ape_ctx->seektablelength + ape_ctx->wavheaderlength; return 0; }
static void load_old_akill(void) { dbFILE *f; int i, j; uint16 tmp16; uint32 tmp32; char buf[NICKMAX], mask2[BUFSIZE], *mask, *s; Akill *ak, *entry; if (! (f = open_db("AKILL", AutokillDBName ? AutokillDBName : "akill.db", "r", 9))) return; get_file_version(f); read_int16(&tmp16, f); slist_setcapacity(&akills, tmp16); for (j = 0; j < akills.capacity; j++) { ak = scalloc(sizeof(Akill), 1); SAFE(read_string(&mask, f)); s = strchr(mask, '@'); *s = 0; s++; ak->user = sstrdup(mask); ak->host = sstrdup(s); SAFE(read_string(&ak->reason, f)); SAFE(read_buffer(buf, f)); if (!*buf) ak->by = sstrdup("<unknown>"); else ak->by = sstrdup(buf); SAFE(read_int32(&tmp32, f)); ak->seton = tmp32 ? tmp32 : time(NULL); SAFE(read_int32(&tmp32, f)); ak->expires = tmp32; /* Sanity checks *sigh* */ /* No nicknames allowed! */ if (strchr(ak->user, '!')) { xanadu_cmd_remove_akill(ak->user, ak->host); free(ak); continue; } snprintf(mask2, sizeof(mask2), "%s@%s", ak->user, ak->host); /* Is the mask already in the AKILL list? */ if (slist_indexof(&akills, mask2) != -1) { free(ak); continue; } /* Checks whether there is an AKILL that already covers * the one we want to add, and whether there are AKILLs * that would be covered by this one. Expiry time * does *also* matter. */ if (akills.count > 0) { for (i = akills.count - 1; i >= 0; i--) { char amask[BUFSIZE]; entry = akills.list[i]; if (!entry) continue; snprintf(amask, sizeof(amask), "%s@%s", entry->user, entry->host); if (match_wild_nocase(amask, mask2) && (entry->expires >= ak->expires || entry->expires == 0)) { xanadu_cmd_remove_akill(ak->user, ak->host); free(ak); ak = NULL; break; } if (match_wild_nocase(mask2, amask) && (entry->expires <= ak->expires || ak->expires == 0)) slist_delete(&akills, i); } } if (ak) slist_add(&akills, ak); } close_db(f); }
void load_os_dbase(void) { dbFILE *f; int16 i, ver; uint16 tmp16, n; uint32 tmp32; char *s; int failed = 0; if (!(f = open_db(s_OperServ, OperDBName, "r", OPER_VERSION))) return; ver = get_file_version(f); if (ver <= 9) { NickAlias *na; SAFE(read_int16(&n, f)); for (i = 0; i < n && !failed; i++) { SAFE(read_string(&s, f)); if (s) { na = findnick(s); if (na) { na->nc->flags |= NI_SERVICES_ADMIN; if (slist_indexof(&servadmins, na) == -1) slist_add(&servadmins, na); } free(s); } } if (!failed) SAFE(read_int16(&n, f)); for (i = 0; i < n && !failed; i++) { SAFE(read_string(&s, f)); if (s) { na = findnick(s); if (na) { na->nc->flags |= NI_SERVICES_OPER; if (slist_indexof(&servopers, na) == -1) slist_add(&servopers, na); } free(s); } } } if (ver >= 7) { uint32 tmp32; SAFE(read_int32(&maxusercnt, f)); SAFE(read_int32(&tmp32, f)); maxusertime = tmp32; } if (ver <= 10) load_old_akill(); else { Akill *ak; read_int16(&tmp16, f); slist_setcapacity(&akills, tmp16); for (i = 0; i < akills.capacity; i++) { ak = scalloc(sizeof(Akill), 1); SAFE(read_string(&ak->user, f)); SAFE(read_string(&ak->host, f)); SAFE(read_string(&ak->by, f)); SAFE(read_string(&ak->reason, f)); SAFE(read_int32(&tmp32, f)); ak->seton = tmp32; SAFE(read_int32(&tmp32, f)); ak->expires = tmp32; slist_add(&akills, ak); } } if (ver >= 11) { SXLine *sx; read_int16(&tmp16, f); slist_setcapacity(&sglines, tmp16); for (i = 0; i < sglines.capacity; i++) { sx = scalloc(sizeof(SXLine), 1); SAFE(read_string(&sx->mask, f)); SAFE(read_string(&sx->by, f)); SAFE(read_string(&sx->reason, f)); SAFE(read_int32(&tmp32, f)); sx->seton = tmp32; SAFE(read_int32(&tmp32, f)); sx->expires = tmp32; slist_add(&sglines, sx); } if (ver >= 13) { read_int16(&tmp16, f); slist_setcapacity(&sqlines, tmp16); for (i = 0; i < sqlines.capacity; i++) { sx = scalloc(sizeof(SXLine), 1); SAFE(read_string(&sx->mask, f)); SAFE(read_string(&sx->by, f)); SAFE(read_string(&sx->reason, f)); SAFE(read_int32(&tmp32, f)); sx->seton = tmp32; SAFE(read_int32(&tmp32, f)); sx->expires = tmp32; slist_add(&sqlines, sx); } } read_int16(&tmp16, f); slist_setcapacity(&szlines, tmp16); for (i = 0; i < szlines.capacity; i++) { sx = scalloc(sizeof(SXLine), 1); SAFE(read_string(&sx->mask, f)); SAFE(read_string(&sx->by, f)); SAFE(read_string(&sx->reason, f)); SAFE(read_int32(&tmp32, f)); sx->seton = tmp32; SAFE(read_int32(&tmp32, f)); sx->expires = tmp32; slist_add(&szlines, sx); } } close_db(f); }
int main(int argc, char *argv[]) { int oc; extern char *optarg; extern int optind; char *infile_name = NULL, *outfile_name = NULL; FILE *infile, *outfile; unsigned long i, j, n; long s16, k, r; char buf[1024]; while ((oc = getopt(argc, argv, "h")) != -1) { switch(oc) { case 'h': printf("-h: print this help and exit\n"); exit(EXIT_SUCCESS); } } if (optind < argc) infile_name = argv[optind++]; if (optind < argc) outfile_name = argv[optind++]; if (infile_name) { if ((infile = fopen(infile_name, "rb")) == NULL) { fprintf(stderr, "Failed to open \"%s\" for input -- exit\n", infile_name); exit(EXIT_FAILURE); } } else { infile = stdin; infile_name = "stdin"; } if (outfile_name) { if ((outfile = fopen(outfile_name, "w")) == NULL) { fprintf(stderr, "Failed to open \"%s\" for output -- exit\n", outfile_name); if (infile != stdin) fclose(infile); exit(EXIT_FAILURE); } } else { outfile = stdout; outfile_name = "stdout"; } fgets(buf, 1024, infile); for (i = 0; !feof(infile); i++) { fgets(buf, 1024, infile); n = strtoul(buf, NULL, 10); fprintf(stderr, "n = %lu\n", n); for (j = 0; j < n && !feof(infile); j++) { s16 = read_int16(infile); if (s16 < 0) { r = -s16; s16 = read_int16(infile); for (k = 0; k < r; k++) fprintf(outfile, "%lu %lu %ld\n", i, j, s16); } else fprintf(outfile, "%lu %lu %ld\n", i, j, s16); } } if (infile != stdin) fclose(infile); if (outfile != stdout) fclose(outfile); exit(EXIT_SUCCESS); }
int ape_parseheader(int fd, struct ape_ctx_t* ape_ctx) { int i,n; /* TODO: Skip any leading junk such as id3v2 tags */ ape_ctx->junklength = 0; lseek(fd,ape_ctx->junklength,SEEK_SET); n = read(fd,&ape_ctx->magic,4); if (n != 4) return -1; if (memcmp(ape_ctx->magic,"MAC ",4)!=0) { return -1; } if (read_int16(fd,&ape_ctx->fileversion) < 0) return -1; if (ape_ctx->fileversion >= 3980) { if (read_int16(fd,&ape_ctx->padding1) < 0) return -1; if (read_uint32(fd,&ape_ctx->descriptorlength) < 0) return -1; if (read_uint32(fd,&ape_ctx->headerlength) < 0) return -1; if (read_uint32(fd,&ape_ctx->seektablelength) < 0) return -1; if (read_uint32(fd,&ape_ctx->wavheaderlength) < 0) return -1; if (read_uint32(fd,&ape_ctx->audiodatalength) < 0) return -1; if (read_uint32(fd,&ape_ctx->audiodatalength_high) < 0) return -1; if (read_uint32(fd,&ape_ctx->wavtaillength) < 0) return -1; if (read(fd,&ape_ctx->md5,16) != 16) return -1; /* Skip any unknown bytes at the end of the descriptor. This is for future compatibility */ if (ape_ctx->descriptorlength > 52) lseek(fd,ape_ctx->descriptorlength - 52, SEEK_CUR); /* Read header data */ if (read_uint16(fd,&ape_ctx->compressiontype) < 0) return -1; if (read_uint16(fd,&ape_ctx->formatflags) < 0) return -1; if (read_uint32(fd,&ape_ctx->blocksperframe) < 0) return -1; if (read_uint32(fd,&ape_ctx->finalframeblocks) < 0) return -1; if (read_uint32(fd,&ape_ctx->totalframes) < 0) return -1; if (read_uint16(fd,&ape_ctx->bps) < 0) return -1; if (read_uint16(fd,&ape_ctx->channels) < 0) return -1; if (read_uint32(fd,&ape_ctx->samplerate) < 0) return -1; } else { ape_ctx->descriptorlength = 0; ape_ctx->headerlength = 32; if (read_uint16(fd,&ape_ctx->compressiontype) < 0) return -1; if (read_uint16(fd,&ape_ctx->formatflags) < 0) return -1; if (read_uint16(fd,&ape_ctx->channels) < 0) return -1; if (read_uint32(fd,&ape_ctx->samplerate) < 0) return -1; if (read_uint32(fd,&ape_ctx->wavheaderlength) < 0) return -1; if (read_uint32(fd,&ape_ctx->wavtaillength) < 0) return -1; if (read_uint32(fd,&ape_ctx->totalframes) < 0) return -1; if (read_uint32(fd,&ape_ctx->finalframeblocks) < 0) return -1; if (ape_ctx->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) { lseek(fd, 4, SEEK_CUR); /* Skip the peak level */ ape_ctx->headerlength += 4; } if (ape_ctx->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) { if (read_uint32(fd,&ape_ctx->seektablelength) < 0) return -1; ape_ctx->headerlength += 4; ape_ctx->seektablelength *= sizeof(int32_t); } else { ape_ctx->seektablelength = ape_ctx->totalframes * sizeof(int32_t); } if (ape_ctx->formatflags & MAC_FORMAT_FLAG_8_BIT) ape_ctx->bps = 8; else if (ape_ctx->formatflags & MAC_FORMAT_FLAG_24_BIT) ape_ctx->bps = 24; else ape_ctx->bps = 16; if (ape_ctx->fileversion >= 3950) ape_ctx->blocksperframe = 73728 * 4; else if ((ape_ctx->fileversion >= 3900) || (ape_ctx->fileversion >= 3800 && ape_ctx->compressiontype >= 4000)) ape_ctx->blocksperframe = 73728; else ape_ctx->blocksperframe = 9216; /* Skip any stored wav header */ if (!(ape_ctx->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER)) { lseek(fd, ape_ctx->wavheaderlength, SEEK_CUR); } } ape_ctx->totalsamples = ape_ctx->finalframeblocks; if (ape_ctx->totalframes > 1) ape_ctx->totalsamples += ape_ctx->blocksperframe * (ape_ctx->totalframes-1); if (ape_ctx->seektablelength > 0) { ape_ctx->seektable = malloc(ape_ctx->seektablelength); if (ape_ctx->seektable == NULL) return -1; for (i=0; i < ape_ctx->seektablelength / sizeof(uint32_t); i++) { if (read_uint32(fd,&ape_ctx->seektable[i]) < 0) { free(ape_ctx->seektable); return -1; } } } ape_ctx->firstframe = ape_ctx->junklength + ape_ctx->descriptorlength + ape_ctx->headerlength + ape_ctx->seektablelength + ape_ctx->wavheaderlength; return 0; }
static int reader_int16(lua_State* L) { reader_t* reader = lua_touserdata(L, 1); lua_pushinteger(L, (lua_Integer)read_int16(reader)); return 1; }
int32_t parse_mile_message(struct mile_packet *packet, void **bl_reader, int16_t exceed_cpu_used, MEM_POOL_PTR session_mem) { int32_t result_code = MILE_RETURN_SUCCESS; //读buffer和写buffer struct data_buffer* rbuf = packet->rbuf; struct data_buffer* sbuf = packet->sbuf; //读取消息头 struct mile_message_header msg_head; //当前时间与超时时间 uint64_t now_time; uint64_t deadline_time; if (rbuf == NULL) { log_error("严重错误, 读buffer为空!"); return ERROR_PACKET_FORMAT; } msg_head.version_major = read_int8(rbuf); msg_head.version_minor = read_int8(rbuf); msg_head.message_type = read_int16(rbuf); msg_head.message_id = read_int32(rbuf); packet->timeout = read_int32(rbuf); log_debug( "数据包包头信息 -- 主版本号: %d, 小版本号: %d, 消息类型: 0x%x, 消息id: %d, 超时: %d", msg_head.version_major, msg_head.version_minor, msg_head.message_type, msg_head.message_id, packet->timeout); now_time = get_time_msec(); if (packet->timeout != 0 && now_time - packet->launch_time / 1000 > packet->timeout) { log_warn( "执行sql超时, 收到sql命令时的时间 %llu, 当前时间 %llu, 超时时间 %u", packet->launch_time / 1000, now_time, packet->timeout); return ERROR_TIMEOUT; } else { deadline_time = now_time + packet->timeout; } uint16_t msg_head_type = (msg_head.message_type & 0xFF00); if (msg_head_type == MT_VG_MD) { result_code = process_mergeserver_message(&msg_head, rbuf, sbuf, exceed_cpu_used, deadline_time); } else if (msg_head_type == MT_VG_SC) { result_code = StorageEngine::storage->Command(&msg_head, rbuf, sbuf); if (MILE_RETURN_SUCCESS != result_code) gen_docserver_client_error_packet(result_code, &msg_head, sbuf); } else if (msg_head_type == MT_VG_CD) { result_code = process_client_message(&msg_head, rbuf, sbuf); } else if (msg_head_type == MT_VG_SM) { result_code = process_master_message(&msg_head, rbuf, sbuf, bl_reader, session_mem); } else if (msg_head_type == MT_VG_TEST_REQ) { result_code = process_test_message(&msg_head, rbuf, sbuf); } else { result_code = -1; } if (result_code != MILE_RETURN_SUCCESS) { log_error( "执行过程中出错, 错误码 %d, 错误原因 %s", result_code, error_msg(result_code)); } return result_code; }
NickInfo *load_nick(dbFILE *f, int ver) { NickInfo *ni; int32 tmp32; int i; ni = scalloc(sizeof(NickInfo), 1); SAFE(read_buffer(ni->nick, f)); SAFE(read_buffer(ni->pass, f)); SAFE(read_string(&ni->url, f)); SAFE(read_string(&ni->email, f)); SAFE(read_string(&ni->last_usermask, f)); if (!ni->last_usermask) ni->last_usermask = sstrdup("@"); SAFE(read_string(&ni->last_realname, f)); if (!ni->last_realname) ni->last_realname = sstrdup(""); SAFE(read_string(&ni->last_quit, f)); SAFE(read_int32(&tmp32, f)); ni->time_registered = tmp32; SAFE(read_int32(&tmp32, f)); ni->last_seen = tmp32; SAFE(read_int16(&ni->status, f)); ni->status &= ~NS_TEMPORARY; #ifdef USE_ENCRYPTION if (!(ni->status & (NS_ENCRYPTEDPW | NS_VERBOTEN))) { if (debug) log("debug: %s: encrypting password for `%s' on load", s_NickServ, ni->nick); if (encrypt_in_place(ni->pass, PASSMAX) < 0) fatal("%s: Can't encrypt `%s' nickname password!", s_NickServ, ni->nick); ni->status |= NS_ENCRYPTEDPW; } #else if (ni->status & NS_ENCRYPTEDPW) { /* Bail: it makes no sense to continue with encrypted * passwords, since we won't be able to verify them */ fatal("%s: load database: password for %s encrypted " "but encryption disabled, aborting", s_NickServ, ni->nick); } #endif /* Store the _name_ of the link target in ni->link for now; * we'll resolve it after we've loaded all the nicks */ SAFE(read_string((char **)&ni->link, f)); /* We actually recalculate link and channel counts later, but leave * them in for now to avoid changing the data file format */ SAFE(read_int16(&ni->linkcount, f)); if (ni->link) { SAFE(read_int16(&ni->channelcount, f)); /* No other information saved for linked nicks, since * they get it all from their link target */ ni->channelmax = CSMaxReg; ni->language = DEF_LANGUAGE; } else { SAFE(read_int32(&ni->flags, f)); if (!NSAllowKillImmed) ni->flags &= ~NI_KILL_IMMED; if (ver >= 9) { read_ptr((void **)&ni->suspendinfo, f); } else if (ver == 8 && (ni->flags & 0x10000000)) { /* In version 8, 0x10000000 was NI_SUSPENDED */ ni->suspendinfo = (SuspendInfo *)1; } if (ni->suspendinfo) { SuspendInfo *si = smalloc(sizeof(*si)); SAFE(read_buffer(si->who, f)); SAFE(read_string(&si->reason, f)); SAFE(read_int32(&tmp32, f)); si->suspended = tmp32; SAFE(read_int32(&tmp32, f)); si->expires = tmp32; ni->suspendinfo = si; } SAFE(read_int16(&ni->accesscount, f)); if (ni->accesscount) { char **access; access = smalloc(sizeof(char *) * ni->accesscount); ni->access = access; for (i = 0; i < ni->accesscount; i++, access++) SAFE(read_string(access, f)); } SAFE(read_int16(&ni->channelcount, f)); SAFE(read_int16(&ni->channelmax, f)); if (ver <= 8) { /* Fields not initialized or updated properly */ /* These will be updated by load_cs_dbase() */ ni->channelcount = 0; if (ver == 5) ni->channelmax = CSMaxReg; } SAFE(read_int16(&ni->language, f)); if (!langtexts[ni->language]) ni->language = DEF_LANGUAGE; } /* Link and channel counts are recalculated later */ ni->linkcount = 0; ni->channelcount = 0; ni->historycount = 0; return ni; }
void Linker::read_const(FILE *f, FILE *pFtarg, long *pi) { /* a constant is a tag followed by constant data tag = 1 -> constant is short atom tag = 2 -> constant is short int tag = 3 -> constant is arb string terminated by EOS tag = 4 -> constant is 4 byte float tag = 5 -> constant is 4 byte long tag = 6 -> constant is 4 byte long wide char tag = 7 -> constant is 8 byte double tag = 8 -> constant is real */ aBYTE buf[8]; int ccount; aBYTE ibyte; aINT16 temp, length; aINT32 temp32; aCHAR ichar; if (0 == fread(buf, 1, 1, f)) aborteof(aS("read const")); ucFWRITE(buf, 1, 1, pFtarg); (*pi) += 1; switch(*buf) { case 1: read_atom(f, pFtarg); (*pi) += 2; break; case 2: if (0 == fread(buf, 2, 1, f)) aborteof(aS("read const 2")); ucFWRITE(buf, 2, 1, pFtarg); (*pi) += 2; break; case 3: // single byte string ccount = 1; if (0 == fread(&ibyte, 1, 1, f)) aborteof(aS("read const 3")); ichar = (aCHAR)ibyte; while(ichar) { ++ccount; ucFWRITE(&ichar, 1, 1, pFtarg); if (0 == fread(&ibyte, 1, 1, f)) aborteof(aS("read const 3b")); ichar = (aCHAR)ibyte; } ucFWRITE(&ichar, 1, 1, pFtarg); (*pi) += ccount*sizeof(char); break; case 4: // float if (0 == fread(buf, 4, 1, f)) aborteof(aS("read const 4")); ucFWRITE(buf, 4, 1, pFtarg); (*pi) += 4; break; case 5: // long if (0 == fread(buf, 4, 1, f)) aborteof(aS("read const 5")); ucFWRITE(buf, 4, 1, pFtarg); (*pi) += 4; break; case 6: // wide character string ccount = 1; // if (0 == fread(&ichar, sizeof(aCHAR), 1, f)) if (!read_int16(&temp, f)) aborteof(aS("read const 3")); while(temp) { ++ccount; // ucFWRITE(&ichar, sizeof(aCHAR), 1, pFtarg); write_int16(temp, pFtarg); // if (0 == fread(&ichar, sizeof(aCHAR), 1, f)) if (!read_int16(&temp, f)) aborteof(aS("read const 3b")); } // fwrite(&ichar, sizeof(aCHAR), 1, pFtarg); write_int16(temp, pFtarg); (*pi) += ccount*2; break; case 9: // fixed case 7: // C double if (0 == fread(buf, 8, 1, f)) aborteof(aS("read const 7")); ucFWRITE(buf, 8, 1, pFtarg); (*pi) += 8; break; case 8: for(ccount = 0; ccount < 6; ccount += 2) { // copy the real descr if (!read_int16(&temp, f)) aborteof(aS("read const 3")); if(ccount == 0) length = temp; // length write_int16(temp, pFtarg); } while(length) { // copy the gigits if (!read_int32(&temp32, f)) aborteof(aS("read const 3b")); write_int32(temp32, pFtarg); ccount+= 4; length--; } (*pi) += ccount; } // end switch }
void load_ns_dbase(void) { dbFILE *f; int ver, i, j, c; NickAlias *na, **nalast, *naprev; NickCore *nc, **nclast, *ncprev; int failed = 0; uint16 tmp16; uint32 tmp32; char *s, *pass; if (!(f = open_db(s_NickServ, NickDBName, NICK_VERSION))) return; ver = get_file_version(f); if (ver <= 11) { // close_db(f); // load_old_ns_dbase(); printf("old database gtfo !\n"); return; } /* First we load nick cores */ for (i = 0; i < 1024 && !failed; i++) { nclast = &nclists[i]; ncprev = NULL; while ((c = getc_db(f)) == 1) { if (c != 1) printf("Invalid format in %s", NickDBName); nc = scalloc(1, sizeof(NickCore)); *nclast = nc; nclast = &nc->next; nc->prev = ncprev; ncprev = nc; slist_init(&nc->aliases); SAFE(read_string(&nc->display, f)); printf("%s", nc->display); if (ver < 14) { SAFE(read_string(&pass, f)); if (pass) { memset(nc->pass, 0, PASSMAX); memcpy(nc->pass, pass, strlen(pass)); } else memset(nc->pass, 0, PASSMAX); } else SAFE(read_buffer(nc->pass, f)); // printf(" %s", nc->pass); SAFE(read_string(&nc->email, f)); // printf(" %s", nc->email); SAFE(read_string(&nc->greet, f)); // printf(" %s", nc->greet); SAFE(read_int32(&nc->icq, f)); // printf(" %d", nc->icq); SAFE(read_string(&nc->url, f)); // printf(" %s\n", nc->url); SAFE(read_int32(&nc->flags, f)); if (!NSAllowKillImmed) nc->flags &= ~NI_KILL_IMMED; SAFE(read_int16(&nc->language, f)); /* Add services opers and admins to the appropriate list, but only if the database version is more than 10. */ /* if (nc->flags & NI_SERVICES_ADMIN) slist_add(&servadmins, nc); if (nc->flags & NI_SERVICES_OPER) slist_add(&servopers, nc); */ // OSEF des axx Sop et Sadmin ! SAFE(read_int16(&nc->accesscount, f)); if (nc->accesscount) { char **access; access = scalloc(sizeof(char *) * nc->accesscount, 1); nc->access = access; for (j = 0; j < nc->accesscount; j++, access++) SAFE(read_string(access, f)); } SAFE(read_int16(&tmp16, f)); nc->memos.memocount = (int16) tmp16; SAFE(read_int16(&tmp16, f)); nc->memos.memomax = (int16) tmp16; if (nc->memos.memocount) { Memo *memos; memos = scalloc(sizeof(Memo) * nc->memos.memocount, 1); nc->memos.memos = memos; for (j = 0; j < nc->memos.memocount; j++, memos++) { SAFE(read_int32(&memos->number, f)); SAFE(read_int16(&memos->flags, f)); SAFE(read_int32(&tmp32, f)); memos->time = tmp32; SAFE(read_buffer(memos->sender, f)); SAFE(read_string(&memos->text, f)); memos->moduleData = NULL; } } SAFE(read_int16(&nc->channelcount, f)); SAFE(read_int16(&tmp16, f)); nc->channelmax = CSMaxReg; if (ver < 13) { /* Used to be dead authentication system */ SAFE(read_int16(&tmp16, f)); SAFE(read_int32(&tmp32, f)); SAFE(read_int16(&tmp16, f)); SAFE(read_string(&s, f)); } } /* while (getc_db(f) != 0) */ *nclast = NULL; } /* for (i) */ for (i = 0; i < 1024 && !failed; i++) { nalast = &nalists[i]; naprev = NULL; while ((c = getc_db(f)) == 1) { if (c != 1) printf("Invalid format in %s", NickDBName); na = scalloc(1, sizeof(NickAlias)); SAFE(read_string(&na->nick, f)); SAFE(read_string(&na->last_usermask, f)); SAFE(read_string(&na->last_realname, f)); SAFE(read_string(&na->last_quit, f)); SAFE(read_int32(&tmp32, f)); na->time_registered = tmp32; SAFE(read_int32(&tmp32, f)); na->last_seen = tmp32; SAFE(read_int16(&na->status, f)); na->status &= ~NS_TEMPORARY; SAFE(read_string(&s, f)); na->nc = findcore(s); free(s); slist_add(&na->nc->aliases, na); if (!(na->status & NS_VERBOTEN)) { if (!na->last_usermask) na->last_usermask = sstrdup(""); if (!na->last_realname) na->last_realname = sstrdup(""); } na->nc->flags &= ~NI_SERVICES_ROOT; *nalast = na; nalast = &na->next; na->prev = naprev; naprev = na; } /* while (getc_db(f) != 0) */ *nalast = NULL; } /* for (i) */ // close_db(f); // nevermind wasting memory for (i = 0; i < 1024; i++) { NickAlias *next; for (na = nalists[i]; na; na = next) { next = na->next; /* We check for coreless nicks (although it should never happen) */ if (!na->nc) { printf("%s: while loading database: %s has no core! We delete it (here just ignore it !).", s_NickServ, na->nick); // delnick(na); continue; } /* Add the Services root flag if needed. */ /* for (j = 0; j < RootNumber; j++) if (!stricmp(ServicesRoots[j], na->nick)) na->nc->flags |= NI_SERVICES_ROOT; */ // OSEF de savoir si Paul Pierre ou Jacques est Services Root ! } } }
/* Reads a property of type 'prop_type' from 'data', and puts the * result 'out'. Returns 0 upon success, a negative value otherwise */ static int read_ply_property(struct file_data *data, const int prop_type, const int swap_bytes, void *out) { int c, rcode=0; /* Just local pointers to copy the result from the 'read_[type]' * functions into... */ t_int8 *tmp_int8; t_uint8 *tmp_uint8; t_int16 *tmp_int16; t_uint16 *tmp_uint16; t_int32 *tmp_int32; t_uint32 *tmp_uint32; float *tmp_float32; double *tmp_float64; switch(prop_type) { case uint8: c = getc(data); if (c == EOF) rcode = EOF; else { tmp_uint8 = out; *tmp_uint8 = (t_uint8)c; } break; case int8: c = getc(data); if (c == EOF) rcode = EOF; else { tmp_int8= out; *tmp_int8 = (t_int8)c; } break; case uint16: tmp_uint16 = out; rcode = read_uint16(data, swap_bytes, tmp_uint16); break; case int16: tmp_int16 = out; rcode = read_int16(data, swap_bytes, tmp_int16); break; case uint32: tmp_uint32 = out; rcode = read_uint32(data, swap_bytes, tmp_uint32); break; case int32: tmp_int32 = out; rcode = read_int32(data, swap_bytes, tmp_int32); break; case float32: tmp_float32 = out; rcode = read_float32(data, swap_bytes, tmp_float32); break; case float64: tmp_float64 = out; rcode = read_float64(data, swap_bytes, tmp_float64); break; default: rcode = MESH_CORRUPTED; break; } return rcode; }
static bmp_result bmp_analyse_header(bmp_image *bmp, uint8_t *data) { uint32_t header_size; uint32_t i; uint8_t j; int32_t width, height; uint8_t palette_size; unsigned int flags = 0; /* a variety of different bitmap headers can follow, depending * on the BMP variant. A full description of the various headers * can be found at * http://msdn.microsoft.com/en-us/library/ms532301(VS.85).aspx */ header_size = read_uint32(data, 0); if (bmp->buffer_size < (14 + header_size)) return BMP_INSUFFICIENT_DATA; if (header_size == 12) { /* the following header is for os/2 and windows 2.x and consists of: * * +0 UINT32 size of this header (in bytes) * +4 INT16 image width (in pixels) * +6 INT16 image height (in pixels) * +8 UINT16 number of colour planes (always 1) * +10 UINT16 number of bits per pixel */ width = read_int16(data, 4); height = read_int16(data, 6); if ((width <= 0) || (height == 0)) return BMP_DATA_ERROR; if (height < 0) { bmp->reversed = true; height = -height; } /* ICOs only support 256*256 resolutions * In the case of the ICO header, the height is actually the added * height of XOR-Bitmap and AND-Bitmap (double the visible height) * Technically we could remove this check and ICOs with bitmaps * of any size could be processed; this is to conform to the spec. */ if (bmp->ico) { if ((width > 256) || (height > 512)) { return BMP_DATA_ERROR; } else { bmp->width = width; bmp->height = height / 2; } } else { bmp->width = width; bmp->height = height; } if (read_uint16(data, 8) != 1) return BMP_DATA_ERROR; bmp->bpp = read_uint16(data, 10); /** * The bpp value should be in the range 1-32, but the only * values considered legal are: * RGB ENCODING: 1, 4, 8, 16, 24 and 32 */ if ((bmp->bpp != 1) && (bmp->bpp != 4) && (bmp->bpp != 8) && (bmp->bpp != 16) && (bmp->bpp != 24) && (bmp->bpp != 32)) return BMP_DATA_ERROR; bmp->colours = (1 << bmp->bpp); palette_size = 3; } else if (header_size < 40) { return BMP_DATA_ERROR; } else { /* the following header is for windows 3.x and onwards. it is a * minimum of 40 bytes and (as of Windows 95) a maximum of 108 bytes. * * +0 UINT32 size of this header (in bytes) * +4 INT32 image width (in pixels) * +8 INT32 image height (in pixels) * +12 UINT16 number of colour planes (always 1) * +14 UINT16 number of bits per pixel * +16 UINT32 compression methods used * +20 UINT32 size of bitmap (in bytes) * +24 UINT32 horizontal resolution (in pixels per meter) * +28 UINT32 vertical resolution (in pixels per meter) * +32 UINT32 number of colours in the image * +36 UINT32 number of important colours * +40 UINT32 mask identifying bits of red component * +44 UINT32 mask identifying bits of green component * +48 UINT32 mask identifying bits of blue component * +52 UINT32 mask identifying bits of alpha component * +56 UINT32 color space type * +60 UINT32 x coordinate of red endpoint * +64 UINT32 y coordinate of red endpoint * +68 UINT32 z coordinate of red endpoint * +72 UINT32 x coordinate of green endpoint * +76 UINT32 y coordinate of green endpoint * +80 UINT32 z coordinate of green endpoint * +84 UINT32 x coordinate of blue endpoint * +88 UINT32 y coordinate of blue endpoint * +92 UINT32 z coordinate of blue endpoint * +96 UINT32 gamma red coordinate scale value * +100 UINT32 gamma green coordinate scale value * +104 UINT32 gamma blue coordinate scale value */ width = read_int32(data, 4); height = read_int32(data, 8); if ((width <= 0) || (height == 0)) return BMP_DATA_ERROR; if (height < 0) { bmp->reversed = true; height = -height; } /* ICOs only support 256*256 resolutions * In the case of the ICO header, the height is actually the added * height of XOR-Bitmap and AND-Bitmap (double the visible height) * Technically we could remove this check and ICOs with bitmaps * of any size could be processed; this is to conform to the spec. */ if (bmp->ico) { if ((width > 256) || (height > 512)) { return BMP_DATA_ERROR; } else { bmp->width = width; bmp->height = height / 2; } } else { bmp->width = width; bmp->height = height; } if (read_uint16(data, 12) != 1) return BMP_DATA_ERROR; bmp->bpp = read_uint16(data, 14); if (bmp->bpp == 0) bmp->bpp = 8; bmp->encoding = read_uint32(data, 16); /** * The bpp value should be in the range 1-32, but the only * values considered legal are: * RGB ENCODING: 1, 4, 8, 16, 24 and 32 * RLE4 ENCODING: 4 * RLE8 ENCODING: 8 * BITFIELD ENCODING: 16 and 32 */ switch (bmp->encoding) { case BMP_ENCODING_RGB: if ((bmp->bpp != 1) && (bmp->bpp != 4) && (bmp->bpp != 8) && (bmp->bpp != 16) && (bmp->bpp != 24) && (bmp->bpp != 32)) return BMP_DATA_ERROR; break; case BMP_ENCODING_RLE8: if (bmp->bpp != 8) return BMP_DATA_ERROR; break; case BMP_ENCODING_RLE4: if (bmp->bpp != 4) return BMP_DATA_ERROR; break; case BMP_ENCODING_BITFIELDS: if ((bmp->bpp != 16) && (bmp->bpp != 32)) return BMP_DATA_ERROR; break; /* invalid encoding */ default: return BMP_DATA_ERROR; break; } /* Bitfield encoding means we have red, green, blue, and alpha masks. * Here we aquire the masks and determine the required bit shift to * align them in our 24-bit color 8-bit alpha format. */ if (bmp->encoding == BMP_ENCODING_BITFIELDS) { if (header_size == 40) { header_size += 12; if (bmp->buffer_size < (14 + header_size)) return BMP_INSUFFICIENT_DATA; for (i = 0; i < 3; i++) bmp->mask[i] = read_uint32(data, 40 + (i << 2)); } else { for (i = 0; i < 4; i++) bmp->mask[i] = read_uint32(data, 40 + (i << 2)); } for (i = 0; i < 4; i++) { if (bmp->mask[i] == 0) break; for (j = 31; j > 0; j--) if (bmp->mask[i] & (1 << j)) { if ((j - 7) > 0) bmp->mask[i] &= 0xff << (j - 7); else bmp->mask[i] &= 0xff >> (-(j - 7)); bmp->shift[i] = (i << 3) - (j - 7); break; } } } bmp->colours = read_uint32(data, 32); if (bmp->colours == 0) bmp->colours = (1 << bmp->bpp); palette_size = 4; } data += header_size; /* if there's no alpha mask, flag the bmp opaque */ if ((!bmp->ico) && (bmp->mask[3] == 0)) { flags |= BMP_OPAQUE; bmp->opaque = true; } /* we only have a palette for <16bpp */ if (bmp->bpp < 16) { /* we now have a series of palette entries of the format: * * +0 BYTE blue * +1 BYTE green * +2 BYTE red * * if the palette is from an OS/2 or Win2.x file then the entries * are padded with an extra byte. */ /* boundary checking */ if (bmp->buffer_size < (14 + header_size + ((uint64_t)4 * bmp->colours))) return BMP_INSUFFICIENT_DATA; /* create the colour table */ bmp->colour_table = (uint32_t *)malloc(bmp->colours * 4); if (!bmp->colour_table) return BMP_INSUFFICIENT_MEMORY; for (i = 0; i < bmp->colours; i++) { bmp->colour_table[i] = data[2] | (data[1] << 8) | (data[0] << 16); if (bmp->opaque) bmp->colour_table[i] |= (0xff << 24); data += palette_size; bmp->colour_table[i] = read_uint32((uint8_t *)&bmp->colour_table[i],0); } } /* create our bitmap */ flags |= BMP_NEW | BMP_CLEAR_MEMORY; bmp->bitmap = bmp->bitmap_callbacks.bitmap_create(bmp->width, bmp->height, flags); if (!bmp->bitmap) { if (bmp->colour_table) free(bmp->colour_table); bmp->colour_table = NULL; return BMP_INSUFFICIENT_MEMORY; } /* BMPs within ICOs don't have BMP file headers, so the image data should * always be right after the colour table. */ if (bmp->ico) bmp->bitmap_offset = (intptr_t)data - (intptr_t)bmp->bmp_data; return BMP_OK; }
void* wav_read_open(const char *filename) { struct wav_reader* wr = (struct wav_reader*) malloc(sizeof(*wr)); long data_pos = 0; memset(wr, 0, sizeof(*wr)); wr->wav = fopen(filename, "rb"); if (wr->wav == NULL) { free(wr); return NULL; } while (1) { uint32_t tag, tag2, length; tag = read_tag(wr); if (feof(wr->wav)) break; length = read_int32(wr); if (tag != TAG('R', 'I', 'F', 'F') || length < 4) { fseek(wr->wav, length, SEEK_CUR); continue; } tag2 = read_tag(wr); length -= 4; if (tag2 != TAG('W', 'A', 'V', 'E')) { fseek(wr->wav, length, SEEK_CUR); continue; } // RIFF chunk found, iterate through it while (length >= 8) { uint32_t subtag, sublength; subtag = read_tag(wr); if (feof(wr->wav)) break; sublength = read_int32(wr); length -= 8; if (length < sublength) break; if (subtag == TAG('f', 'm', 't', ' ')) { if (sublength < 16) { // Insufficient data for 'fmt ' break; } wr->format = read_int16(wr); wr->channels = read_int16(wr); wr->sample_rate = read_int32(wr); wr->byte_rate = read_int32(wr); wr->block_align = read_int16(wr); wr->bits_per_sample = read_int16(wr); fseek(wr->wav, sublength - 16, SEEK_CUR); } else if (subtag == TAG('d', 'a', 't', 'a')) { data_pos = ftell(wr->wav); wr->data_length = sublength; fseek(wr->wav, sublength, SEEK_CUR); } else { fseek(wr->wav, sublength, SEEK_CUR); } length -= sublength; } if (length > 0) { // Bad chunk? fseek(wr->wav, length, SEEK_CUR); } } fseek(wr->wav, data_pos, SEEK_SET); return wr; }
// static bool BitmapFontLoader::load(const char * const filepath, BitmapFont &font) { uint32_t largest_id = 0; std::vector<BmfCharBlock> character_blocks; BmfCommonBlock common_block; std::ifstream file(filepath, std::ifstream::in | std::ifstream::binary); if (!file.is_open()) { log::error("BitmapFontLoader: Count not open file %", filepath); return false; } try { if (! (read_uint8(file) == 'B' && read_uint8(file) == 'M' && read_uint8(file) == 'F')) { throw ParseError("Invalid file header."); } uint8_t version = read_uint8(file); if (version != BmfVersion) { throw ParseError("Wrong version. Expected " + to_string(BmfVersion) + ", found " + to_string(static_cast<unsigned int>(version))); } while (file.peek() != std::istream::traits_type::eof()) { uint8_t block_type = read_uint8(file); uint32_t block_size = read_uint32(file); switch (block_type) { case BmfInfoBlock::TYPE: { BmfInfoBlock block; block.font_size = read_int16(file); block.bit_field = read_uint8(file); block.char_set = read_uint8(file); block.stretch_h = read_uint16(file); block.anti_aliasing = read_uint8(file); block.padding_up = read_uint8(file); block.padding_right = read_uint8(file); block.padding_down = read_uint8(file); block.padding_left = read_uint8(file); block.spacing_horizontal = read_uint8(file); block.spacing_vertical = read_uint8(file); block.outline = read_uint8(file); read_string(file); } break; case BmfCommonBlock::TYPE: common_block.line_height = read_uint16(file); common_block.base = read_uint16(file); common_block.scale_w = read_uint16(file); common_block.scale_h = read_uint16(file); common_block.pages = read_uint16(file); common_block.bit_field = read_uint8(file); common_block.alpha_channel = read_uint8(file); common_block.red_channel = read_uint8(file); common_block.green_channel = read_uint8(file); common_block.blue_channel = read_uint8(file); break; case BmfPageBlock::TYPE: read_string(file); break; case BmfCharBlock::TYPE: { int number_of_characters = block_size / 20; log::debug("BitmapFontLoader: number of characters in font file: %", number_of_characters); for (int i=0; i<number_of_characters; i++) { BmfCharBlock block; block.id = read_uint32(file); block.x = read_uint16(file); block.y = read_uint16(file); block.width = read_uint16(file); block.height = read_uint16(file); block.offset_x = read_int16(file); block.offset_y = read_int16(file); block.advance_x = read_uint16(file); block.page = read_uint8(file); block.channel = read_uint8(file); //log::debug("BitmapFontLoader: char id: % (%)", block.id, (char)block.id); character_blocks.push_back(block); if (block.id > largest_id) largest_id = block.id; } } break; case BmfKerningPairBlock::TYPE: { int number_of_kerning_pairs = block_size / 10; for (int i=0; i<number_of_kerning_pairs; i++) { BmfKerningPairBlock block; block.first = read_uint32(file); block.second = read_uint32(file); block.amount = read_int16(file); } } break; default: throw ParseError("Invalid block type " + to_string(static_cast<unsigned int>(block_type))); } } } catch (EndOfFile &eof) { log::error("BitmapFontLoader: Encountered end of file unexpectedly."); log::debug("File position: %", file.tellg()); file.close(); return false; } catch (ParseError &err) { log::error("BitmapFontLoader: Failed to parse font definition. Position: %\n Reason: %", file.tellg(), err.what()); file.close(); return false; } file.close(); font.m_base = common_block.base; font.m_line_height = common_block.line_height; font.reserve(largest_id+1); for (BmfCharBlock &cblock : character_blocks) { BitmapFontCharacter c; c.id = cblock.id; c.x = cblock.x; c.y = cblock.y; c.width = cblock.width; c.height = cblock.height; c.offset_x = cblock.offset_x; c.offset_y = cblock.offset_y; c.advance_x = cblock.advance_x; font.add_character(c); } return true; }
void wav2c(FILE *in, FILE *out, FILE *outh) { uint32_t header[5]; int16_t format, channels, bits; uint32_t rate; uint32_t i, length, padlength=0, arraylen; int32_t audio=0; // read the WAV file's header for (i=0; i<5; i++) { header[i] = read_uint32(in); } if (header[0] != 0x46464952 || header[2] != 0x45564157 || header[3] != 0x20746D66 || header[4] != 0x00000010) { die("error in format of file %s", filename); } // read the audio format parameters format = read_int16(in); channels = read_int16(in); rate = read_uint32(in); read_uint32(in); // ignore byterate read_int16(in); // ignore blockalign bits = read_int16(in); //printf("format: %d, channels: %d, rate: %d, bits %d\n", format, channels, rate, bits); if (format != 1) die("file %s is compressed, only uncompressed supported", filename); if (rate != 44100 && rate != 22050 && rate != 11025 /*&& rate != 8000*/ ) die("sample rate %d in %s is unsupported\n" "Only 44100, 22050, 11025 work", rate, filename); if (channels != 1 && channels != 2) die("file %s has %d channels, but only 1 & 2 are supported", filename, channels); if (bits != 16) die("file %s has %d bit format, but only 16 is supported", filename, bits); // read the data header, skip non-audio data while (1) { header[0] = read_uint32(in); length = read_uint32(in); if (header[0] == 0x61746164) break; // beginning of actual audio data // skip over non-audio data for (i=0; i < length; i++) { read_uint8(in); } } // the length must be a multiple of the data size if (channels == 2) { if (length % 4) die("file %s data length is not a multiple of 4", filename); length = length / 4; } if (channels == 1) { if (length % 1) die("file %s data length is not a multiple of 2", filename); length = length / 2; } if (length > 0xFFFFFF) die("file %s data length is too long", filename); bcount = 0; // AudioPlayMemory requires padding to 2.9 ms boundary (128 samples @ 44100) if (rate == 44100) { padlength = padding(length, 128); format = 1; } else if (rate == 22050) { padlength = padding(length, 64); format = 2; } else if (rate == 11025) { padlength = padding(length, 32); format = 3; } if (pcm_mode) { arraylen = ((length + padlength) * 2 + 3) / 4 + 1; format |= 0x80; } else { arraylen = (length + padlength + 3) / 4 + 1; } total_length += arraylen; // output a minimal header, just the length, #bits and sample rate fprintf(outh, "extern const unsigned int AudioSample%s[%d];\n", samplename, arraylen); fprintf(out, "// Converted from %s, using %d Hz, %s encoding\n", filename, rate, (pcm_mode ? "16 bit PCM" : "u-law")); fprintf(out, "const unsigned int AudioSample%s[%d] = {\n", samplename, arraylen); fprintf(out, "0x%08X,", length | (format << 24)); wcount = 1; // finally, read the audio data while (length > 0) { if (channels == 1) { audio = read_int16(in); } else { audio = read_int16(in); audio += read_int16(in); audio /= 2; } if (pcm_mode) { print_byte(out, audio); print_byte(out, audio >> 8); } else { print_byte(out, ulaw_encode(audio)); } length--; }
long long evaluate(TERM* term, EVALUATION_CONTEXT* context) { size_t offs, hi_bound, lo_bound; long long op1; long long op2; long long index; unsigned int i; unsigned int needed; unsigned int satisfied; int ovector[3]; int rc; STRING* string; STRING* saved_anonymous_string; TERM_CONST* term_const = ((TERM_CONST*) term); TERM_UNARY_OPERATION* term_unary = ((TERM_UNARY_OPERATION*) term); TERM_BINARY_OPERATION* term_binary = ((TERM_BINARY_OPERATION*) term); TERM_TERNARY_OPERATION* term_ternary = ((TERM_TERNARY_OPERATION*) term); TERM_STRING* term_string = ((TERM_STRING*) term); TERM_VARIABLE* term_variable = ((TERM_VARIABLE*) term); TERM_STRING_OPERATION* term_string_operation = ((TERM_STRING_OPERATION*) term); TERM_INTEGER_FOR* term_integer_for; MATCH* match; TERM* item; TERM_RANGE* range; TERM_ITERABLE* items; TERM_STRING* t; switch(term->type) { case TERM_TYPE_CONST: return term_const->value; case TERM_TYPE_FILESIZE: return context->file_size; case TERM_TYPE_ENTRYPOINT: return context->entry_point; case TERM_TYPE_RULE: return evaluate(term_binary->op1, context); case TERM_TYPE_STRING: if (term_string->string == NULL) /* it's an anonymous string */ { string = context->current_string; } else { string = term_string->string; } return string->flags & STRING_FLAGS_FOUND; case TERM_TYPE_STRING_AT: if (term_string->string == NULL) /* it's an anonymous string */ { string = context->current_string; } else { string = term_string->string; } if (string->flags & STRING_FLAGS_FOUND) { offs = evaluate(term_string->offset, context); match = string->matches_head; while (match != NULL) { if (match->offset == offs) return 1; match = match->next; } return 0; } else return 0; case TERM_TYPE_STRING_IN_RANGE: if (term_string->string == NULL) /* it's an anonymous string */ { string = context->current_string; } else { string = term_string->string; } if (string->flags & STRING_FLAGS_FOUND) { range = (TERM_RANGE*) term_string->range; lo_bound = evaluate(range->min, context); hi_bound = evaluate(range->max, context); match = string->matches_head; while (match != NULL) { if (match->offset >= lo_bound && match->offset <= hi_bound) return 1; match = match->next; } return 0; } else return 0; case TERM_TYPE_STRING_IN_SECTION_BY_NAME: return 0; /*TODO: Implementar section by name*/ case TERM_TYPE_STRING_COUNT: i = 0; if (term_string->string == NULL) /* it's an anonymous string */ { string = context->current_string; } else { string = term_string->string; } match = string->matches_head; while (match != NULL) { i++; match = match->next; } return i; case TERM_TYPE_STRING_OFFSET: i = 1; index = evaluate(term_string->index, context); if (term_string->string == NULL) /* it's an anonymous string */ { string = context->current_string; } else { string = term_string->string; } match = string->matches_head; while (match != NULL && i < index) { match = match->next; i++; } if (match != NULL && i == index) { return match->offset; } return UNDEFINED; case TERM_TYPE_AND: if (evaluate(term_binary->op1, context)) return evaluate(term_binary->op2, context); else return 0; case TERM_TYPE_OR: if (evaluate(term_binary->op1, context)) return 1; else return evaluate(term_binary->op2, context); case TERM_TYPE_NOT: return !evaluate(term_unary->op, context); case TERM_TYPE_ADD: ARITHMETIC_OPERATOR(+, term_binary, context); case TERM_TYPE_SUB: ARITHMETIC_OPERATOR(-, term_binary, context); case TERM_TYPE_MUL: ARITHMETIC_OPERATOR(*, term_binary, context); case TERM_TYPE_DIV: ARITHMETIC_OPERATOR(/, term_binary, context); case TERM_TYPE_BITWISE_AND: ARITHMETIC_OPERATOR(&, term_binary, context); case TERM_TYPE_BITWISE_OR: ARITHMETIC_OPERATOR(|, term_binary, context); case TERM_TYPE_SHIFT_LEFT: ARITHMETIC_OPERATOR(<<, term_binary, context); case TERM_TYPE_SHIFT_RIGHT: ARITHMETIC_OPERATOR(>>, term_binary, context); case TERM_TYPE_BITWISE_NOT: op1 = evaluate(term_unary->op, context); if (IS_UNDEFINED(op1)) return UNDEFINED; else return ~op1; case TERM_TYPE_GT: COMPARISON_OPERATOR(>, term_binary, context); case TERM_TYPE_LT: COMPARISON_OPERATOR(<, term_binary, context); case TERM_TYPE_GE: COMPARISON_OPERATOR(>=, term_binary, context); case TERM_TYPE_LE: COMPARISON_OPERATOR(<=, term_binary, context); case TERM_TYPE_EQ: COMPARISON_OPERATOR(==, term_binary, context); case TERM_TYPE_NOT_EQ: COMPARISON_OPERATOR(!=, term_binary, context); case TERM_TYPE_OF: t = (TERM_STRING*) term_binary->op2; needed = evaluate(term_binary->op1, context); satisfied = 0; i = 0; while (t != NULL) { if (evaluate((TERM*) t, context)) { satisfied++; } t = t->next; i++; } if (needed == 0) /* needed == 0 means ALL*/ needed = i; return (satisfied >= needed); case TERM_TYPE_STRING_FOR: t = (TERM_STRING*) term_ternary->op2; needed = evaluate(term_ternary->op1, context); satisfied = 0; i = 0; while (t != NULL) { saved_anonymous_string = context->current_string; context->current_string = t->string; if (evaluate(term_ternary->op3, context)) { satisfied++; } context->current_string = saved_anonymous_string; t = t->next; i++; } if (needed == 0) /* needed == 0 means ALL*/ needed = i; return (satisfied >= needed); case TERM_TYPE_INTEGER_FOR: term_integer_for = (TERM_INTEGER_FOR*) term; items = term_integer_for->items; needed = evaluate(term_integer_for->count, context); satisfied = 0; i = 0; item = items->first(items, evaluate, context); while (item != NULL) { term_integer_for->variable->integer = evaluate(item, context); if (evaluate(term_integer_for->expression, context)) { satisfied++; } item = items->next(items, evaluate, context); i++; } if (needed == 0) /* needed == 0 means ALL*/ needed = i; return (satisfied >= needed); case TERM_TYPE_UINT8_AT_OFFSET: return read_uint8(context->mem_block, evaluate(term_unary->op, context)); case TERM_TYPE_UINT16_AT_OFFSET: return read_uint16(context->mem_block, evaluate(term_unary->op, context)); case TERM_TYPE_UINT32_AT_OFFSET: return read_uint32(context->mem_block, evaluate(term_unary->op, context)); case TERM_TYPE_INT8_AT_OFFSET: return read_int8(context->mem_block, evaluate(term_unary->op, context)); case TERM_TYPE_INT16_AT_OFFSET: return read_int16(context->mem_block, evaluate(term_unary->op, context)); case TERM_TYPE_INT32_AT_OFFSET: return read_int32(context->mem_block, evaluate(term_unary->op, context)); case TERM_TYPE_VARIABLE: if (term_variable->variable->type == VARIABLE_TYPE_STRING) { return ( term_variable->variable->string != NULL && *term_variable->variable->string != '\0'); } else { return term_variable->variable->integer; } case TERM_TYPE_STRING_MATCH: rc = regex_exec(&(term_string_operation->re), FALSE, term_string_operation->variable->string, strlen(term_string_operation->variable->string)); return (rc >= 0); case TERM_TYPE_STRING_CONTAINS: return (strstr(term_string_operation->variable->string, term_string_operation->string) != NULL); default: return 0; } }