static void *senderLoop(void *arg) { Connection *conn = (Connection *) arg; char payload[RUSP_PLDS]; size_t plds; pthread_cleanup_push(cleanupFunction, &(conn->sndusrbuff.mtx)); while (1) { plds = waitLookMaxStrBuff(&(conn->sndusrbuff), payload, RUSP_PLDS); Segment sgm = createSegment((conn->sndusrbuff.size == plds) ? RUSP_PSH : RUSP_NUL, plds, getWindowNext(&(conn->sndwnd)), 0, payload); waitWindowSpace(&(conn->sndwnd), plds); addSgmBuff(&(conn->sndsgmbuff), sgm, RUSP_NACK); sendSegment(conn, sgm); slideWindowNext(&(conn->sndwnd), sgm.hdr.plds); DBGPRINT(RUSP_DEBUG, "SND (NXT): base:%u nxt:%u end:%u SNDUSRBUFF:%zu SNDSGMBUFF:%ld", getWindowBase(&(conn->sndwnd)), getWindowNext(&(conn->sndwnd)), getWindowEnd(&(conn->sndwnd)), getStrBuffSize(&(conn->sndusrbuff)), getSgmBuffSize(&(conn->sndsgmbuff))); popStrBuff(&(conn->sndusrbuff), plds); } pthread_cleanup_pop(1); return NULL; }
static void sendCACK(Connection *conn, const uint32_t ackn) { Segment acksgm; acksgm = createSegment(RUSP_CACK, 0, getWindowNext(&(conn->sndwnd)), ackn, NULL); sendSegment(conn, acksgm); }
Node *createSnake(Node *_head, int _count, Node *_body) { Node *root = createSegment(_head); setState(root, HEAD); setState(_body, BODY); const int StripeSize = 3; int counter = 0; Node *listptr = root; if(_count > 0) { //Create and position the body segments for(int i = 0; i < _count; ++i) { if(listptr!=NULL) { // Set the initial strip pattern on the snake // and change the starting frame for a ripple effect counter++; if(counter <= StripeSize) { addState(_body, ALT); _body->anim.currentFrame = 1; } else if(counter < (StripeSize*2)) { removeState(_body, ALT); _body->anim.currentFrame = 0; } else { counter = 0; } insertAfterSegment(listptr, createSegment(_body), false); updateSnakePos(root, &listptr->next, RIGHT); listptr = getLastSegment(root); } } } return root; }
void renderDigit(int x, int y, int value, int color) { if (color == GREEN) { colorPalette = greenPalette; } else { colorPalette = redPalette; } bitmap->width = 42; bitmap->height = 63; createSegment(value); tftBlt(bitmap, x, y); }
/* * ------------------------------------------------------------- main -- */ int main(int argc, const char * argv[]) { data_collect shm_sem; int shm_size = 0; int sendData; int pos = 0; char output; /* get size as parameter */ shm_size = parseParameter(argc, argv); /* create segment/semaphore and return collection or when already created only return collection */ shm_sem = createSegment(shm_size); // 3) while (!= EOF) von Shared Memory lesen // aufpassen das Leseindex hinter Schreibindex bleibt do { /* Decrement read semaphore, because we read from a written segment, if >0 all ok else block application */ if (P(shm_sem.sem_r) != 0) { if (errno == EINTR) { /* syscall interrupted by signal, try again */ continue; } perror("P(shm_sem.sem_r)"); closeSegment(shm_sem); break; } /* get character from shared memory and write to stdout */ output = shm_sem.segment[pos]; pos++; if (output != EOF) { printf("%c", output); } /* if pos == shared memory size, start at 0 again */ if (pos == shm_sem.shm_size) { pos = 0; } /* increment write semaphore to tell sender that segment is read and can be overwritten */ if (V(shm_sem.sem_w) != 0) { perror("V(shm_sem.sem_w)"); closeSegment(shm_sem); break; } } while (output != EOF); return 0; }
void ReplayController::startCapturing() { ASSERT(m_sessionState == SessionState::Inactive); ASSERT(m_segmentState == SegmentState::Unloaded); setSessionState(SessionState::Capturing); setForceDeterministicSettings(true); LOG(WebReplay, "%-20s Starting capture.\n", "ReplayController"); InspectorInstrumentation::captureStarted(m_page); m_currentPosition = ReplayPosition(0, 0); createSegment(); }
/** * retrieves a segment * * @param segId: id of the segment to be retrieved * @return: a reference to the segment */ Segment& SegmentManager::getSegment(uint64_t segId) { Segment* ret; try { ret = segmentInventory->retrieveFromMap(segId); } catch (const std::out_of_range& oor) { std::cerr << "** Segment with id: " << segId << " not in map - creating one **" << std::endl; uint64_t oldCurrentId = currentId; currentId = segId; createSegment(SegmentType::SLOTTED_PAGE, 10, ""); currentId = oldCurrentId; return getSegment(segId); } return *ret; }
SegmentManager::SegmentManager(BufferManager& bufferManager, bool isInitialSetup) : bufferManager(bufferManager) { segmentInventory = util::make_unique<SegmentInventory>(bufferManager, isInitialSetup); if(isInitialSetup) { // Build free space inventory SegmentId fsiID = segmentInventory->createSegment(); freeSpaceInventory = util::make_unique<FSISegment>(fsiID, *segmentInventory, bufferManager); // Create SPSegments for MetadataManager SegmentId spMetadataRelationsId = createSegment(SegmentType::SP, 1); assert(spMetadataRelationsId == kSchemaSegmentId); } else { // Load free space inventory SegmentId fsiID = kFreeSpaceInventoryId; freeSpaceInventory = util::make_unique<FSISegment>(fsiID, *segmentInventory, bufferManager); } assert(freeSpaceInventory->getId() == kFreeSpaceInventoryId); // for now bitches =) .. move this to meta segment later }
void activeClose(Connection *conn) { Segment fin; cancelThread(conn->sender); joinThread(conn->sender); fin = createSegment(RUSP_FIN, 0, getWindowNext(&(conn->sndwnd)), 0, NULL); addSgmBuff(&(conn->sndsgmbuff), fin, RUSP_NACK); setConnectionState(conn, RUSP_FINWT1); sendSegment(conn, fin); slideWindowNext(&(conn->sndwnd), 1); DBGPRINT(RUSP_DEBUG, "SND (NXT): base:%u nxt:%u end:%u SNDUSRBUFF:%zu SNDSGMBUFF:%ld", getWindowBase(&(conn->sndwnd)), getWindowNext(&(conn->sndwnd)), getWindowEnd(&(conn->sndwnd)), getStrBuffSize(&(conn->sndusrbuff)), getSgmBuffSize(&(conn->sndsgmbuff))); joinThread(conn->receiver); }
void ReplayController::frameNavigated(DocumentLoader* loader) { ASSERT(m_sessionState != SessionState::Inactive); ASSERT_ARG(loader, loader); // The initial capturing segment is created prior to main frame navigation. // Otherwise, the prior capturing segment was completed when the frame detached, // and it is now time to create a new segment. if (m_sessionState == SessionState::Capturing && m_segmentState == SegmentState::Unloaded) { m_currentPosition = ReplayPosition(m_currentPosition.segmentOffset + 1, 0); createSegment(); } // During playback, the next segment is loaded when the final input is dispatched, // so nothing needs to be done here. // We store the input cursor in both Document and JSDOMWindow, so that // replay state is accessible from JavaScriptCore and script-free layout code. loader->frame()->document()->setInputCursor(m_activeCursor.get()); loader->frame()->script().globalObject(mainThreadNormalWorld())->setInputCursor(m_activeCursor.get()); }
cpShape *cpSpaceSerializer::createShape(TiXmlElement *elm) { cpShape *shape; const char* type = elm->Attribute("type"); if (stringEquals(type, "circle")) shape = createCircle(elm); else if (stringEquals(type, "segment")) shape = createSegment(elm); else if (stringEquals(type, "poly")) shape = createPoly(elm); else return NULL; CPSS_ID id = createValue<CPSS_ID>("id", elm); _shapeMap[id] = shape; shape->sensor = createValue<int>("sensor", elm); shape->e = createValue<cpFloat>("e", elm); shape->u = createValue<cpFloat>("u", elm); shape->surface_v = createPoint("surface_v", elm); shape->collision_type = createValue<cpCollisionType>("collision_type", elm); shape->group = createValue<cpGroup>("group", elm); shape->layers = createValue<cpLayers>("layers", elm); if (delegate) { if (!delegate->reading(shape, id)) { if (shape->body != _space->staticBody) cpBodyFree(shape->body); cpShapeFree(shape); shape = NULL; } } return shape; }
/** creates vehicle at desired position */ void Schlange::create(const osg::Matrix& pose){ if (created) { destroy(); } odeHandle.createNewSimpleSpace(parentspace,false); int half = conf.segmNumber/2; int segperspace=5; if(conf.useSpaces){ int spacenum=conf.segmNumber/segperspace+1; spaces.resize(spacenum); for(int i=0; i<spacenum; i++){ OdeHandle o(odeHandle); o.createNewSimpleSpace(odeHandle.space,true); spaces[i]=o; } } if(conf.frictionRatio != 1) odeHandle.substance.toAnisotropFriction(conf.frictionRatio, Axis(0,0,1)); for ( int n = 0; n < conf.segmNumber; n++ ) { Primitive* p; if(conf.useSpaces) p = createSegment(n, spaces[n/segperspace]); else p = createSegment(n, odeHandle); p->setPose(p->getPose() * osg::Matrix::rotate(M_PI/2, 0, 1, 0) * osg::Matrix::translate((n-half)*conf.segmLength, 0 , conf.segmDia/2) * pose); objects.push_back(p); } // if (n==-1* conf.segmNumber/2) { // p = new Box(conf.segmLength*1.8,conf.segmLength*.8, conf.segmLength*1); // //p = new Capsule(conf.segmDia*2 , conf.segmLength); // p->init(odeHandle, conf.segmMass*2, osgHandle); // } // // else { // //if(n==0 || n== conf.segmNumber){ // // p = new Box(conf.segmLength,conf.segmLength*2, conf.segmLength); // // p->init(odeHandle, conf.segmMass*2, osgHandle); // // } // else{ // if(n==-1/*== 0 | n== conf.segmNumber-1*/) { // p = new Capsule(conf.segmDia*.8/*2.8*/ , conf.segmLength*1); // // p = new Box(conf.segmLength*.3,conf.segmLength, conf.segmLength*.9); // p->init(odeHandle, conf.segmMass*4, osgHandle);} // else{ // p = new Capsule(conf.segmDia*.8 , conf.segmLength); // // p = new Box(conf.segmLength*.3,conf.segmLength*0.3, conf.segmLength*1.0); // p->init(odeHandle, conf.segmMass, osgHandle); // } } // // else { // // p->setPose(osg::Matrix::rotate(M_PI/2, 0, 1, 0) * // // osg::Matrix::translate((n-half)*conf.segmLength*(1+((double)n)/10), 0 , conf.segmDia/2) * // // pose); // p->setPose(osg::Matrix::rotate(M_PI/2, 0, 1, 0) * // // p->setPose(osg::Matrix::rotate(M_PI/2, 0, 1, 0) * // osg::Matrix::translate((n-half)*conf.segmLength, 0 , conf.segmDia/2) * // pose); // // p->getOSGPrimitive()->setTexture("Images/wood.rgb"); // // p->getOSGPrimitive()->setTexture("Images/tire.rgb"); // p->getOSGPrimitive()->setTexture("Images/whitemetal_farbig.rgb"); // // p->getOSGPrimitive()->setColor(Color(0.0f,0.0f,1.0f,0.2f)); // objects.push_back(p); // } created=true; };
ConnectionId passiveOpen(Connection *lconn) { Connection *aconn = NULL; Segment syn, synack, acksynack; char ssyn[RUSP_SGMS + 1], ssynack[RUSP_SGMS + 1], sacksynack[RUSP_SGMS + 1]; int asock, synackretrans; struct sockaddr_in caddr; struct timespec start, end; long double sampleRTT; while (getConnectionState(lconn) == RUSP_LISTEN) { readUSocket(lconn->sock.fd, &caddr, ssyn, RUSP_SGMS); deserializeSegment(ssyn, &syn); DBGFUNC(RUSP_DEBUG, printInSegment(caddr, syn)); if (syn.hdr.ctrl != RUSP_SYN) continue; setConnectionState(lconn, RUSP_SYNRCV); asock = openSocket(); synack = createSegment(RUSP_SYN | RUSP_SACK, 0, 10, RUSP_NXTSEQN(syn.hdr.seqn, 1), NULL); serializeSegment(synack, ssynack); for (synackretrans = 0; synackretrans < RUSP_RETR; synackretrans++) { clock_gettime(CLOCK_MONOTONIC, &start); writeUSocket(asock, caddr, ssynack, strlen(ssynack)); DBGFUNC(RUSP_DEBUG, printOutSegment(caddr, synack)); setConnectionState(lconn, RUSP_SYNSND); if (!selectSocket(asock, RUSP_SAMPLRTT)) continue; readUSocket(asock, &caddr, sacksynack, RUSP_SGMS); clock_gettime(CLOCK_MONOTONIC, &end); sampleRTT = getElapsed(start, end); deserializeSegment(sacksynack, &acksynack); DBGFUNC(RUSP_DEBUG, printInSegment(caddr, acksynack)); if ((acksynack.hdr.ctrl == RUSP_SACK) & (acksynack.hdr.seqn == synack.hdr.ackn) & (acksynack.hdr.ackn == RUSP_NXTSEQN(synack.hdr.seqn, 1))) { aconn = createConnection(); setConnectionState(aconn, RUSP_SYNSND); setupConnection(aconn, asock, caddr, acksynack.hdr.ackn, acksynack.hdr.seqn, sampleRTT); setConnectionState(lconn, RUSP_LISTEN); return aconn->connid; } } closeSocket(asock); setConnectionState(lconn, RUSP_LISTEN); } return -1; }
int activeOpen(Connection *conn, const struct sockaddr_in laddr) { Segment syn, synack, acksynack; char ssyn[RUSP_SGMS + 1], ssynack[RUSP_SGMS + 1], sacksynack[RUSP_SGMS + 1]; int asock, synretrans; struct sockaddr_in aaddr; struct timespec start, end; long double sampleRTT; if (getConnectionState(conn) != RUSP_CLOSED) ERREXIT("Cannot synchronize connection: connection not closed."); asock = openSocket(); syn = createSegment(RUSP_SYN, 0, 0, 0, NULL); serializeSegment(syn, ssyn); for (synretrans = 0; synretrans < RUSP_SYN_RETR; synretrans++) { clock_gettime(CLOCK_MONOTONIC, &start); writeUSocket(asock, laddr, ssyn, strlen(ssyn)); DBGFUNC(RUSP_DEBUG, printOutSegment(laddr, syn)); setConnectionState(conn, RUSP_SYNSND); if (!selectSocket(asock, RUSP_SAMPLRTT)) continue; readUSocket(asock, &aaddr, ssynack, RUSP_SGMS); clock_gettime(CLOCK_MONOTONIC, &end); sampleRTT = getElapsed(start, end); deserializeSegment(ssynack, &synack); DBGFUNC(RUSP_DEBUG, printInSegment(aaddr, synack)); if ((synack.hdr.ctrl == (RUSP_SYN | RUSP_SACK)) & (synack.hdr.ackn == RUSP_NXTSEQN(syn.hdr.seqn, 1))) { setConnectionState(conn, RUSP_SYNRCV); acksynack = createSegment(RUSP_SACK, 0, RUSP_NXTSEQN(syn.hdr.seqn, 1), RUSP_NXTSEQN(synack.hdr.seqn, 1), NULL); serializeSegment(acksynack, sacksynack); writeUSocket(asock, aaddr, sacksynack, strlen(sacksynack)); DBGFUNC(RUSP_DEBUG, printOutSegment(aaddr, acksynack)); setupConnection(conn, asock, aaddr, acksynack.hdr.seqn, acksynack.hdr.ackn, sampleRTT); return conn->connid; } } closeSocket(asock); setConnectionState(conn, RUSP_CLOSED); return -1; }
/* *createRNDF function * *p : a pointer to an array of strings represinting a RNDF * *this function will take an array of strings represinting a RNDF *and return a struct RNDF */ struct RNDF *createRNDF(char **p) { struct RNDF *r; char *temp; char **params; int now; int n = 0; int i; int s_start; int s_end; int z_start; int z_end; r = malloc(sizeof(struct RNDF)); assert(r != 0); now = numberOfWords(p[n]); assert(now == 2); params = divideLine(p[n], now, MAX_STRING_LENGTH); assert(params != 0); r -> RNDF_name = malloc(MAX_STRING_LENGTH * sizeof(char)); stringCopy(params[1], r -> RNDF_name); freeCharArray(params, now); n++; now = numberOfWords(p[n]); assert(now == 2); params = divideLine(p[n], now, MAX_STRING_LENGTH); assert(params != 0); r -> number_of_segments = atoi(params[1]); freeCharArray(params, now); n++; now = numberOfWords(p[n]); assert(now == 2); params = divideLine(p[n], now, MAX_STRING_LENGTH); assert(params != 0); r -> number_of_zones = atoi(params[1]); freeCharArray(params, now); n++; temp = "format_version"; now = numberOfWords(p[n]); params = divideLine(p[n], now, MAX_STRING_LENGTH); assert(params != 0); if(compTwoStrings(params[0], temp)){ assert(now == 2); r -> format_version = malloc(MAX_STRING_LENGTH * sizeof(char)); stringCopy(params[1], r -> format_version); n++; } else r -> format_version = 0; freeCharArray(params, now); temp = "creation_date"; now = numberOfWords(p[n]); params = divideLine(p[n], now, MAX_STRING_LENGTH); assert(params != 0); if(compTwoStrings(params[0], temp)){ assert(now == 2); r -> creation_date = malloc(MAX_STRING_LENGTH * sizeof(char)); stringCopy(params[1], r -> creation_date); n++; } else r -> creation_date = 0; freeCharArray(params, now); r -> segments_list = malloc(r -> number_of_segments * sizeof(struct segment)); s_start = n; s_end = n + 1; temp = "end_segment"; for(i = 0; i < r -> number_of_segments; i++){ r -> segments_list[i] = createSegment((p + s_start)); now = numberOfWords(p[s_end]); params = divideLine(p[s_end], now, MAX_STRING_LENGTH); assert(params != 0); while(!compTwoStrings(temp, params[0])){ freeCharArray(params, now); s_end++; now = numberOfWords(p[s_end]); params = divideLine(p[s_end], now, MAX_STRING_LENGTH); assert(params != 0); } freeCharArray(params, now); s_end++; s_start = s_end; } n = s_end; r -> zones_list = malloc(r -> number_of_zones * sizeof(struct zone)); z_start = n; z_end = n + 1; temp = "end_zone"; for(i = 0; i < r -> number_of_zones; i++){ r -> zones_list[i] = createZone((p + s_start)); now = numberOfWords(p[z_end]); params = divideLine(p[z_end], now, MAX_STRING_LENGTH); assert(params != 0); while(!compTwoStrings(temp, p[s_end])){ freeCharArray(params, now); s_end++; now = numberOfWords(p[z_end]); params = divideLine(p[z_end], now, MAX_STRING_LENGTH); assert(params != 0); } freeCharArray(params, now); s_end++; s_start = s_end; } n = s_end; return r; }
unsigned int loadIntoIdb(FILE *dll) { _IMAGE_DOS_HEADER dos, *pdos; _IMAGE_NT_HEADERS nt, *pnt; _IMAGE_SECTION_HEADER sect, *psect; unsigned int exp_size, exp_rva, exp_fileoff; _IMAGE_EXPORT_DIRECTORY *expdir = NULL; unsigned int len, handle; if (fread(&dos, sizeof(_IMAGE_DOS_HEADER), 1, dll) != 1) { return 0xFFFFFFFF; } if (dos.e_magic != 0x5A4D || fseek(dll, dos.e_lfanew, SEEK_SET)) { return 0xFFFFFFFF; } if (fread(&nt, sizeof(_IMAGE_NT_HEADERS), 1, dll) != 1) { return 0xFFFFFFFF; } if (nt.Signature != 0x4550) { return 0xFFFFFFFF; } if (fread(§, sizeof(_IMAGE_SECTION_HEADER), 1, dll) != 1) { return 0xFFFFFFFF; } //read all header bytes into buff len = sect.PointerToRawData; unsigned char *dat = (unsigned char*)malloc(len); if (dat == NULL || fseek(dll, 0, SEEK_SET) || fread(dat, len, 1, dll) != 1) { free(dat); return 0xFFFFFFFF; } pdos = (_IMAGE_DOS_HEADER*)dat; pnt = (_IMAGE_NT_HEADERS*)(dat + pdos->e_lfanew); handle = pnt->OptionalHeader.ImageBase; psect = (_IMAGE_SECTION_HEADER*)(pnt + 1); //now loop to find hole large enough to accomodate image //try ImageBase first bool found = false; bool triedDefault = handle == 0x10000000; do { msg("Trying base address of 0x%x\n", handle); segment_t *s = getseg(handle); if (s == NULL) { #if (IDA_SDK_VERSION < 530) segment_t *n = (segment_t *)segs.getn_area(segs.get_next_area(handle)); #else segment_t *n = get_next_seg(handle); #endif if (n != NULL) { unsigned int moduleEnd = getModuleEnd(n->startEA); if (moduleEnd == 0xffffffff) { moduleEnd = n->endEA; } if ((n->startEA - handle) >= nt.OptionalHeader.SizeOfImage) { found = true; } else { handle = (moduleEnd + 0x10000) & ~0xffff; } } else if ((0x80000000 - handle) >= nt.OptionalHeader.SizeOfImage) { found = true; } } else { unsigned int moduleEnd = getModuleEnd(s->startEA); if (moduleEnd == 0xffffffff) { moduleEnd = s->endEA; } handle = (moduleEnd + 0x10000) & ~0xffff; } if (!found && (handle >= 0x80000000 || (0x80000000 - handle) < nt.OptionalHeader.SizeOfImage)) { if (triedDefault) { //no room to load this library free(dat); return 0xFFFFFFFF; } else { handle = 0x10000000; triedDefault = true; } } } while (!found); createSegment(handle, len, dat); applyPEHeaderTemplates(handle); exp_rva = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; exp_size = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size; if (exp_rva && exp_size) { exp_fileoff = rvaToFileOffset(psect, nt.FileHeader.NumberOfSections, exp_rva); expdir = (_IMAGE_EXPORT_DIRECTORY*)malloc(exp_size); } if (expdir == NULL || fseek(dll, exp_fileoff, SEEK_SET) || fread(expdir, exp_size, 1, dll) != 1) { free(dat); free(expdir); return 0xFFFFFFFF; } createSegment(handle + exp_rva, exp_size, (unsigned char*)expdir); if (expdir->AddressOfFunctions < exp_rva || expdir->AddressOfFunctions >= (exp_rva + exp_size)) { //EAT lies outside directory bounds msg("EAT lies outside directory bounds\n"); } if (expdir->AddressOfNames != 0 && expdir->AddressOfNames < exp_rva || expdir->AddressOfNames >= (exp_rva + exp_size)) { //ENT lies outside directory bounds msg("ENT lies outside directory bounds\n"); } if (expdir->AddressOfNameOrdinals != 0 && expdir->AddressOfNameOrdinals < exp_rva || expdir->AddressOfNameOrdinals >= (exp_rva + exp_size)) { //EOT lies outside directory bounds msg("EOT lies outside directory bounds\n"); } free(dat); free(expdir); return handle; }
void PETables::buildThunks(FILE *f) { unsigned int import_rva, min_rva = 0xFFFFFFFF, max_rva = 0; unsigned int min_iat = 0xFFFFFFFF, max_iat = 0; _IMAGE_IMPORT_DESCRIPTOR desc; import_rva = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; if (import_rva) { msg("import_rva = %x, image_base = %x\n", import_rva, (unsigned int)nt->OptionalHeader.ImageBase); import_rva = rvaToFileOffset(import_rva); imports = NULL; while (1) { // msg("iat seeking to %x\n", import_rva); if (fseek(f, import_rva, SEEK_SET)) { // msg("Could not seek to import table: %x\n", import_rva); destroy(); return; } if (fread(&desc, sizeof(desc), 1, f) != 1) { // msg("Failed to read import table\n"); destroy(); return; } unsigned int iat_base = desc.FirstThunk; // msg("iat_base = %x\n", iat_base); if (iat_base == 0) break; //end of import descriptor array unsigned int name_table = desc.OriginalFirstThunk; unsigned int name = desc.Name; //rva of dll name string unsigned int iat = rvaToFileOffset(iat_base); if (name_table == 0) { name_table = iat; } else { name_table = rvaToFileOffset(name_table); } import_rva = ftell(f); name = rvaToFileOffset(name); thunk_rec *tr = (thunk_rec*)calloc(1, sizeof(thunk_rec)); if (tr == NULL) { // msg("Failed to alloc thunk record\n"); destroy(); return; } tr->iat_base = iat_base; if (iat_base < min_iat) min_iat = iat_base; tr->next = imports; imports = tr; if (fseek(f, name, SEEK_SET)) { // msg("Could not seek to name %x\n", name); destroy(); return; } tr->dll_name = stringFromFile(f); if (tr->dll_name == NULL) { // msg("dll_name was null\n"); destroy(); return; } // msg("thunk dll: %s\n", tr->dll_name); if (fseek(f, name_table, SEEK_SET)) { // if (fseek(f, iat, SEEK_SET)) { msg("Could not seek to iat\n"); destroy(); return; } if (desc.Name < min_rva) min_rva = desc.Name; if (desc.Name > max_rva) max_rva = desc.Name + strlen(tr->dll_name) + 1; while (1) { tr->iat = (unsigned int*)realloc(tr->iat, (tr->iat_size + 1) * sizeof(unsigned int)); if (tr->iat == NULL) { msg("failed to realloc iat\n"); destroy(); return; } if (fread(&tr->iat[tr->iat_size], sizeof(unsigned int), 1, f) != 1) { msg("Failed to read iat\n"); destroy(); return; } tr->iat_size++; if (tr->iat[tr->iat_size - 1] == 0) break; } unsigned int end_iat = iat_base + 4 * tr->iat_size; if (end_iat > max_iat) max_iat = end_iat; // tr->names = (char**)calloc(tr->iat_size, sizeof(char*)); for (int i = 0; tr->iat[i]; i++) { unsigned int name_rva = tr->iat[i]; if (name_rva & 0x80000000) continue; //import by ordinal if (fseek(f, rvaToFileOffset(name_rva + 2), SEEK_SET)) { msg("Could not seek to name_rva (by ordinal)\n"); destroy(); return; } // tr->names[i] = stringFromFile(f); char *n = stringFromFile(f); #ifdef DEBUG msg("read import name %s\n", n); #endif if (name_rva < min_rva) min_rva = name_rva; if (name_rva > max_rva) max_rva = name_rva + strlen(n) + 1; free(n); } } if (isEnabled(base + min_rva) && isEnabled(base + max_rva - 1)) { } else { unsigned int sz = max_rva - min_rva + 2; unsigned char *strtable = (unsigned char *)malloc(sz); if (fseek(f, rvaToFileOffset(min_rva), SEEK_SET)) { free(strtable); // destroy(); return; } if (fread(strtable, sz, 1, f) != 1) { free(strtable); // destroy(); return; } createSegment(base + min_rva, sz, strtable); free(strtable); } // Make sure there is a segment to hold the import table if (!isEnabled(base + min_iat) && !isEnabled(base + max_iat - 1)) { createSegment(base + min_iat, max_iat - min_iat, NULL); } } }
int main() { initializeSemaphores(); // Declare values to store data in the segments int chairsShmID, barbersShmID, cashiershmID, specialClientsCounterShmID, stopClientsShmID, stopSpecialClientesShmID, chairsQuantityShmID, barbersQuantityShmID, nodeShmID, chairsQuantity, barbersQuantity, cashierQueueSize = 100, *specialClientsCounterPtr, *stopClientesPtr, *stopSpecialClientsPtr, *chairsQuantityPtr, *barbersQuantityPtr, *cashierQueuePtr,*chairsQueuePtr, *barbersListPtr; key_t chairsKey, barbersKey, cashierKey, specialClientsCounterKey, stopClientsKey, stopSpecialClientsKey,chairsQuantityKey,barbersQuantityKey; // Segment keys to be used chairsKey = 5677; barbersKey = 5678; cashierKey = 5679; specialClientsCounterKey = 5680; stopClientsKey = 5681; stopSpecialClientsKey = 5682; chairsQuantityKey = 5683; barbersQuantityKey = 5684; // Get the maximun amount of chairs printf("Ingrese la cantidad de sillas: "); scanf("%d", &chairsQuantity); // Get the maximum amout of barbers printf("Ingrese la cantidad de barberos: "); scanf("%d", &barbersQuantity); // Initialize necessary arrays int chairsQueue[chairsQuantity]; chairsQueuePtr = chairsQueue; int barbersList[barbersQuantity]; barbersListPtr = barbersList; int cashierQueue[CASHIER_QUEUE_SIZE]; cashierQueuePtr = cashierQueue; // Create the neccessary segments chairsShmID = createSegment(chairsKey,STRUCT_SEG_SIZE); barbersShmID = createSegment(barbersKey,STRUCT_SEG_SIZE); cashiershmID = createSegment(cashierKey,cashierQueueSize); specialClientsCounterShmID = createSegment(specialClientsCounterKey,INT_SEG_SIZE); stopClientsShmID = createSegment(stopClientsKey,INT_SEG_SIZE); stopSpecialClientesShmID = createSegment(stopSpecialClientsKey,INT_SEG_SIZE); chairsQuantityShmID = createSegment(chairsQuantityKey,INT_SEG_SIZE); barbersQuantityShmID = createSegment(barbersQuantityKey,INT_SEG_SIZE); printf("Segmentos creados ... \n"); // Attach the segment structures chairsQueuePtr = attachIntSegment(chairsShmID); barbersListPtr = attachIntSegment(barbersShmID); cashierQueuePtr = attachIntSegment(cashiershmID); specialClientsCounterPtr = attachIntSegment(specialClientsCounterShmID); stopClientesPtr = attachIntSegment(stopClientsShmID); stopSpecialClientsPtr = attachIntSegment(stopSpecialClientesShmID); chairsQuantityPtr = attachIntSegment(chairsQuantityShmID); barbersQuantityPtr = attachIntSegment(barbersQuantityShmID); printf("Estructuras asignadas a los segmentos ... \n"); // Set structures initial values *specialClientsCounterPtr = 0; *stopClientesPtr = 1; *stopSpecialClientsPtr = 1; *chairsQuantityPtr = chairsQuantity; *barbersQuantityPtr = barbersQuantity; //Initialize share structures with empty spaces clearControlArray(chairsQueuePtr,chairsQuantity,0); clearControlArray(barbersListPtr,barbersQuantity,0); clearControlArray(cashierQueuePtr,CASHIER_QUEUE_SIZE,0); printf("Structuras inicializadas... \n"); printf("Recursos inicializados exitosamente! \n"); exit(0); return 0; }
unsigned int loadIntoIdb(FILE *dll) { _IMAGE_DOS_HEADER dos, *pdos; _IMAGE_NT_HEADERS nt, *pnt; _IMAGE_SECTION_HEADER sect, *psect; unsigned int exp_size, exp_rva, exp_fileoff; _IMAGE_EXPORT_DIRECTORY *expdir; unsigned int len, handle; if (fread(&dos, sizeof(_IMAGE_DOS_HEADER), 1, dll) != 1) { return 0xFFFFFFFF; } if (dos.e_magic != 0x5A4D || fseek(dll, dos.e_lfanew, SEEK_SET)) { return 0xFFFFFFFF; } if (fread(&nt, sizeof(_IMAGE_NT_HEADERS), 1, dll) != 1) { return 0xFFFFFFFF; } if (nt.Signature != 0x4550) { return 0xFFFFFFFF; } if (fread(§, sizeof(_IMAGE_SECTION_HEADER), 1, dll) != 1) { return 0xFFFFFFFF; } //read all header bytes into buff len = sect.PointerToRawData; unsigned char *dat = (unsigned char*)malloc(len); if (dat == NULL || fseek(dll, 0, SEEK_SET) || fread(dat, len, 1, dll) != 1) { free(dat); return 0xFFFFFFFF; } pdos = (_IMAGE_DOS_HEADER*)dat; pnt = (_IMAGE_NT_HEADERS*)(dat + pdos->e_lfanew); handle = pnt->OptionalHeader.ImageBase; psect = (_IMAGE_SECTION_HEADER*)(pnt + 1); createSegment(handle, len, dat); applyPEHeaderTemplates(handle); exp_rva = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; exp_size = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size; exp_fileoff = rvaToFileOffset(psect, nt.FileHeader.NumberOfSections, exp_rva); expdir = (_IMAGE_EXPORT_DIRECTORY*)malloc(exp_size); if (expdir == NULL || fseek(dll, exp_fileoff, SEEK_SET) || fread(expdir, exp_size, 1, dll) != 1) { free(dat); free(expdir); return 0xFFFFFFFF; } createSegment(handle + exp_rva, exp_size, (unsigned char*)expdir); if (expdir->AddressOfFunctions < exp_rva || expdir->AddressOfFunctions >= (exp_rva + exp_size)) { //EAT lies outside directory bounds msg("EAT lies outside directory bounds\n"); } if (expdir->AddressOfNames < exp_rva || expdir->AddressOfNames >= (exp_rva + exp_size)) { //ENT lies outside directory bounds msg("ENT lies outside directory bounds\n"); } if (expdir->AddressOfNameOrdinals < exp_rva || expdir->AddressOfNameOrdinals >= (exp_rva + exp_size)) { //EOT lies outside directory bounds msg("EOT lies outside directory bounds\n"); } free(dat); free(expdir); return handle; }