예제 #1
0
파일: hook.c 프로젝트: MartinDrab/IRPMon
NTSTATUS HookDriverObject(PDRIVER_OBJECT DriverObject, PDRIVER_MONITOR_SETTINGS MonitorSettings, PDRIVER_HOOK_RECORD *DriverRecord)
{
	KIRQL irql;
	PDRIVER_HOOK_RECORD record = NULL;
	PDEVICE_HOOK_RECORD *existingDevices = NULL;
	ULONG existingDeviceCount = 0;
	NTSTATUS status = STATUS_UNSUCCESSFUL;
	DEBUG_ENTER_FUNCTION("DriverObject=0x%p; MonitorSettings=%u; DriverRecord=0x%p", DriverObject, MonitorSettings, DriverRecord);

	status = _DriverHookRecordCreate(DriverObject, MonitorSettings, FALSE, &record);
	if (NT_SUCCESS(status)) {
		status = _CreateRecordsForExistingDevices(record, &existingDevices, &existingDeviceCount);
		if (NT_SUCCESS(status)) {
			KeAcquireSpinLock(&_driverTableLock, &irql);
			if (HashTableGet(_driverTable, DriverObject) == NULL) {
				KIRQL irql2;
				ULONG i = 0;

				DriverHookRecordReference(record);
				HashTableInsert(_driverTable, &record->HashItem, DriverObject);
				KeAcquireSpinLock(&record->SelectedDevicesLock, &irql2);
				for (i = 0; i < existingDeviceCount; ++i) {
					PDEVICE_HOOK_RECORD deviceRecord = existingDevices[i];

					DeviceHookRecordReference(deviceRecord);
					HashTableInsert(record->SelectedDevices, &deviceRecord->HashItem, deviceRecord->DeviceObject);
				}

				KeReleaseSpinLock(&record->SelectedDevicesLock, irql2);
				KeReleaseSpinLock(&_driverTableLock, irql);
				_MakeDriverHookRecordValid(record);
				if (record->MonitoringEnabled)
					_HookDriverObject(DriverObject, record);

				DriverHookRecordReference(record);
				*DriverRecord = record;
			} else {
				KeReleaseSpinLock(&_driverTableLock, irql);
				status = STATUS_ALREADY_REGISTERED;
			}

			_FreeDeviceHookRecordArray(existingDevices, existingDeviceCount);
		}

		DriverHookRecordDereference(record);
	}

	DEBUG_EXIT_FUNCTION("0x%x, *DriverRecord=0x%p", status, *DriverRecord);
	return status;
}
예제 #2
0
void DigestCacheSet(DigestCache* self, const char* filename, uint32_t hash, uint64_t timestamp, const HashDigest& digest)
{
  ReadWriteLockWrite(&self->m_Lock);

  DigestCacheRecord* r;

  if (nullptr != (r = (DigestCacheRecord*) HashTableLookup(&self->m_Table, hash, filename)))
  {
    r->m_Timestamp     = timestamp;
    r->m_ContentDigest = digest;
    r->m_AccessTime    = self->m_AccessTime;
  }
  else
  {
    r = LinearAllocate<DigestCacheRecord>(&self->m_Allocator);
    r->m_Hash          = hash;
    r->m_ContentDigest = digest;
    r->m_Next          = nullptr;
    r->m_String        = StrDup(&self->m_Allocator, filename);
    r->m_Timestamp     = timestamp;
    r->m_AccessTime    = self->m_AccessTime;
    HashTableInsert(&self->m_Table, r);
  }

  ReadWriteUnlockWrite(&self->m_Lock);
}
예제 #3
0
파일: piggy.cpp 프로젝트: paud/d2x-xl
tBitmapIndex PiggyRegisterBitmap (grsBitmap *bmP, const char *name, int bInFile)
{
	tBitmapIndex temp;
	Assert (gameData.pig.tex.nBitmaps [gameStates.app.bD1Data] < MAX_BITMAP_FILES);

if (strstr (name, "door13"))
	name = name;
temp.index = gameData.pig.tex.nBitmaps [gameStates.app.bD1Data];
if (!bInFile) {
#ifdef EDITOR
	if (FindArg ("-macdata"))
		swap_0_255 (bmP);
#endif
	if (!bBigPig)  
		gr_bitmap_rle_compress (bmP);
	nBitmapFilesNew++;
	}
strncpy (gameData.pig.tex.pBitmapFiles [gameData.pig.tex.nBitmaps [gameStates.app.bD1Data]].name, name, 12);
HashTableInsert (bitmapNames + gameStates.app.bD1Mission, 
						gameData.pig.tex.pBitmapFiles[gameData.pig.tex.nBitmaps [gameStates.app.bD1Data]].name, 
						gameData.pig.tex.nBitmaps [gameStates.app.bD1Data]);
gameData.pig.tex.pBitmaps [gameData.pig.tex.nBitmaps [gameStates.app.bD1Data]] = *bmP;
if (!bInFile) {
	bitmapOffsets [gameStates.app.bD1Data][gameData.pig.tex.nBitmaps [gameStates.app.bD1Data]] = 0;
	gameData.pig.tex.bitmapFlags [gameStates.app.bD1Data][gameData.pig.tex.nBitmaps [gameStates.app.bD1Data]] = bmP->bmProps.flags;
	}
gameData.pig.tex.nBitmaps [gameStates.app.bD1Data]++;
return temp;
}
예제 #4
0
static return_val registerSec( orl_sec_handle shnd, section_type type )
{
    section_ptr         sec;
    return_val          error;

    sec = MemAlloc( sizeof( section_struct ) );
    if( sec ) {
        error = HashTableInsert( HandleToSectionTable, (hash_value) shnd, (hash_data) sec );
        if( error == OKAY ) {
            memset( sec, 0, sizeof( section_struct ) );
            sec->shnd = shnd;
            sec->name = ORLSecGetName( shnd );
            sec->type = type;
            sec->next = NULL;
            if( Sections.first ) {
                Sections.last->next = sec;
                Sections.last = sec;
            } else {
                Sections.first = sec;
                Sections.last = sec;
            }
        } else {
            MemFree( sec );
            return( OUT_OF_MEMORY );
        }
    } else {
        return( OUT_OF_MEMORY );
    }
    return( OKAY );
}
예제 #5
0
static FunctionMeta* FindFunction(lua_State* L, lua_Debug* ar)
{
  // This is slow, it involves string formatting. It's mostly OK, because we're
  // careful not to include this in the timings. It will of course affect cache
  // and other things. Not that we can make a lot of informed decisions about
  // that in an interpreted language anyway.
  if (!lua_getinfo(L, "Sn", ar))
    Croak("couldn't get debug info for function call");

  char buffer[1024];
  snprintf(buffer, sizeof(buffer), "%s;%s;%s;%d",
      ar->name ? ar->name : "", ar->namewhat ? ar->namewhat : "", ar->source, ar->linedefined);
  buffer[(sizeof buffer)-1] = 0;

  const uint32_t hash = Djb2Hash(buffer);
  HashRecord* r = HashTableLookup(&s_Profiler.m_Functions, hash, buffer);

  if (!r) {
    r = LinearAllocate<FunctionMeta>(s_Profiler.m_Allocator);
    r->m_Hash   = hash;
    r->m_String = StrDup(s_Profiler.m_Allocator, buffer);
    r->m_Next   = nullptr;
    HashTableInsert(&s_Profiler.m_Functions, r);
  }
  
  return static_cast<FunctionMeta*>(r);
}
예제 #6
0
static return_val createLabelList( orl_sec_handle shnd )
{
    label_list          list;
    return_val          error;

    list = MemAlloc( sizeof( label_list_struct ) );
    if( list ) {
        list->first = NULL;
        list->last = NULL;
        error = HashTableInsert( HandleToLabelListTable, (hash_value) shnd, (hash_data) list );
        if( error == OKAY ) {
            if( (Options & PRINT_PUBLICS) && shnd != 0 ) {
                error = addListToPublics( list );
                if( error != OKAY ) {
                    MemFree( list );
                }
            }
        } else {
            MemFree( list );
        }
    } else {
        error = OUT_OF_MEMORY;
    }
    return( error );
}
예제 #7
0
static return_val registerSec( orl_sec_handle shnd, section_type type )
{
    section_ptr         section;
    return_val          error;
    hash_entry_data     key_entry;

    section = MemAlloc( sizeof( section_struct ) );
    if( section != NULL ) {
        key_entry.key.u.sec_handle = shnd;
        key_entry.data.u.section = section;
        error = HashTableInsert( HandleToSectionTable, &key_entry );
        if( error == RC_OKAY ) {
            memset( section, 0, sizeof( section_struct ) );
            section->shnd = shnd;
            section->name = ORLSecGetName( shnd );
            section->type = type;
            section->next = NULL;
            if( Sections.first != NULL ) {
                Sections.last->next = section;
                Sections.last = section;
            } else {
                Sections.first = section;
                Sections.last = section;
            }
        } else {
            MemFree( section );
            return( RC_OUT_OF_MEMORY );
        }
    } else {
        return( RC_OUT_OF_MEMORY );
    }
    return( RC_OKAY );
}
예제 #8
0
NTSTATUS HandleTableHandleDuplicate(PCHANDLE_TABLE HandleTable, HANDLE Handle, PHANDLE NewHandle)
{
	KIRQL irql;
	PCHANDLE_TABLE_MAPPING newMapping = NULL;
	NTSTATUS status = STATUS_UNSUCCESSFUL;
	DEBUG_ENTER_FUNCTION("HandleTable=0x%p; Handle=0x%p; NewHandle=0x%p", HandleTable, Handle, NewHandle);

	newMapping = (PCHANDLE_TABLE_MAPPING)HeapMemoryAlloc(HandleTable->PoolType, sizeof(CHANDLE_TABLE_MAPPING));
	if (newMapping != NULL) {
		PVOID object = NULL;

		status = HandleTablehandleTranslate(HandleTable, Handle, &object);
		if (NT_SUCCESS(status)) {
			newMapping->HandleTable = HandleTable;
			newMapping->Object = object;
			_HandleTableLockExclusive(HandleTable, &irql);
			newMapping->HandleValue = (HANDLE)InterlockedIncrement(&HandleTable->NextFreeHandle);
			HashTableInsert(HandleTable->HashTable, &newMapping->HashItem, newMapping->HandleValue);
			_HandleTableUnlock(HandleTable, irql);
			*NewHandle = newMapping->HandleValue;
		}

		if (!NT_SUCCESS(status))
			HeapMemoryFree(newMapping);
	} else status = STATUS_INSUFFICIENT_RESOURCES;

	DEBUG_EXIT_FUNCTION("0x%x, *NewHandle", status, *NewHandle);
	return status;
}
예제 #9
0
static return_val createLabelList( orl_sec_handle shnd )
{
    label_list          list;
    return_val          error;
    hash_entry_data     key_entry;

    list = MemAlloc( sizeof( label_list_struct ) );
    if( list != NULL ) {
        list->first = NULL;
        list->last = NULL;
        key_entry.key.u.sec_handle = shnd;
        key_entry.data.u.sec_label_list = list;
        error = HashTableInsert( HandleToLabelListTable, &key_entry );
        if( error == RC_OKAY ) {
            if( (Options & PRINT_PUBLICS) && shnd != ORL_NULL_HANDLE ) {
                error = addListToPublics( list );
                if( error != RC_OKAY ) {
                    MemFree( list );
                }
            }
        } else {
            MemFree( list );
        }
    } else {
        error = RC_OUT_OF_MEMORY;
    }
    return( error );
}
예제 #10
0
파일: scripting.c 프로젝트: leiradel/mgba
void mScriptBridgeInstallEngine(struct mScriptBridge* sb, struct mScriptEngine* se) {
	if (!se->init(se, sb)) {
		return;
	}
	const char* name = se->name(se);
	HashTableInsert(&sb->engines, name, se);
}
예제 #11
0
static void registerSegment( orl_sec_handle o_shnd )
//**************************************************
{
    orl_sec_flags               sec_flags;
    orl_sec_handle              reloc_section;
    orl_sec_alignment           alignment;
    char *                      content;
    int                         ctr;
    segment                     *seg;

    seg = NewSegment();
    seg->name = ORLSecGetName( o_shnd );
    seg->size = ORLSecGetSize( o_shnd );
    seg->start = 0;
    seg->use_32 = 1;            // only 32-bit object files use ORL
    seg->attr = ( 2 << 2 );     // (?) combine public
    alignment = ORLSecGetAlignment( o_shnd );
    // FIXME: Need better alignment translation.
    switch( alignment ) {
    case 0:
        seg->attr |= ( 1 << 5 ); break;
    case 1:
        seg->attr |= ( 2 << 5 ); break;
    case 3:
    case 4:
        seg->attr |= ( 3 << 5 ); break;
    case 8:
        seg->attr |= ( 4 << 5 ); break;
    case 2:
        seg->attr |= ( 5 << 5 ); break;
    case 12:
        seg->attr |= ( 6 << 5 ); break;
    default:
        // fprintf( stderr, "NOTE! 'Strange' alignment (%d) found. Using byte alignment.\n", alignment );
        seg->attr |= ( 1 << 5 ); break;
    }
    sec_flags = ORLSecGetFlags( o_shnd );
    if( !( sec_flags & ORL_SEC_FLAG_EXEC ) ) {
        seg->data_seg = true;
    }
    if( seg->size > 0 && ORLSecGetContents( o_shnd, &content ) == ORL_OKAY ) {
        Segment = seg;
        // Putting contents into segment struct.
        for( ctr = 0; ctr < seg->size; ctr++ ) {
            PutSegByte( ctr, content[ctr] );
        }
    }
    if( !HashTableInsert( SectionToSegmentTable, (hash_value)o_shnd, (hash_data)seg ) ) {
        SysError( ERR_OUT_OF_MEM, false );
    }
    reloc_section = ORLSecGetRelocTable( o_shnd );
    if( reloc_section ) {
        if( !addRelocSection( reloc_section ) ) {
            SysError( ERR_OUT_OF_MEM, false );
        }
    }
}
예제 #12
0
char *assign(char *name,char *value) {
  if (!symtab) shellinit();
  if (!value) {
    HashTableRemove(symtab,name);
  } else {
    HashTableInsert(symtab,name,value);
  }
  return value;
}
예제 #13
0
void RegisterValue( const char * name, enum ParamType t, void * ptr, int size )
{
	Init();

	struct Param * p = (struct Param*)HashGetEntry( parameters, name );

	if( p )
	{
		//Entry already exists.
		if( p->orphan )
		{
			if( p->t != PASTRING )
			{
				fprintf( stderr, "Warning: Orphan parameter %s was not a PSTRING.\n", name );
			}
			char * orig = p->lp->ptr;
			p->lp->ptr = ptr;
			p->t = t;
			p->size = size;
			p->orphan = 0;
			int r = SetParameter( p, orig );
			free( orig );
			if( r )
			{
				fprintf( stderr, "Warning: Problem when setting Orphan parameter %s\n", name );
			}
		}
		else
		{
			struct LinkedParameter * lp = p->lp;
			if( size != p->size )
			{
				fprintf( stderr, "Size mismatch: Parameter %s.\n", name );
			}
			else
			{
				p->lp = malloc( sizeof( struct LinkedParameter ) );
				p->lp->lp = lp;
				p->lp->ptr = ptr;
				memcpy( p->lp->ptr, p->lp->lp->ptr, size );
			}
		}
	}
	else
	{
		struct Param ** n = (struct Param**)HashTableInsert( parameters, name, 1 );
		*n = malloc( sizeof( struct Param ) );
		(*n)->t = t;
		(*n)->lp = malloc( sizeof( struct LinkedParameter ) );
		(*n)->lp->lp = 0;
		(*n)->lp->ptr = ptr;
		(*n)->orphan = 0;
		(*n)->size = size;
		(*n)->callback = 0;
	}
}
예제 #14
0
파일: configuration.c 프로젝트: ikeboy/mgba
void ConfigurationSetValue(struct Configuration* configuration, const char* section, const char* key, const char* value) {
	struct Table* currentSection = &configuration->root;
	if (section) {
		currentSection = HashTableLookup(&configuration->sections, section);
		if (!currentSection) {
			if (value) {
				currentSection = malloc(sizeof(*currentSection));
				HashTableInit(currentSection, 0, _sectionDeinit);
				HashTableInsert(&configuration->sections, section, currentSection);
			} else {
				return;
			}
		}
	}
	if (value) {
		HashTableInsert(currentSection, key, strdup(value));
	} else {
		HashTableRemove(currentSection, key);
	}
}
예제 #15
0
파일: hook.c 프로젝트: MartinDrab/IRPMon
static VOID _MakeDeviceHookRecordValid(PDEVICE_HOOK_RECORD DeviceRecord)
{
	KIRQL irql;
	DEBUG_ENTER_FUNCTION("DeviceRecord=0x%p", DeviceRecord);

	KeAcquireSpinLock(&_deviceValidationTableLock, &irql);
	HashTableInsert(_deviceValidationTable, &DeviceRecord->ValidationHashItem, DeviceRecord);
	KeReleaseSpinLock(&_deviceValidationTableLock, irql);

	DEBUG_EXIT_FUNCTION_VOID();
	return;
}
예제 #16
0
파일: hook.c 프로젝트: MartinDrab/IRPMon
NTSTATUS DriverHookRecordAddDevice(PDRIVER_HOOK_RECORD DriverRecord, PDEVICE_OBJECT DeviceObject, PUCHAR IRPSettings, PUCHAR FastIoSettings, BOOLEAN MonitoringEnabled, PDEVICE_HOOK_RECORD *DeviceRecord)
{
	KIRQL irql;
	PHASH_ITEM h = NULL;
	PDEVICE_HOOK_RECORD newDeviceRecord = NULL;
	NTSTATUS status = STATUS_UNSUCCESSFUL;
	DEBUG_ENTER_FUNCTION("Record=0x%p; DeviceObject=0x%p; IRPSettings=0x%p; FastIoSettings=0x%p; MonitoringEnabled=%u; DeviceRecord=0x%p", DriverRecord, DeviceObject, IRPSettings, FastIoSettings, MonitoringEnabled, DeviceRecord);
	
	status = _DeviceHookRecordCreate(DriverRecord, &newDeviceRecord, IRPSettings, FastIoSettings, MonitoringEnabled, edrcrUserRequest, DeviceObject);
	if (NT_SUCCESS(status)) {
		KeAcquireSpinLock(&DriverRecord->SelectedDevicesLock, &irql);
		h = HashTableGet(DriverRecord->SelectedDevices, DeviceObject);
		if (h == NULL) {
			// For the hash table
			DeviceHookRecordReference(newDeviceRecord);
			HashTableInsert(DriverRecord->SelectedDevices, &newDeviceRecord->HashItem, DeviceObject);
			KeReleaseSpinLock(&DriverRecord->SelectedDevicesLock, irql);
			_MakeDeviceHookRecordValid(newDeviceRecord);
			// For the reference going out of this routine
			DeviceHookRecordReference(newDeviceRecord);
			*DeviceRecord = newDeviceRecord;
		} else {
			PDEVICE_HOOK_RECORD existingDeviceRecord = NULL;

			existingDeviceRecord = CONTAINING_RECORD(h, DEVICE_HOOK_RECORD, HashItem);
			DeviceHookRecordReference(existingDeviceRecord);
			KeReleaseSpinLock(&DriverRecord->SelectedDevicesLock, irql);
			if (existingDeviceRecord->CreateReason == edrcrDriverHooked) {
				memset(existingDeviceRecord->IRPMonitorSettings, TRUE, (IRP_MJ_MAXIMUM_FUNCTION + 1)*sizeof(UCHAR));
				if (IRPSettings != NULL)
					memcpy(existingDeviceRecord->IRPMonitorSettings, IRPSettings, (IRP_MJ_MAXIMUM_FUNCTION + 1)*sizeof(UCHAR));

				memset(existingDeviceRecord->FastIoMonitorSettings, TRUE, FastIoMax*sizeof(UCHAR));
				if (FastIoSettings != NULL)
					memcpy(existingDeviceRecord->FastIoMonitorSettings, FastIoSettings,  FastIoMax*sizeof(UCHAR));

				existingDeviceRecord->CreateReason = edrcrUserRequest;
				existingDeviceRecord->MonitoringEnabled = MonitoringEnabled;
				_MakeDeviceHookRecordValid(existingDeviceRecord);
				DeviceHookRecordReference(existingDeviceRecord);
				*DeviceRecord = existingDeviceRecord;
				status = STATUS_SUCCESS;
			} else status = STATUS_ALREADY_REGISTERED;

			DeviceHookRecordDereference(existingDeviceRecord);
		}

		DeviceHookRecordDereference(newDeviceRecord);
	}

	DEBUG_EXIT_FUNCTION("0x%x, *DeviceRecord=0x%p", status, *DeviceRecord);
	return status;
}
예제 #17
0
파일: hook.c 프로젝트: MartinDrab/IRPMon
static VOID _MakeDriverHookRecordValid(PDRIVER_HOOK_RECORD DriverRecord)
{
	KIRQL irql;
	DEBUG_ENTER_FUNCTION("DriverRecord=0x%p", DriverRecord);

	KeAcquireSpinLock(&_driverValidationTableLock, &irql);
	ASSERT(HashTableGet(_driverValidationTable, DriverRecord) == NULL);
	HashTableInsert(_driverValidationTable, &DriverRecord->ValidationHashItem, DriverRecord);
	KeReleaseSpinLock(&_driverValidationTableLock, irql);

	DEBUG_EXIT_FUNCTION_VOID();
	return;
}
예제 #18
0
static return_val initHashTables( void )
{
    int         loop;
    return_val  error;

    error = createHashTables();
    if( error == OKAY ) {
        for( loop = 0; loop < NUM_ELTS( RecognizedName ); loop++ ) {
            HashTableInsert( NameRecognitionTable, (hash_value) RecognizedName[loop].name, RecognizedName[loop].type );
        }
    }
    return( error );
}
예제 #19
0
void DigestCacheInit(DigestCache* self, size_t heap_size, const char* filename)
{
  ReadWriteLockInit(&self->m_Lock);

  self->m_State = nullptr;
  self->m_StateFilename = filename;

  HeapInit(&self->m_Heap, heap_size, HeapFlags::kDefault);
  LinearAllocInit(&self->m_Allocator, &self->m_Heap, heap_size / 2, "digest allocator");
  MmapFileInit(&self->m_StateFile);
  HashTableInit(&self->m_Table, &self->m_Heap, HashTable::kFlagPathStrings);

  self->m_AccessTime = time(nullptr);

  MmapFileMap(&self->m_StateFile, filename);
  if (MmapFileValid(&self->m_StateFile))
  {
    const DigestCacheState* state = (const DigestCacheState*) self->m_StateFile.m_Address;
    if (DigestCacheState::MagicNumber == state->m_MagicNumber)
    {
      const uint64_t time_now = time(nullptr);

      // Throw out records that haven't been accessed in a week.
      const uint64_t cutoff_time = time_now - 7 * 24 * 60 * 60;

      self->m_State = state;

      //HashTablePrepareBulkInsert(&self->m_Table, state->m_Records.GetCount());

      for (const FrozenDigestRecord& record : state->m_Records)
      {
        if (record.m_AccessTime < cutoff_time)
          continue;

        DigestCacheRecord* r = LinearAllocate<DigestCacheRecord>(&self->m_Allocator);
        r->m_Hash          = record.m_FilenameHash;
        r->m_ContentDigest = record.m_ContentDigest;
        r->m_Next          = nullptr;
        r->m_String        = record.m_Filename.Get();
        r->m_Timestamp     = record.m_Timestamp;
        r->m_AccessTime    = record.m_AccessTime;
        HashTableInsert(&self->m_Table, r);
      }
      Log(kDebug, "digest cache initialized -- %d entries", state->m_Records.GetCount());
    }
    else
    {
      MmapFileUnmap(&self->m_StateFile);
    }
  }
}
예제 #20
0
static return_val initHashTables( void )
{
    int             i;
    return_val      error;
    hash_entry_data key_entry;

    error = createHashTables();
    if( error == RC_OKAY ) {
        for( i = 0; i < NUM_ELTS( RecognizedName ); i++ ) {
            key_entry.key.u.string = RecognizedName[i].name;
            key_entry.data.u.sec_type = RecognizedName[i].type;
            HashTableInsert( NameRecognitionTable, &key_entry );
        }
    }
    return( error );
}
예제 #21
0
void HashTableDoubleSize ( HashTable & _ht )
{
    int oldSize = _ht.m_tableSize;
    _ht.m_tableSize <<= 1;

    HashTable::Element* oldData = _ht.m_pData;
    _ht.m_pData = new HashTable::Element[ _ht.m_tableSize ];
    for ( int i = 0; i < _ht.m_tableSize; i++ )
        _ht.m_pData[ i ].m_status = HashTable::Element::NOT_OCCUPIED;
    _ht.m_numOccupied = 0;

    for ( int i = 0; i < oldSize; i++ )
        if (  oldData[ i ].m_status == HashTable::Element::OCCUPIED  )
            HashTableInsert( _ht, oldData[ i ].m_key, oldData[ i ].m_value );

    delete[] oldData;
}
예제 #22
0
static return_val createRefList( orl_sec_handle shnd )
{
    ref_list    list;
    return_val  error;

    list = MemAlloc( sizeof( ref_list_struct ) );
    if( list ) {
        list->first = NULL;
        list->last = NULL;
        error = HashTableInsert( HandleToRefListTable, (hash_value) shnd, (hash_data) list );
        if( error != OKAY ) {
            MemFree( list );
        }
    } else {
        error = OUT_OF_MEMORY;
    }
    return( error );
}
예제 #23
0
static return_val createRefList( orl_sec_handle shnd )
{
    ref_list        list;
    return_val      error;
    hash_entry_data key_entry;

    list = MemAlloc( sizeof( ref_list_struct ) );
    if( list != NULL ) {
        list->first = NULL;
        list->last = NULL;
        key_entry.key.u.sec_handle = shnd;
        key_entry.data.u.sec_ref_list = list;
        error = HashTableInsert( HandleToRefListTable, &key_entry );
        if( error != RC_OKAY ) {
            MemFree( list );
        }
    } else {
        error = RC_OUT_OF_MEMORY;
    }
    return( error );
}
예제 #24
0
파일: chash.c 프로젝트: BotBitz/colorchord
//Re-process a range; populated is the number of elements we expect to run into.
//If we removed some, it will be less length by that much.
//NOTE: This function doesn't range check diddily.
static void RedoHashRange( struct chash * hash, int start, int length, int populated )
{
	int i;
	int buckets = GeneralUsePrimes[hash->bucketCountPlace];
	struct chashentry * thisEntry = &hash->buckets[start];
	struct chashentry * overEntry = &hash->buckets[buckets];
	struct chashentry * copyEntry;

	struct chashlist * resort = alloca( sizeof( struct chashlist ) + sizeof( struct chashentry ) * (populated) );
	resort->length = populated;
	copyEntry = &resort->items[0];

	for( i = 0; i < length; i++ )
	{
		if( thisEntry->key )
		{
			copyEntry->key = thisEntry->key;
			copyEntry->value = thisEntry->value;
			copyEntry->hash = thisEntry->hash;
			copyEntry++;
			thisEntry->key = 0;
		}

		thisEntry++;
		if( thisEntry == overEntry ) thisEntry = &hash->buckets[0];
	}

	hash->entryCount -= populated;

	copyEntry = &resort->items[0];

	for( i = 0; i < populated; i++ )
	{
		*HashTableInsert( hash, copyEntry->key, 1 ) = copyEntry->value;
		copyEntry++;
	}

}
예제 #25
0
void CrawlPage(WebPage webpage){
	char* nexturl= NULL;
	int lastpos = 0;
	int depth = webpage.depth + 1;
	
	if(depth > maxWebPageDepth) return;
	
	printf("\n\n[crawler]: Crawling - %s\n\n",webpage.url);
	
	while((lastpos = GetNextURL(webpage.html, lastpos, webpage.url, &nexturl))>0){
		NormalizeURL(nexturl);
		if(!CheckURL(nexturl)){
			// setup new page
			struct WebPage* newwebpage = (WebPage*)calloc(1,sizeof(WebPage));
			newwebpage->url = (char*)calloc(strlen(nexturl)+1, sizeof(char));
			strcpy(newwebpage->url,nexturl);
			newwebpage->depth = depth;
			
			// get new webpage
    		if(GetWebPage(newwebpage)){
    			if(HashTableInsert(nexturl)){											 // If not found in hash table, add to hash table
    				printf("[crawler]: Parser found new link - %s\n",nexturl);
    				struct ListNode* listentry = (ListNode*)calloc(1,sizeof(ListNode));							
    				listentry->page = newwebpage;									     // then add to list
					WebPageList->tail = InsertNode(WebPageList->tail,listentry);
					
	   				WriteFile(*newwebpage, filenum++); 									 // then write file
    			} else{
    				CleanUpPage(newwebpage);
    			}
			}
		}
		free(nexturl);
		nexturl = NULL;
		// Sleep for a second 
		sleep(INTERVAL_PER_FETCH);
	}
}
/*
 * Return: 1-success, 0-failure
 * */
