void Regexp::Info::mark(Object* obj, ObjectMark& mark) { auto_mark(obj, mark); Regexp* reg_o = force_as<Regexp>(obj); regex_t* reg = reg_o->onig_data; if(!reg) return; ByteArray* reg_ba = ByteArray::from_body(reg); if(ByteArray* reg_tmp = force_as<ByteArray>(mark.call(reg_ba))) { reg_o->onig_data = reinterpret_cast<regex_t*>(reg_tmp->raw_bytes()); mark.just_set(obj, reg_tmp); reg_ba = reg_tmp; reg = reg_o->onig_data; } if(reg->p) { ByteArray* ba = ByteArray::from_body(reg->p); ByteArray* tmp = force_as<ByteArray>(mark.call(ba)); if(tmp) { reg->p = reinterpret_cast<unsigned char*>(tmp->raw_bytes()); mark.just_set(obj, tmp); } } if(reg->exact) { int exact_size = reg->exact_end - reg->exact; ByteArray* ba = ByteArray::from_body(reg->exact); ByteArray* tmp = force_as<ByteArray>(mark.call(ba)); if(tmp) { reg->exact = reinterpret_cast<unsigned char*>(tmp->raw_bytes()); reg->exact_end = reg->exact + exact_size; mark.just_set(obj, tmp); } } if(reg->int_map) { ByteArray* ba = ByteArray::from_body(reg->int_map); ByteArray* tmp = force_as<ByteArray>(mark.call(ba)); if(tmp) { reg->int_map = reinterpret_cast<int*>(tmp->raw_bytes()); mark.just_set(obj, tmp); } } if(reg->int_map_backward) { ByteArray* ba = ByteArray::from_body(reg->int_map_backward); ByteArray* tmp = force_as<ByteArray>(mark.call(ba)); if(tmp) { reg->int_map_backward = reinterpret_cast<int*>(tmp->raw_bytes()); mark.just_set(obj, tmp); } } if(reg->repeat_range) { ByteArray* ba = ByteArray::from_body(reg->repeat_range); ByteArray* tmp = force_as<ByteArray>(mark.call(ba)); if(tmp) { reg->repeat_range = reinterpret_cast<OnigRepeatRange*>(tmp->raw_bytes()); mark.just_set(obj, tmp); } } }
Scene::Scene(SagaEngine *vm) : _vm(vm) { ByteArray sceneLUTData; uint32 resourceId; uint i; // Do nothing for SAGA2 games for now if (_vm->isSaga2()) { _inGame = false; _sceneLoaded = false; return; } // Load scene module resource context _sceneContext = _vm->_resource->getContext(GAME_RESOURCEFILE); if (_sceneContext == NULL) { error("Scene::Scene() scene context not found"); } // Load scene lookup table resourceId = _vm->_resource->convertResourceId(_vm->getResourceDescription()->sceneLUTResourceId); debug(3, "Loading scene LUT from resource %i", resourceId); _vm->_resource->loadResource(_sceneContext, resourceId, sceneLUTData); if (sceneLUTData.empty()) { error("Scene::Scene() sceneLUT is empty"); } _sceneLUT.resize(sceneLUTData.size() / 2); ByteArrayReadStreamEndian readS(sceneLUTData, _sceneContext->isBigEndian()); for (i = 0; i < _sceneLUT.size(); i++) { _sceneLUT[i] = readS.readUint16(); debug(8, "sceneNumber %i has resourceId %i", i, _sceneLUT[i]); } #ifdef SAGA_DEBUG #define DUMP_SCENES_LEVEL 10 if (DUMP_SCENES_LEVEL <= gDebugLevel) { int backUpDebugLevel = gDebugLevel; SAGAResourceTypes *types; int typesCount; SAGAResourceTypes resType; SceneResourceDataArray resourceList; getResourceTypes(types, typesCount); for (i = 0; i < _sceneLUT.size(); i++) { gDebugLevel = -1; loadSceneDescriptor(_sceneLUT[i]); loadSceneResourceList(_sceneDescription.resourceListResourceId, resourceList); gDebugLevel = backUpDebugLevel; debug(DUMP_SCENES_LEVEL, "Dump Scene: number %i, descriptor resourceId %i, resourceList resourceId %i", i, _sceneLUT[i], _sceneDescription.resourceListResourceId); debug(DUMP_SCENES_LEVEL, "\tresourceListCount %i", (int)resourceList.size()); for (SceneResourceDataArray::iterator j = resourceList.begin(); j != resourceList.end(); ++j) { if (j->resourceType >= typesCount) { error("wrong resource type %i", j->resourceType); } resType = types[j->resourceType]; debug(DUMP_SCENES_LEVEL, "\t%s resourceId %i", SAGAResourceTypesString[resType], j->resourceId); } } } #endif debug(3, "LUT has %d entries.", _sceneLUT.size()); _sceneLoaded = false; _sceneNumber = 0; _chapterNumber = 0; _sceneResourceId = 0; _inGame = false; _sceneDescription.reset(); _sceneProc = NULL; _objectMap = new ObjectMap(_vm); _actionMap = new ObjectMap(_vm); }
void PlatformDomainNameServiceQuery::runBlocking() { if (!serviceValid) { emitError(); return; } SWIFT_LOG(debug) << "Querying " << service << std::endl; std::vector<DomainNameServiceQuery::Result> records; #if defined(SWIFTEN_PLATFORM_WINDOWS) DNS_RECORD* responses; // FIXME: This conversion doesn't work if unicode is deffed above if (DnsQuery(service.c_str(), DNS_TYPE_SRV, DNS_QUERY_STANDARD, NULL, &responses, NULL) != ERROR_SUCCESS) { emitError(); return; } DNS_RECORD* currentEntry = responses; while (currentEntry) { if (currentEntry->wType == DNS_TYPE_SRV) { DomainNameServiceQuery::Result record; record.priority = currentEntry->Data.SRV.wPriority; record.weight = currentEntry->Data.SRV.wWeight; record.port = currentEntry->Data.SRV.wPort; // The pNameTarget is actually a PCWSTR, so I would have expected this // conversion to not work at all, but it does. // Actually, it doesn't. Fix this and remove explicit cast // Remove unicode undef above as well record.hostname = std::string((const char*) currentEntry->Data.SRV.pNameTarget); records.push_back(record); } currentEntry = currentEntry->pNext; } DnsRecordListFree(responses, DnsFreeRecordList); #else // Make sure we reinitialize the domain list every time res_init(); ByteArray response; response.resize(NS_PACKETSZ); int responseLength = res_query(const_cast<char*>(service.c_str()), ns_c_in, ns_t_srv, reinterpret_cast<u_char*>(vecptr(response)), response.size()); if (responseLength == -1) { SWIFT_LOG(debug) << "Error" << std::endl; emitError(); return; } // Parse header HEADER* header = reinterpret_cast<HEADER*>(vecptr(response)); unsigned char* messageStart = vecptr(response); unsigned char* messageEnd = messageStart + responseLength; unsigned char* currentEntry = messageStart + NS_HFIXEDSZ; // Skip over the queries int queriesCount = ntohs(header->qdcount); while (queriesCount > 0) { int entryLength = dn_skipname(currentEntry, messageEnd); if (entryLength < 0) { emitError(); return; } currentEntry += entryLength + NS_QFIXEDSZ; queriesCount--; } // Process the SRV answers int answersCount = ntohs(header->ancount); while (answersCount > 0) { DomainNameServiceQuery::Result record; int entryLength = dn_skipname(currentEntry, messageEnd); currentEntry += entryLength; currentEntry += NS_RRFIXEDSZ; // Priority if (currentEntry + 2 >= messageEnd) { emitError(); return; } record.priority = boost::numeric_cast<int>(ns_get16(currentEntry)); currentEntry += 2; // Weight if (currentEntry + 2 >= messageEnd) { emitError(); return; } record.weight = boost::numeric_cast<int>(ns_get16(currentEntry)); currentEntry += 2; // Port if (currentEntry + 2 >= messageEnd) { emitError(); return; } record.port = boost::numeric_cast<int>(ns_get16(currentEntry)); currentEntry += 2; // Hostname if (currentEntry >= messageEnd) { emitError(); return; } ByteArray entry; entry.resize(NS_MAXDNAME); entryLength = dn_expand(messageStart, messageEnd, currentEntry, reinterpret_cast<char*>(vecptr(entry)), entry.size()); if (entryLength < 0) { emitError(); return; } record.hostname = std::string(reinterpret_cast<const char*>(vecptr(entry))); records.push_back(record); currentEntry += entryLength; answersCount--; } #endif BoostRandomGenerator generator; DomainNameServiceQuery::sortResults(records, generator); //std::cout << "Sending out " << records.size() << " SRV results " << std::endl; eventLoop->postEvent(boost::bind(boost::ref(onResult), records), shared_from_this()); }
Field::Field(const String& name, ByteArray value, Store store) { ConstructField(name, value, 0, value.size(), store); }
bool PsxRelocator::relocateFile(PsxRelocatorFile& file, int& relocationAddress) { std::map<int,int> relocationOffsets; std::map<int,int> symbolOffsets; int start = relocationAddress; // assign addresses to segments for (PsxSegment& seg: file.segments) { int index = seg.id; int size = seg.data.size(); relocationOffsets[index] = relocationAddress; relocationAddress += size; while (relocationAddress % 4) relocationAddress++; } // parse/add/relocate symbols bool error = false; for (PsxSymbol& sym: file.symbols) { int pos; switch (sym.type) { case PsxSymbolType::Internal: case PsxSymbolType::Function: sym.label->setValue(relocationOffsets[sym.segment]+sym.offset); sym.label->setDefined(true); break; case PsxSymbolType::InternalID: pos = relocationOffsets[sym.segment]+sym.offset; sym.label->setValue(pos); sym.label->setDefined(true); symbolOffsets[sym.id] = pos; break; case PsxSymbolType::BSS: sym.label->setValue(relocationAddress); sym.label->setDefined(true); symbolOffsets[sym.id] = relocationAddress; relocationAddress += sym.size; while (relocationAddress % 4) relocationAddress++; break; case PsxSymbolType::External: if (sym.label->isDefined() == false) { Logger::queueError(Logger::Error,L"Undefined external symbol %s in file %s",sym.name,file.name); error = true; continue; } symbolOffsets[sym.id] = sym.label->getValue(); break; } } if (error) return false; int dataStart = outputData.size(); outputData.reserveBytes(relocationAddress-start); // load code and data for (PsxSegment& seg: file.segments) { // relocate ByteArray sectionData = seg.data; for (PsxRelocation& rel: seg.relocations) { RelocationData relData; int pos = rel.segmentOffset; relData.opcode = sectionData.getDoubleWord(pos); switch (rel.refType) { case PsxRelocationRefType::SymblId: relData.relocationBase = symbolOffsets[rel.referenceId]+rel.relativeOffset; break; case PsxRelocationRefType::SegmentOffset: relData.relocationBase = relocationOffsets[rel.referenceId] + rel.referencePos+rel.relativeOffset; break; } switch (rel.type) { case PsxRelocationType::WordLiteral: reloc->relocateOpcode(R_MIPS_32,relData); break; case PsxRelocationType::UpperImmediate: reloc->relocateOpcode(R_MIPS_HI16,relData); break; case PsxRelocationType::LowerImmediate: reloc->relocateOpcode(R_MIPS_LO16,relData); break; case PsxRelocationType::FunctionCall: reloc->relocateOpcode(R_MIPS_26,relData); break; } sectionData.replaceDoubleWord(pos,relData.opcode); } int arrayStart = dataStart+relocationOffsets[seg.id]-start; memcpy(outputData.data(arrayStart),sectionData.data(),sectionData.size()); } return true; }
void buffer_set_size(buffer inBuffer,int inLen) { ByteArray b = (ByteArray)inBuffer; b->__SetSize(inLen); }
char * buffer_data(buffer inBuffer) { ByteArray b = (ByteArray)inBuffer; return b->GetBase(); }
bool OGG::Decode (Resource *resource, AudioBuffer *audioBuffer) { OggVorbis_File oggFile; if (resource->path) { FILE_HANDLE *file = lime::fopen (resource->path, "rb"); if (!file) { return false; } if (file->isFile ()) { ov_open (file->getFile (), &oggFile, NULL, file->getLength ()); } else { ByteArray data = ByteArray (resource->path); OAL_OggMemoryFile fakeFile = { data.Bytes (), data.Size (), 0 }; if (ov_open_callbacks (&fakeFile, &oggFile, NULL, 0, OAL_CALLBACKS_BUFFER) != 0) { return false; } } } else { OAL_OggMemoryFile fakeFile = { resource->data->Bytes (), resource->data->Size (), 0 }; if (ov_open_callbacks (&fakeFile, &oggFile, NULL, 0, OAL_CALLBACKS_BUFFER) != 0) { return false; } } // 0 for Little-Endian, 1 for Big-Endian #ifdef HXCPP_BIG_ENDIAN #define BUFFER_READ_TYPE 1 #else #define BUFFER_READ_TYPE 0 #endif int bitStream; long bytes = 1; int totalBytes = 0; #define BUFFER_SIZE 32768 vorbis_info *pInfo = ov_info (&oggFile, -1); if (pInfo == NULL) { //LOG_SOUND("FAILED TO READ OGG SOUND INFO, IS THIS EVEN AN OGG FILE?\n"); return false; } audioBuffer->channels = pInfo->channels; audioBuffer->sampleRate = pInfo->rate; //default to 16? todo audioBuffer->bitsPerSample = 16; // Seem to need four times the read PCM total audioBuffer->data->Resize (ov_pcm_total (&oggFile, -1) * 4); while (bytes > 0) { if (audioBuffer->data->Size () < totalBytes + BUFFER_SIZE) { audioBuffer->data->Resize (totalBytes + BUFFER_SIZE); } bytes = ov_read (&oggFile, (char *)audioBuffer->data->Bytes () + totalBytes, BUFFER_SIZE, BUFFER_READ_TYPE, 2, 1, &bitStream); totalBytes += bytes; } audioBuffer->data->Resize (totalBytes); ov_clear (&oggFile); #undef BUFFER_SIZE #undef BUFFER_READ_TYPE return true; }
ByteArray DataPackage::Serialize() { ByteArray body = SerializeBody(); ByteArray head = SerializeHead(static_cast<int32_t>(body.size())); return head + body; }
void test_get_byte() { ByteArray* b = new_bytearray("xyz"); TS_ASSERT_EQUALS(b->get_byte(state, Fixnum::from(0)), Fixnum::from('x')); TS_ASSERT_EQUALS(b->get_byte(state, Fixnum::from(2)), Fixnum::from('z')); }
void test_move_bytes() { ByteArray* b = new_bytearray("xyzzy"); b->move_bytes(state, Fixnum::from(0), Fixnum::from(2), Fixnum::from(3)); TS_ASSERT_SAME_DATA(b->raw_bytes(), "xyzxy", 5); }
void test_size() { ByteArray* b = ByteArray::create(state, 1); TS_ASSERT_EQUALS(b->size(state), Fixnum::from(sizeof(Object*))); }
void test_allocate() { ByteArray* b = ByteArray::allocate(state, Fixnum::from(5)); TS_ASSERT_EQUALS(b->size(state)->to_native(), 8); }
void test_fetch_bytes() { ByteArray* b = new_bytearray("xyzzy"); ByteArray* ba = b->fetch_bytes(state, Fixnum::from(1), Fixnum::from(3)); TS_ASSERT_SAME_DATA(ba->raw_bytes(), "yzz", 3); }
Array* Array_readLocalData(Input& fr) { if (fr[0].matchWord("Use")) { if (fr[1].isString()) { Object* obj = fr.getObjectForUniqueID(fr[1].getStr()); if (obj) { fr+=2; return dynamic_cast<Array*>(obj); } } osg::notify(osg::WARN)<<"Warning: invalid uniqueID found in file."<<std::endl; return NULL; } std::string uniqueID; if (fr[0].matchWord("UniqueID") && fr[1].isString()) { uniqueID = fr[1].getStr(); fr += 2; } int entry = fr[0].getNoNestedBrackets(); const char* arrayName = fr[0].getStr(); unsigned int capacity = 0; fr[1].getUInt(capacity); ++fr; fr += 2; Array* return_array = 0; if (strcmp(arrayName,"ByteArray")==0) { ByteArray* array = new ByteArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { int int_value; if (fr[0].getInt(int_value)) { ++fr; array->push_back(int_value); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"ShortArray")==0) { ShortArray* array = new ShortArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { int int_value; if (fr[0].getInt(int_value)) { ++fr; array->push_back(int_value); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"IntArray")==0) { IntArray* array = new IntArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { int int_value; if (fr[0].getInt(int_value)) { ++fr; array->push_back(int_value); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"UByteArray")==0) { UByteArray* array = new UByteArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { unsigned int uint_value; if (fr[0].getUInt(uint_value)) { ++fr; array->push_back(uint_value); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"UShortArray")==0) { UShortArray* array = new UShortArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { unsigned int uint_value; if (fr[0].getUInt(uint_value)) { ++fr; array->push_back(uint_value); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"UIntArray")==0) { UIntArray* array = new UIntArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { unsigned int uint_value; if (fr[0].getUInt(uint_value)) { ++fr; array->push_back(uint_value); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"UVec4bArray")==0 || strcmp(arrayName,"Vec4ubArray")==0) { Vec4ubArray* array = new Vec4ubArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { unsigned int r,g,b,a; if (fr[0].getUInt(r) && fr[1].getUInt(g) && fr[2].getUInt(b) && fr[3].getUInt(a)) { fr+=4; array->push_back(osg::Vec4ub(r,g,b,a)); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"FloatArray")==0) { FloatArray* array = new FloatArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { float float_value; if (fr[0].getFloat(float_value)) { ++fr; array->push_back(float_value); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"DoubleArray")==0) { DoubleArray* array = new DoubleArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { double double_value; if (fr[0].getFloat(double_value)) { ++fr; array->push_back(double_value); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"Vec2Array")==0) { Vec2Array* array = new Vec2Array; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { Vec2 v; if (fr[0].getFloat(v.x()) && fr[1].getFloat(v.y())) { fr += 2; array->push_back(v); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"Vec2dArray")==0) { Vec2dArray* array = new Vec2dArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { Vec2d v; if (fr[0].getFloat(v.x()) && fr[1].getFloat(v.y())) { fr += 2; array->push_back(v); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"Vec3Array")==0) { Vec3Array* array = new Vec3Array; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { Vec3 v; if (fr[0].getFloat(v.x()) && fr[1].getFloat(v.y()) && fr[2].getFloat(v.z())) { fr += 3; array->push_back(v); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"Vec3dArray")==0) { Vec3dArray* array = new Vec3dArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { Vec3d v; if (fr[0].getFloat(v.x()) && fr[1].getFloat(v.y()) && fr[2].getFloat(v.z())) { fr += 3; array->push_back(v); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"Vec4Array")==0) { Vec4Array* array = new Vec4Array; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { Vec4 v; if (fr[0].getFloat(v.x()) && fr[1].getFloat(v.y()) && fr[2].getFloat(v.z()) && fr[3].getFloat(v.w())) { fr += 4; array->push_back(v); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"Vec4dArray")==0) { Vec4dArray* array = new Vec4dArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { Vec4d v; if (fr[0].getFloat(v.x()) && fr[1].getFloat(v.y()) && fr[2].getFloat(v.z()) && fr[3].getFloat(v.w())) { fr += 4; array->push_back(v); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"Vec2bArray")==0) { Vec2bArray* array = new Vec2bArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { unsigned int r,g; if (fr[0].getUInt(r) && fr[1].getUInt(g)) { fr+=2; array->push_back(osg::Vec2b(r,g)); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"Vec3bArray")==0) { Vec3bArray* array = new Vec3bArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { unsigned int r,g,b; if (fr[0].getUInt(r) && fr[1].getUInt(g) && fr[2].getUInt(b)) { fr+=3; array->push_back(osg::Vec3b(r,g,b)); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"Vec4bArray")==0) { Vec4bArray* array = new Vec4bArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { unsigned int r,g,b,a; if (fr[0].getUInt(r) && fr[1].getUInt(g) && fr[2].getUInt(b) && fr[3].getUInt(a)) { fr+=4; array->push_back(osg::Vec4b(r,g,b,a)); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"Vec2sArray")==0) { Vec2sArray* array = new Vec2sArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { unsigned int r,g; if (fr[0].getUInt(r) && fr[1].getUInt(g)) { fr+=2; array->push_back(osg::Vec2s(r,g)); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"Vec3sArray")==0) { Vec3sArray* array = new Vec3sArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { unsigned int r,g,b; if (fr[0].getUInt(r) && fr[1].getUInt(g) && fr[2].getUInt(b)) { fr+=3; array->push_back(osg::Vec3s(r,g,b)); } else ++fr; } ++fr; return_array = array; } else if (strcmp(arrayName,"Vec4sArray")==0) { Vec4sArray* array = new Vec4sArray; array->reserve(capacity); while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { unsigned int r,g,b,a; if (fr[0].getUInt(r) && fr[1].getUInt(g) && fr[2].getUInt(b) && fr[3].getUInt(a)) { fr+=4; array->push_back(osg::Vec4s(r,g,b,a)); } else ++fr; } ++fr; return_array = array; } if (return_array) { if (!uniqueID.empty()) fr.registerUniqueIDForObject(uniqueID.c_str(),return_array); } return return_array; }
bool Shader::LoadFromBinary(const ByteArray& byteArray) { return LoadFromBinary(byteArray.GetConstBuffer(), byteArray.GetSize()); }
ByteArray cursorToString(CXCursor cursor, unsigned flags) { const CXCursorKind kind = clang_getCursorKind(cursor); ByteArray ret; ret.reserve(256); ret += eatString(clang_getCursorKindSpelling(kind)); if (clang_isInvalid(kind)) return ret; switch (RTags::cursorType(kind)) { case Reference: ret += " r"; break; case Cursor: ret += " c"; break; case Other: ret += " o"; break; case Include: ret += " i"; break; } const ByteArray name = eatString(clang_getCursorDisplayName(cursor)); const ByteArray other = eatString(clang_getCursorSpelling(cursor)); if (!name.isEmpty()) ret += " " + name; if (other != name && !other.isEmpty()) ret += " " + other; if (clang_isCursorDefinition(cursor)) ret += " def"; if (flags & IncludeUSR) ret += " " + eatString(clang_getCursorUSR(cursor)); CXFile file; unsigned off, line, col; //presumedLine, presumedCol, instantiationLoc, expansionLoc; CXSourceLocation location = clang_getCursorLocation(cursor); clang_getSpellingLocation(location, &file, &line, &col, &off); // clang_getPresumedLocation(location, 0, &presumedLine, &presumedCol); // clang_getInstantiationLocation(location, 0, 0, 0, &instantiationLoc); // clang_getExpansionLocation(location, 0, 0, 0, &expansionLoc); const Str fileName(clang_getFileName(file)); if (fileName.data() && *fileName.data()) { ret += ' '; ret += fileName.data(); ret += ','; ret += ByteArray::number(off); if (flags & IncludeRange) { ret += " ("; CXSourceRange range = clang_getCursorExtent(cursor); unsigned start, end; clang_getSpellingLocation(clang_getRangeStart(range), 0, 0, 0, &start); clang_getSpellingLocation(clang_getRangeEnd(range), 0, 0, 0, &end); ret += ByteArray::number(start); ret += '-'; ret += ByteArray::number(end); ret += ')'; } // if (presumedLine != line || presumedCol != col) // ret += ByteArray::snprintf<32>("presumed: %d:%d", presumedLine, presumedCol); // if (instantiationLoc != off) // ret += ByteArray::snprintf<32>("instantiation: %d", instantiationLoc); // if (expansionLoc != off) // ret += ByteArray::snprintf<32>("expansion: %d", expansionLoc); } return ret; }
bool ByteArray::load(ByteArray &value) { LOG_COMM("Executing byte array load through byte array"); return this->load(value.getRawDataPtr(), value.getBufferSize()); }
void buffer_append_char(buffer inBuffer,int inChar) { ByteArray b = (ByteArray)inBuffer; b->Add(inChar); }
std::vector<ArFileEntry> loadArArchive(const std::wstring& inputName) { ByteArray input = ByteArray::fromFile(inputName); std::vector<ArFileEntry> result; if (memcmp(input.data(),"!<arch>\n",8) != 0) { if (memcmp(input.data(),"\x7F""ELF",4) != 0) return result; ArFileEntry entry; entry.name = getFileNameFromPath(inputName); entry.data = input; result.push_back(entry); return result; } size_t pos = 8; while (pos < input.size()) { ArFileHeader* header = (ArFileHeader*) input.data(pos); pos += sizeof(ArFileHeader); // get file size int size = 0; for (int i = 0; i < 10; i++) { if (header->fileSize[i] == ' ') break; size = size*10; size += (header->fileSize[i]-'0'); } // only ELF files are actually interesting if (memcmp(input.data(pos),"\x7F""ELF",4) == 0) { // get file name char fileName[17]; fileName[16] = 0; for (int i = 0; i < 16; i++) { if (header->fileName[i] == ' ') { // remove trailing slashes of file names if (i > 0 && fileName[i-1] == '/') i--; fileName[i] = 0; break;; } fileName[i] = header->fileName[i]; } ArFileEntry entry; entry.name = convertUtf8ToWString(fileName); entry.data = input.mid(pos,size); result.push_back(entry); } pos += size; if (pos % 2) pos++; } return result; }
ByteArray SenderChainKey::getDerivative(const ByteArray &seed, const ByteArray &key) const { unsigned char out[32]; HMAC_SHA256((unsigned char*)seed.c_str(), seed.size(), (unsigned char*)key.c_str(), key.size(), out); return ByteArray((const char*)out, 32); }
bool ElfRelocator::relocateFile(ElfRelocatorFile& file, u64& relocationAddress) { ElfFile* elf = file.elf; u64 start = relocationAddress; // calculate address for each section std::map<u64,u64> relocationOffsets; for (ElfRelocatorSection& entry: file.sections) { ElfSection* section = entry.section; size_t index = entry.index; int size = section->getSize(); while (relocationAddress % section->getAlignment()) relocationAddress++; if (entry.label != NULL) entry.label->setValue(relocationAddress); relocationOffsets[index] = relocationAddress; relocationAddress += size; } size_t dataStart = outputData.size(); outputData.reserveBytes((size_t)(relocationAddress-start)); // load sections bool error = false; for (ElfRelocatorSection& entry: file.sections) { ElfSection* section = entry.section; size_t index = entry.index; if (section->getType() == SHT_NOBITS) { // reserveBytes initialized the data to 0 already continue; } ByteArray sectionData = section->getData(); // relocate if necessary ElfSection* relSection = entry.relSection; if (relSection != NULL) { Elf32_Rel* rel = (Elf32_Rel*) &relSection->getData()[0]; int relCount = relSection->getSize()/sizeof(Elf32_Rel); for (int i = 0; i < relCount; i++) { int pos = rel[i].r_offset; int symNum = rel[i].getSymbolNum(); if (symNum <= 0) { Logger::queueError(Logger::Warning,L"Invalid symbol num %06X",symNum); error = true; continue; } auto sym = elf->getSymbol(symNum); int symSection = sym->st_shndx; RelocationData relData; relData.opcode = sectionData.getDoubleWord(pos); relData.opcodeOffset = pos+relocationOffsets[index]; relocator->setSymbolAddress(relData,sym->st_value,sym->st_info & 0xF); // externs? if (relData.targetSymbolType == STT_NOTYPE && sym->st_shndx == 0) { std::wstring symName = toWLowercase(elf->getStrTableString(sym->st_name)); Label* label = Global.symbolTable.getLabel(symName,-1,-1); if (label == NULL) { Logger::queueError(Logger::Error,L"Invalid external symbol %s",symName); error = true; continue; } if (label->isDefined() == false) { Logger::queueError(Logger::Error,L"Undefined external symbol %s in file %s",symName,file.name); error = true; continue; } relData.relocationBase = (unsigned int) label->getValue(); relData.targetSymbolType = label->isData() ? STT_OBJECT : STT_FUNC; relData.targetSymbolInfo = label->getInfo(); } else { relData.relocationBase = relocationOffsets[symSection]+relData.symbolAddress; } if (relocator->relocateOpcode(rel[i].getType(),relData) == false) { Logger::queueError(Logger::Error,relData.errorMessage); error = true; continue; } sectionData.replaceDoubleWord(pos,relData.opcode); } } size_t arrayStart = (size_t) (dataStart+relocationOffsets[index]-start); memcpy(outputData.data(arrayStart),sectionData.data(),sectionData.size()); } // now update symbols for (ElfRelocatorSymbol& sym: file.symbols) { u64 oldAddress = sym.relocatedAddress; switch (sym.section) { case SHN_ABS: // address does not change sym.relocatedAddress = sym.relativeAddress; break; case SHN_COMMON: // needs to be allocated. relativeAddress gives alignment constraint { u64 start = relocationAddress; while (relocationAddress % sym.relativeAddress) relocationAddress++; sym.relocatedAddress = relocationAddress; relocationAddress += sym.size; outputData.reserveBytes((size_t)(relocationAddress-start)); } break; default: // normal relocated symbol sym.relocatedAddress = sym.relativeAddress+relocationOffsets[sym.section]; break; } if (sym.label != NULL) sym.label->setValue(sym.relocatedAddress); if (oldAddress != sym.relocatedAddress) dataChanged = true; } return !error; }
int MemoryFile::write(const ByteArray &array ) { int savePos = Pos; write( array.data(), array.size() ); return Pos - savePos; }
TEST(ByteArraySuite, loading) { const shared_int SIZE = 100; char buffer[SIZE]; ByteArray bytes; ByteArray empty; ASSERT_TRUE(bytes.init(&buffer[0], SIZE)); shared_bool bIN = true, bOUT = false; shared_int iIN = 999, iOUT = 0; shared_real rIN = 9999.9999, rOUT = 0; // Boolean loading EXPECT_TRUE(bytes.load(bIN)); EXPECT_EQ(bytes.getBufferSize(), SIZE+sizeof(shared_bool)); EXPECT_TRUE(bytes.unload(bOUT)); EXPECT_EQ((shared_int)bytes.getBufferSize(), SIZE); EXPECT_EQ(bOUT, bIN); // Integer loading EXPECT_TRUE(bytes.load(iIN)); EXPECT_EQ(bytes.getBufferSize(), SIZE+sizeof(shared_int)); EXPECT_TRUE(bytes.unload(iOUT)); EXPECT_EQ((shared_int)bytes.getBufferSize(), SIZE); EXPECT_EQ(iOUT, iIN); // Real loading EXPECT_TRUE(bytes.load(rIN)); EXPECT_EQ(bytes.getBufferSize(), SIZE+sizeof(shared_real)); EXPECT_TRUE(bytes.unload(rOUT)); EXPECT_EQ((shared_int)bytes.getBufferSize(), SIZE); EXPECT_EQ(rOUT, rIN); // Unloading a single member (down to an empty buffer size) EXPECT_TRUE(empty.load(bIN)); EXPECT_EQ(empty.getBufferSize(), sizeof(shared_bool)); EXPECT_TRUE(empty.unload(bOUT)); EXPECT_EQ((int)empty.getBufferSize(), 0); EXPECT_EQ(bOUT, bIN); // Loading two members (unloading the first) and then checking the value of the second rOUT = 0.0; iOUT = 0; EXPECT_TRUE(empty.load(rIN)); EXPECT_EQ(empty.getBufferSize(), sizeof(shared_real)); EXPECT_TRUE(empty.load(iIN)); EXPECT_EQ(empty.getBufferSize(), sizeof(shared_real)+sizeof(shared_int)); EXPECT_TRUE(empty.unloadFront(rOUT)); EXPECT_EQ(rOUT, rIN); EXPECT_TRUE(empty.unload(iOUT)); EXPECT_EQ((int)empty.getBufferSize(), 0); EXPECT_EQ(iOUT, iIN); }
bool PsxRelocator::parseObject(ByteArray data, PsxRelocatorFile& dest) { if (memcmp(data.data(),psxObjectFileMagicNum,sizeof(psxObjectFileMagicNum)) != 0) return false; int pos = 6; std::vector<PsxSegment>& segments = dest.segments; std::vector<PsxSymbol>& syms = dest.symbols; int activeSegment = -1; int lastSegmentPartStart = -1; while (pos < data.size()) { switch (data[pos]) { case 0x10: // segment definition { PsxSegment seg; seg.id = data.getDoubleWord(pos+1); segments.push_back(seg); pos += 5; if (data[pos] != 8) return false; int nameLen = data[pos+1]; std::wstring& name = segments[segments.size()-1].name; pos += 1 + loadString(data,pos+1,name); } break; case 0x14: // group? pos += data[pos+4]+5; break; case 0x1C: // source file name pos += data[pos+3]+4; break; case 0x06: // set segment id { int id = data.getWord(pos+1); pos += 3; int num = -1; for (size_t i = 0; i < segments.size(); i++) { if (segments[i].id == id) { num = i; break; } } activeSegment = num; } break; case 0x02: // append to data segment { int size = data.getWord(pos+1); pos += 3; ByteArray d = data.mid(pos,size); pos += size; lastSegmentPartStart = segments[activeSegment].data.size(); segments[activeSegment].data.append(d); } break; case 0x08: // append zeroes data segment { int size = data.getWord(pos+1); pos += 3; ByteArray d; d.reserveBytes(size); segments[activeSegment].data.append(d); } break; case 0x0A: // relocation data { int type = data[pos+1]; pos += 2; PsxRelocation rel; rel.relativeOffset = 0; rel.filePos = pos-2; switch (type) { case 0x10: // 32 bit word rel.type = PsxRelocationType::WordLiteral; rel.segmentOffset = data.getWord(pos); pos += 2; break; case 0x4A: // jal rel.type = PsxRelocationType::FunctionCall; rel.segmentOffset = data.getWord(pos); pos += 2; break; case 0x52: // upper immerdiate rel.type = PsxRelocationType::UpperImmediate; rel.segmentOffset = data.getWord(pos); pos += 2; break; case 0x54: // lower immediate (add) rel.type = PsxRelocationType::LowerImmediate; rel.segmentOffset = data.getWord(pos); pos += 2; break; default: return false; } rel.segmentOffset += lastSegmentPartStart; checkothertype: int otherType = data[pos++]; switch (otherType) { case 0x02: // reference to symbol with id num rel.refType = PsxRelocationRefType::SymblId; rel.referenceId = data.getWord(pos); pos += 2; break; case 0x2C: // ref to other segment? rel.refType = PsxRelocationRefType::SegmentOffset; switch (data[pos++]) { case 0x00: rel.relativeOffset = data.getDoubleWord(pos); pos += 4; goto checkothertype; case 0x04: rel.referenceId = data.getWord(pos); // segment id pos += 2; if (data[pos++] != 0x00) { return false; } rel.referencePos = data.getDoubleWord(pos); pos += 4; break; default: return false; } break; case 0x2E: // negative ref? rel.refType = PsxRelocationRefType::SegmentOffset; switch (data[pos++]) { case 0x00: rel.relativeOffset = -data.getDoubleWord(pos); pos += 4; goto checkothertype; default: return false; } break; default: return false; } segments[activeSegment].relocations.push_back(rel); } break; case 0x12: // internal symbol { PsxSymbol sym; sym.type = PsxSymbolType::Internal; sym.segment = data.getWord(pos+1); sym.offset = data.getDoubleWord(pos+3); pos += 7 + loadString(data,pos+7,sym.name); syms.push_back(sym); } break; case 0x0E: // external symbol { PsxSymbol sym; sym.type = PsxSymbolType::External; sym.id = data.getWord(pos+1); pos += 3 + loadString(data,pos+3,sym.name); syms.push_back(sym); } break; case 0x30: // bss symbol? { PsxSymbol sym; sym.type = PsxSymbolType::BSS; sym.id = data.getWord(pos+1); sym.segment = data.getWord(pos+3); sym.size = data.getDoubleWord(pos+5); pos += 9 + loadString(data,pos+9,sym.name); syms.push_back(sym); } break; case 0x0C: // internal with id { PsxSymbol sym; sym.type = PsxSymbolType::InternalID; sym.id = data.getWord(pos+1); sym.segment = data.getWord(pos+3); sym.offset = data.getDoubleWord(pos+5); pos += 9 + loadString(data,pos+9,sym.name); syms.push_back(sym); } break; case 0x4A: // function { PsxSymbol sym; sym.type = PsxSymbolType::Function; sym.segment = data.getWord(pos+1); sym.offset = data.getDoubleWord(pos+3); pos += 0x1D + loadString(data,pos+0x1D,sym.name); syms.push_back(sym); } break; case 0x4C: // function size pos += 11; break; case 0x3C: // ?? pos += 3; break; case 0x00: // ?? pos++; break; case 0x32: // ?? pos += 3; break; case 0x3A: // ?? pos += 9; break; default: return false; } } return true; }
TEST(ByteArraySuite, byteSwapping) { if(ByteArray::isByteSwapEnabled()) { ASSERT_TRUE(ByteArray::isByteSwapEnabled()); ByteArray swapped; unsigned char buffer[] = { 0x00, 0x00, 0x00, 0x38, // be: 56 0x00, 0x00, 0x00, 0x0a, // be: 10 0x00, 0x00, 0x00, 0x01, // be: 1 0x3e, 0x81, 0x32, 0x64, // be: 0.25233757495880127 0x3f, 0x30, 0x4b, 0x75, // be: 0.68865138292312622 0x3f, 0xa8, 0x9d, 0xd2, // be: 1.3173162937164307 0x3f, 0x85, 0x93, 0xdd, // be: 1.0435749292373657 0xbf, 0xf4, 0x8c, 0xc5, // be: -1.9105459451675415 }; const unsigned int bufferLength = 32; shared_int tempInt; shared_real tempReal; swapped.init((const char*) buffer, bufferLength); ASSERT_EQ(swapped.getBufferSize(), bufferLength); ASSERT_TRUE(swapped.unload(tempReal)); EXPECT_FLOAT_EQ(tempReal, -1.9105459451675415); ASSERT_TRUE(swapped.unload(tempReal)); EXPECT_FLOAT_EQ(tempReal, 1.0435749292373657); ASSERT_TRUE(swapped.unload(tempReal)); EXPECT_FLOAT_EQ(tempReal, 1.3173162937164307); ASSERT_TRUE(swapped.unload(tempReal)); EXPECT_FLOAT_EQ(tempReal, 0.68865138292312622); ASSERT_TRUE(swapped.unload(tempReal)); EXPECT_FLOAT_EQ(tempReal, 0.25233757495880127); ASSERT_TRUE(swapped.unload(tempInt)); EXPECT_EQ(tempInt, 1); ASSERT_TRUE(swapped.unload(tempInt)); EXPECT_EQ(tempInt, 10); ASSERT_TRUE(swapped.unload(tempInt)); EXPECT_EQ(tempInt, 56); ASSERT_EQ(swapped.getBufferSize(), 0); } }
void Scene::processSceneResources(SceneResourceDataArray &resourceList) { ByteArray resourceData; const byte *palPointer; SAGAResourceTypes *types = 0; int typesCount = 0; SAGAResourceTypes resType; getResourceTypes(types, typesCount); // Process the scene resource list for (SceneResourceDataArray::iterator resource = resourceList.begin(); resource != resourceList.end(); ++resource) { if (resource->invalid) { continue; } _vm->_resource->loadResource(_sceneContext, resource->resourceId, resourceData); if (resourceData.size() >= 6) { if (!memcmp(resourceData.getBuffer(), "DUMMY!", 6)) { resource->invalid = true; warning("DUMMY resource %i", resource->resourceId); } } if (resource->invalid) { continue; } if (resource->resourceType >= typesCount) { error("Scene::processSceneResources() wrong resource type %i", resource->resourceType); } resType = types[resource->resourceType]; switch (resType) { case SAGA_UNKNOWN: warning("UNKNOWN resourceType %i", resource->resourceType); break; case SAGA_ACTOR: //for (a = actorsInScene; a; a = a->nextInScene) // if (a->obj.figID == glist->file_id) // if (_vm->getGameId() == GID_ITE || // ((a->obj.flags & ACTORF_FINAL_FACE) & 0xff)) // a->sprites = (xSpriteSet *)glist->offset; warning("STUB: unimplemeted handler of SAGA_ACTOR resource"); break; case SAGA_OBJECT: break; case SAGA_BG_IMAGE: // Scene background resource if (_bg.loaded) { error("Scene::processSceneResources() Multiple background resources encountered"); } debug(3, "Loading background resource."); if (!_vm->decodeBGImage(resourceData, _bg.buffer, &_bg.w, &_bg.h)) { error("Scene::processSceneResources() Error loading background resource %i", resource->resourceId); } _bg.loaded = true; palPointer = _vm->getImagePal(resourceData); memcpy(_bg.pal, palPointer, sizeof(_bg.pal)); break; case SAGA_BG_MASK: // Scene background mask resource if (_bgMask.loaded) { error("Scene::ProcessSceneResources(): Duplicate background mask resource encountered"); } debug(3, "Loading BACKGROUND MASK resource."); _vm->decodeBGImage(resourceData, _bgMask.buffer, &_bgMask.w, &_bgMask.h, true); _bgMask.loaded = true; // At least in ITE the mask needs to be clipped. _bgMask.w = MIN(_bgMask.w, _vm->getDisplayInfo().width); _bgMask.h = MIN(_bgMask.h, getHeight()); debug(4, "BACKGROUND MASK width=%d height=%d length=%d", _bgMask.w, _bgMask.h, _bgMask.buffer.size()); break; case SAGA_STRINGS: debug(3, "Loading scene strings resource..."); _vm->loadStrings(_sceneStrings, resourceData); break; case SAGA_OBJECT_MAP: debug(3, "Loading object map resource..."); _objectMap->load(resourceData); break; case SAGA_ACTION_MAP: debug(3, "Loading action map resource..."); _actionMap->load(resourceData); break; case SAGA_ISO_IMAGES: if (!(_sceneDescription.flags & kSceneFlagISO)) { error("Scene::ProcessSceneResources(): not Iso mode"); } debug(3, "Loading isometric images resource."); _vm->_isoMap->loadImages(resourceData); break; case SAGA_ISO_MAP: if (!(_sceneDescription.flags & kSceneFlagISO)) { error("Scene::ProcessSceneResources(): not Iso mode"); } debug(3, "Loading isometric map resource."); _vm->_isoMap->loadMap(resourceData); break; case SAGA_ISO_PLATFORMS: if (!(_sceneDescription.flags & kSceneFlagISO)) { error("Scene::ProcessSceneResources(): not Iso mode"); } debug(3, "Loading isometric platforms resource."); _vm->_isoMap->loadPlatforms(resourceData); break; case SAGA_ISO_METATILES: if (!(_sceneDescription.flags & kSceneFlagISO)) { error("Scene::ProcessSceneResources(): not Iso mode"); } debug(3, "Loading isometric metatiles resource."); _vm->_isoMap->loadMetaTiles(resourceData); break; case SAGA_ANIM: { uint16 animId = resource->resourceType - 14; debug(3, "Loading animation resource animId=%i", animId); _vm->_anim->load(animId, resourceData); } break; case SAGA_ENTRY: debug(3, "Loading entry list resource..."); loadSceneEntryList(resourceData); break; case SAGA_ISO_MULTI: if (!(_sceneDescription.flags & kSceneFlagISO)) { error("Scene::ProcessSceneResources(): not Iso mode"); } debug(3, "Loading isometric multi resource."); _vm->_isoMap->loadMulti(resourceData); break; case SAGA_PAL_ANIM: debug(3, "Loading palette animation resource."); _vm->_palanim->loadPalAnim(resourceData); break; case SAGA_FACES: if (_vm->getGameId() == GID_ITE) _vm->_interface->loadScenePortraits(resource->resourceId); break; case SAGA_PALETTE: { PalEntry pal[PAL_ENTRIES]; byte *palPtr = resourceData.getBuffer(); if (resourceData.size() < 3 * PAL_ENTRIES) error("Too small scene palette %i", (int)resourceData.size()); for (uint16 c = 0; c < PAL_ENTRIES; c++) { pal[c].red = *palPtr++; pal[c].green = *palPtr++; pal[c].blue = *palPtr++; } _vm->_gfx->setPalette(pal); } break; default: error("Scene::ProcessSceneResources() Encountered unknown resource type %i", resource->resourceType); break; } } }
TEST(ByteArraySuite, copy) { const shared_int SIZE = 100; char buffer[SIZE]; // Copy ByteArray copyFrom; ByteArray copyTo; EXPECT_TRUE(copyFrom.init(&buffer[0], SIZE)); EXPECT_TRUE(copyTo.load(copyFrom)); EXPECT_EQ((shared_int)copyTo.getBufferSize(), SIZE); EXPECT_TRUE(copyTo.load(copyFrom)); EXPECT_EQ((shared_int)copyTo.getBufferSize(), 2*SIZE); // Copy too large ByteArray tooBig; if (tooBig.getMaxBufferSize()-1 <= std::numeric_limits<shared_int>::max()) { shared_int TOO_BIG = tooBig.getMaxBufferSize()-1; char bigBuffer[TOO_BIG]; EXPECT_TRUE(tooBig.init(&bigBuffer[0], TOO_BIG)); EXPECT_FALSE(copyTo.load(tooBig)); // A failed load should not change the buffer. EXPECT_EQ((shared_int)copyTo.getBufferSize(), 2*SIZE); } else std::cout << std::string(15, ' ') << "ByteArray.MaxSize==INT_MAX. Skipping TOO_BIG tests" << std::endl; }
ByteArray HTTPClient::read_response_body_chunk() { ERR_FAIL_COND_V( status !=STATUS_BODY, ByteArray() ); Error err=OK; if (chunked) { while(true) { if (chunk_left==0) { //reading len uint8_t b; int rec=0; err = connection->get_partial_data(&b,1,rec); if (rec==0) break; chunk.push_back(b); if (chunk.size()>32) { ERR_PRINT("HTTP Invalid chunk hex len"); status=STATUS_CONNECTION_ERROR; return ByteArray(); } if (chunk.size()>2 && chunk[chunk.size()-2]=='\r' && chunk[chunk.size()-1]=='\n') { int len=0; for(int i=0;i<chunk.size()-2;i++) { char c = chunk[i]; int v=0; if (c>='0' && c<='9') v=c-'0'; else if (c>='a' && c<='f') v=c-'a'+10; else if (c>='A' && c<='F') v=c-'A'+10; else { ERR_PRINT("HTTP Chunk len not in hex!!"); status=STATUS_CONNECTION_ERROR; return ByteArray(); } len<<=4; len|=v; if (len>(1<<24)) { ERR_PRINT("HTTP Chunk too big!! >16mb"); status=STATUS_CONNECTION_ERROR; return ByteArray(); } } if (len==0) { //end! status=STATUS_CONNECTED; chunk.clear(); return ByteArray(); } chunk_left=len+2; chunk.resize(chunk_left); } } else { int rec=0; err = connection->get_partial_data(&chunk[chunk.size()-chunk_left],chunk_left,rec); if (rec==0) { break; } chunk_left-=rec; if (chunk_left==0) { if (chunk[chunk.size()-2]!='\r' || chunk[chunk.size()-1]!='\n') { ERR_PRINT("HTTP Invalid chunk terminator (not \\r\\n)"); status=STATUS_CONNECTION_ERROR; return ByteArray(); } ByteArray ret; ret.resize(chunk.size()-2); { ByteArray::Write w = ret.write(); copymem(w.ptr(),chunk.ptr(),chunk.size()-2); } chunk.clear(); return ret; } break; } } } else { ByteArray::Write r = tmp_read.write(); int rec=0; err = connection->get_partial_data(r.ptr(),MIN(body_left,tmp_read.size()),rec); if (rec>0) { ByteArray ret; ret.resize(rec); ByteArray::Write w = ret.write(); copymem(w.ptr(),r.ptr(),rec); body_left-=rec; if (body_left==0) { status=STATUS_CONNECTED; } return ret; } } if (err!=OK) { close(); if (err==ERR_FILE_EOF) { status=STATUS_DISCONNECTED; //server disconnected } else { status=STATUS_CONNECTION_ERROR; } } else if (body_left==0 && !chunked) { status=STATUS_CONNECTED; } return ByteArray(); }
void Regexp::make_managed(STATE) { Regexp* obj = this; regex_t* reg = onig_data; assert(reg->chain == 0); ByteArray* reg_ba = ByteArray::create(state, sizeof(regex_t)); memcpy(reg_ba->raw_bytes(), reg, sizeof(regex_t)); regex_t* old_reg = reg; reg = reinterpret_cast<regex_t*>(reg_ba->raw_bytes()); obj->onig_data = reg; write_barrier(state, reg_ba); if(reg->p) { ByteArray* pattern = ByteArray::create(state, reg->alloc); memcpy(pattern->raw_bytes(), reg->p, reg->alloc); reg->p = reinterpret_cast<unsigned char*>(pattern->raw_bytes()); obj->write_barrier(state, pattern); } if(reg->exact) { int exact_size = reg->exact_end - reg->exact; ByteArray* exact = ByteArray::create(state, exact_size); memcpy(exact->raw_bytes(), reg->exact, exact_size); reg->exact = reinterpret_cast<unsigned char*>(exact->raw_bytes()); reg->exact_end = reg->exact + exact_size; obj->write_barrier(state, exact); } int int_map_size = sizeof(int) * ONIG_CHAR_TABLE_SIZE; if(reg->int_map) { ByteArray* intmap = ByteArray::create(state, int_map_size); memcpy(intmap->raw_bytes(), reg->int_map, int_map_size); reg->int_map = reinterpret_cast<int*>(intmap->raw_bytes()); obj->write_barrier(state, intmap); } if(reg->int_map_backward) { ByteArray* intmap_back = ByteArray::create(state, int_map_size); memcpy(intmap_back->raw_bytes(), reg->int_map_backward, int_map_size); reg->int_map_backward = reinterpret_cast<int*>(intmap_back->raw_bytes()); obj->write_barrier(state, intmap_back); } if(reg->repeat_range) { int rrange_size = sizeof(OnigRepeatRange) * reg->repeat_range_alloc; ByteArray* rrange = ByteArray::create(state, rrange_size); memcpy(rrange->raw_bytes(), reg->repeat_range, rrange_size); reg->repeat_range = reinterpret_cast<OnigRepeatRange*>(rrange->raw_bytes()); obj->write_barrier(state, rrange); } onig_free(old_reg); }