int ReadArpCacheAndShow(void)
{
	FILE* fp = NULL;
	char sLine[LINESIZE] = {0};
	char sIp[IPSIZE]  = {0};
	char sMac[MACSIZE] = {0};
	
	/* Open The Cache File */	
	fp = fopen(ARP_ENTRY_FILE, "r");
	if(NULL == fp)
	{
		perror("Open Error");
		return 0;
	}

	/* Read The Cache */
	do{
		bzero((void*)sLine, sizeof(sLine));
		if(fgets(sLine, LINESIZE, fp))
		{
			sscanf(sLine, "%s %*s %*s %s", sIp, sMac);
			if(strcmp(sIp, "IP"))
			{
				HashTableInsert(sIp, sMac);
			}
		}
	}while(strlen(sLine));

	/* Show The Cache */
	HashTablePrint();

	/* Close The Cache File */
	fclose(fp);
	fp = NULL;

	return 1;
}
예제 #27
0
BOOLEAN InitializeIpTable(LPCWSTR binary_file)
{
	HANDLE file;
	OBJECT_ATTRIBUTES attrib;
	UNICODE_STRING str;
	IO_STATUS_BLOCK block;
	unsigned int num = 0,ip = 0;
	LARGE_INTEGER offset = {0};
	unsigned int j = 0;
	initialized = FALSE;
	RtlInitUnicodeString(&str, binary_file);
	InitializeObjectAttributes(&attrib, &str, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,NULL,NULL);

	ZwCreateFile(&file, GENERIC_READ, &attrib, &block, NULL,
		FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OPEN,FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0);

	if(block.Status != STATUS_SUCCESS) {
		PrintLog("Cannot Read IP Table\n");
		return FALSE;
	}

	ZwReadFile(file,NULL,NULL,NULL,&block,&num,4,&offset,NULL);
	offset.QuadPart += 4;
	HashTableInit();

	for(j = 0; j < num; j++) {
		ZwReadFile(file,NULL,NULL,NULL,&block,&ip,4,&offset,NULL);
		offset.QuadPart += 4;
		HashTableInsert(ip);
	}

	ZwClose(file);
	KdPrint(("%d logs of IP Address loaded.\n",num));

	return TRUE;
}
예제 #28
0
static label_entry addLabel( label_list sec_label_list, label_entry entry, orl_symbol_handle sym_hnd )
{
    if( sec_label_list->first == NULL ) {
        sec_label_list->first = entry;
        sec_label_list->last = entry;
        entry->next = NULL;
    } else if( entry->offset > sec_label_list->last->offset ) {
        sec_label_list->last->next = entry;
        sec_label_list->last = entry;
        entry->next = NULL;
    } else if( entry->offset < sec_label_list->first->offset ) {
        entry->next = sec_label_list->first;
        sec_label_list->first = entry;
    } else {
        // fixme: this shouldn't happen too often
        // if it does, change to a skip list
        entry = insertLabelInMiddle( sec_label_list, entry );
    }
    // add entry to list
    if( sym_hnd != NULL ) {
        HashTableInsert( SymbolToLabelTable, (hash_value) sym_hnd, (hash_data) entry );
    }
    return( entry );
}
예제 #29
0
NTSTATUS HandleTableHandleCreate(PCHANDLE_TABLE HandleTable, PVOID Object, PHANDLE NewHandle)
{
	KIRQL irql;
	PCHANDLE_TABLE_MAPPING mapping = NULL;
	NTSTATUS status = STATUS_UNSUCCESSFUL;
	DEBUG_ENTER_FUNCTION("HandleTable=0x%p; Object=0x%p; NewHandle=0x%p", HandleTable, Object, NewHandle);

	mapping = (PCHANDLE_TABLE_MAPPING)HeapMemoryAlloc(HandleTable->PoolType, sizeof(CHANDLE_TABLE_MAPPING));
	if (mapping != NULL) {
		mapping->HandleTable = HandleTable;
		mapping->HandleValue = (HANDLE)InterlockedIncrement(&HandleTable->NextFreeHandle);
		mapping->Object = Object;
		HandleTable->HandleCreateProcedure(mapping->HandleTable, mapping->Object, mapping->HandleValue);
		_HandleTableLockExclusive(HandleTable, &irql);
		HashTableInsert(HandleTable->HashTable, &mapping->HashItem, mapping->HandleValue);
		_HandleTableUnlock(HandleTable, irql);

		*NewHandle = mapping->HandleValue;
		status = STATUS_SUCCESS;
	} else status = STATUS_INSUFFICIENT_RESOURCES;

	DEBUG_EXIT_FUNCTION("0x%x, *NewHandle=0x%p", status, *NewHandle);
	return status;
}
예제 #30
0
return_val Init( void )
{
    return_val          error;
    const char *        const *list;
    const char          *name;
    hash_entry_data     key_entry;

    error = RC_OKAY;

    OutputDest = STDOUT_FILENO;
    ChangePrintDest( OutputDest );

    relocSections.first = NULL;
    relocSections.last = NULL;
    if( !MsgInit() ) {
        // MsgInit does its own error message printing
        return( RC_ERROR );
    }
    MemOpen();

    error = HandleArgs();
    if( error != RC_OKAY ) {
        return( error );
    }

    openFiles();
    initGlobals();
    error = initHashTables();
    if( error != RC_OKAY ) {
        PrintErrorMsg( error, WHERE_INIT_HASH_TABLES );
        return( error );
    }
    error = initServicesUsed();
    if( error != RC_OKAY ) {
        // initServicesUsed does its own error message printing
        return( error );
    }
    error = initSectionTables();
    if( error != RC_OKAY ) {
        PrintErrorMsg( error, WHERE_CREATE_SEC_TABLES );
        return( error );
    }
    if( Options & PRINT_PUBLICS ) {
        CreatePublicsArray();
    }
    if( IsMasmOutput() ) {
        CommentString = MASM_COMMENT_STRING;
    }
    if( IsIntelx86() ) {
        SkipRefTable = HashTableCreate( RECOGNITION_TABLE_SIZE, HASH_STRING_IGNORECASE );
        if( SkipRefTable != NULL ) {
            for( list = intelSkipRefList; (name = *list) != NULL; ++list ) {
                key_entry.key.u.string = name;
                key_entry.data.u.string = *list;
                error = HashTableInsert( SkipRefTable, &key_entry );
                if( error != RC_OKAY ) {
                    break;
                }
            }
        }
    }
    if( LabelChar == 0 ) {
        if( IsMasmOutput() ) {
            LabelChar = 'L';
        } else {
            LabelChar = 'X';
        }
    }
    return( error );
}