예제 #1
0
void
BenchmarkPlayback::InputExhausted()
{
  MOZ_ASSERT(OnThread());
  if (mFinished || mSampleIndex >= mSamples.Length()) {
    return;
  }
  RefPtr<Benchmark> ref(mMainThreadState);
  mDecoder->Decode(mSamples[mSampleIndex])
    ->Then(Thread(), __func__,
           [ref, this](const MediaDataDecoder::DecodedData& aResults) {
             Output(aResults);
             InputExhausted();
           },
           [ref, this](const MediaResult& aError) { MainThreadShutdown(); });
  mSampleIndex++;
  if (mSampleIndex == mSamples.Length()) {
    if (ref->mParameters.mStopAtFrame) {
      mSampleIndex = 0;
    } else {
      mDecoder->Drain()->Then(
        Thread(), __func__,
        [ref, this](const MediaDataDecoder::DecodedData& aResults) {
          mDrained = true;
          Output(aResults);
        },
        [ref, this](const MediaResult& aError) { MainThreadShutdown(); });
    }
  }
}
예제 #2
0
void image_info::adjustThreads()
{
    int new_threads = nr_threads - threads.size();

    if (new_threads == 0)
    {
        return;
    }
    else if (new_threads > 0)
    {
        for (int i = 0; i < new_threads; i++)
        {
            // FIXME: avoid leaking the memory for RenderThread
            threads.push_back(Thread(new RenderThread(this)));
        }
    }
    else
    {
        // this is inefficient but we don't know which threads are going to
        // pick up the quit notices, so we don't know which threads we
        // should call join on, so just delete all of them and create
        // the new number of threads.

        stopThreads();
        adjustThreads();
    }
}
예제 #3
0
void
BenchmarkPlayback::MainThreadShutdown()
{
  MOZ_ASSERT(OnThread());

  if (mDecoder) {
    mDecoder->Flush();
    mDecoder->Shutdown();
    mDecoder = nullptr;
  }

  mDecoderTaskQueue->BeginShutdown();
  mDecoderTaskQueue->AwaitShutdownAndIdle();
  mDecoderTaskQueue = nullptr;

  if (mTrackDemuxer) {
    mTrackDemuxer->Reset();
    mTrackDemuxer->BreakCycles();
    mTrackDemuxer = nullptr;
  }

  RefPtr<Benchmark> ref(mMainThreadState);
  Thread()->AsTaskQueue()->BeginShutdown()->Then(
    ref->Thread(), __func__,
    [ref]() {  ref->Dispose(); },
    []() { MOZ_CRASH("not reached"); });
}
예제 #4
0
void
BenchmarkPlayback::DemuxNextSample()
{
  MOZ_ASSERT(OnThread());

  RefPtr<Benchmark> ref(mMainThreadState);
  RefPtr<MediaTrackDemuxer::SamplesPromise> promise = mTrackDemuxer->GetSamples();
  promise->Then(
    Thread(), __func__,
    [this, ref](RefPtr<MediaTrackDemuxer::SamplesHolder> aHolder) {
      mSamples.AppendElements(Move(aHolder->mSamples));
      if (ref->mParameters.mStopAtFrame &&
          mSamples.Length() == (size_t)ref->mParameters.mStopAtFrame.ref()) {
        InitDecoder(Move(*mTrackDemuxer->GetInfo()));
      } else {
        Dispatch(NS_NewRunnableFunction([this, ref]() { DemuxNextSample(); }));
      }
    },
    [this, ref](DemuxerFailureReason aReason) {
      switch (aReason) {
        case DemuxerFailureReason::END_OF_STREAM:
          InitDecoder(Move(*mTrackDemuxer->GetInfo()));
          break;
        default:
          MainThreadShutdown();
      }
    });
}
예제 #5
0
void CPacketQueue::Init()
{
	gEnv->pLog->Log(TITLE "CPacketQueue::Init()");

	std::thread Thread(&CPacketQueue::Thread, this);
	Thread.detach();
}
예제 #6
0
/** This test case checks that the CCheckQueue works properly
 * with each specified size_t Checks pushed.
 */
static void Correct_Queue_range(std::vector<size_t> range)
{
    auto small_queue = std::unique_ptr<Correct_Queue>(new Correct_Queue {QUEUE_BATCH_SIZE});
    boost::thread_group tg;
    for (auto x = 0; x < nScriptCheckThreads; ++x) {
       tg.create_thread([&]{small_queue->Thread();});
    }
    // Make vChecks here to save on malloc (this test can be slow...)
    std::vector<FakeCheckCheckCompletion> vChecks;
    for (auto i : range) {
        size_t total = i;
        FakeCheckCheckCompletion::n_calls = 0;
        CCheckQueueControl<FakeCheckCheckCompletion> control(small_queue.get());
        while (total) {
            vChecks.resize(std::min(total, (size_t) InsecureRandRange(10)));
            total -= vChecks.size();
            control.Add(vChecks);
        }
        BOOST_REQUIRE(control.Wait());
        if (FakeCheckCheckCompletion::n_calls != i) {
            BOOST_REQUIRE_EQUAL(FakeCheckCheckCompletion::n_calls, i);
            BOOST_TEST_MESSAGE("Failure on trial " << i << " expected, got " << FakeCheckCheckCompletion::n_calls);
        }
    }
    tg.interrupt_all();
    tg.join_all();
}
예제 #7
0
int _tmain(int argc, _TCHAR* argv[])
{
	UNREFERENCED_PARAMETER(argc);
	UNREFERENCED_PARAMETER(argv);
    
	try
	{
		AC::Semaphore Tickets(NUM_TICKETS, NUM_TICKETS);
		std::vector<AC::Thread> Threads;
		for (unsigned short i = 0; i < NUM_SELLERS; i++)
		{
			AC::Thread Thread(new Seller(Tickets, i+1));
			Thread.Start();
			Threads.push_back(Thread);
		}
		for (unsigned short i = 0; i < Threads.size(); i++)
			Threads[i].Wait();
	}
	catch(std::exception& ex)
	{
		fprintf(stderr, "Exception: %s\n", ex.what());
	}

	return 0;
}
예제 #8
0
파일: vm.cpp 프로젝트: queer1/liblightgrep
void Vm::startsWith(const byte* const beg, const byte* const end, const uint64_t startOffset, HitCallback hitFn, void* userData) {
  CurHitFn = hitFn;
  UserData = userData;
  const Instruction* base = &(*Prog)[0];
  uint64_t offset = startOffset;

  if (Prog->First[*beg]) {
    for (ThreadList::const_iterator t(First.begin()); t != First.end(); ++t) {
      Active.emplace_back(
      #ifdef _MSC_VER
        Thread(t->PC, Thread::NOLABEL, offset, Thread::NONE)
      #else
        t->PC, Thread::NOLABEL, offset, Thread::NONE
      #endif
      );
    }

    for (const byte* cur = beg; cur < end; ++cur, ++offset) {
      for (ThreadList::iterator t(Active.begin()); t != Active.end(); ++t) {
        _executeThread(base, t, cur, offset);
      }

      _cleanup();

      if (Active.empty()) {
        // early exit if threads die out
        break;
      }
    }
  }

  closeOut(hitFn, userData);
  reset();
}
예제 #9
0
/// <summary>
/// Create the thread.
/// </summary>
/// <param name="threadProc">Thread enty point</param>
/// <param name="arg">Thread argument.</param>
/// <param name="flags">Thread creation flags</param>
/// <returns>New thread object</returns>
Thread ProcessThreads::CreateNew( ptr_t threadProc, ptr_t arg, DWORD flags /*= 0*/ )
{
    HANDLE hThd = NULL;
    _core.native()->CreateRemoteThreadT( hThd, threadProc, arg, flags );

    return Thread( hThd, &_core );
}
예제 #10
0
/// <summary>
/// Gets all process threads
/// </summary>
/// <param name="dontUpdate">Return already existing thread list</param>
/// <returns>Threads collection</returns>
std::vector<Thread>& ProcessThreads::getAll( bool dontUpdate /*= false*/ )
{
    if (dontUpdate)
        return _threads;

    HANDLE hThreadSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 );

    _threads.clear();

    if (hThreadSnapshot != INVALID_HANDLE_VALUE)
    {
        THREADENTRY32 tEntry = { 0 };
        tEntry.dwSize = sizeof(THREADENTRY32);

        // Iterate threads
        for (BOOL success = Thread32First( hThreadSnapshot, &tEntry ); 
              success == TRUE;
              success = Thread32Next( hThreadSnapshot, &tEntry ))
        {
            if (tEntry.th32OwnerProcessID != _core.pid())
                continue;

            _threads.emplace_back( Thread( tEntry.th32ThreadID, &_core ) );
        }

        CloseHandle( hThreadSnapshot );
    }

    return _threads;
}
예제 #11
0
BOOL WINAPI CtrlHandler(DWORD CtrlType)
{
	switch(CtrlType)
	{
	case CTRL_C_EVENT:
		return TRUE;

	case CTRL_BREAK_EVENT:
		if(!CancelIoInProgress().Signaled())
		{
			CancelIoInProgress().Set();
			Thread(&Thread::detach, &CancelSynchronousIoWrapper, Global->MainThreadHandle());
		}
		WriteInput(KEY_BREAK);

		if (Global->CtrlObject && Global->CtrlObject->Cp())
		{
			if (Global->CtrlObject->Cp()->LeftPanel && Global->CtrlObject->Cp()->LeftPanel->GetMode()==PLUGIN_PANEL)
				Global->CtrlObject->Plugins->ProcessEvent(Global->CtrlObject->Cp()->LeftPanel->GetPluginHandle(),FE_BREAK, ToPtr(CtrlType));

			if (Global->CtrlObject->Cp()->RightPanel && Global->CtrlObject->Cp()->RightPanel->GetMode()==PLUGIN_PANEL)
				Global->CtrlObject->Plugins->ProcessEvent(Global->CtrlObject->Cp()->RightPanel->GetPluginHandle(),FE_BREAK, ToPtr(CtrlType));
		}
		return TRUE;

	case CTRL_CLOSE_EVENT:
		Global->CloseFAR=TRUE;
		Global->AllowCancelExit=FALSE;

		// trick to let wmain() finish correctly
		ExitThread(1);
		//return TRUE;
	}
	return FALSE;
}
예제 #12
0
int _tmain(int argc, _TCHAR* argv[])
{
	UNREFERENCED_PARAMETER(argc);
	UNREFERENCED_PARAMETER(argv);

	try
	{
		AC::Event Event(FALSE, TRUE);
		std::vector<AC::Thread> Threads;
		for (unsigned short i = 1; i <= NUM_THREADS; i++)
		{
			AC::Thread Thread(new TaskPrint(Event, i));
			Thread.Start();
			Threads.push_back(Thread);
		}
		Sleep(DELAY_MS);
		Event.SetEvent();
		for (unsigned short i = 0; i < Threads.size(); i++)
			Threads[i].Wait();
	}
	catch(std::exception& ex)
	{
		fprintf(stderr, "Exception: %s\n", ex.what());
	}

	return 0;
}
tAsyncCall* System_Threading_Thread_ctorParam(PTR pThis_, PTR pParams, PTR pReturnValue) {
	tThread *pThread = Thread();
	pThread->startDelegate = ((PTR*)pParams)[0];
	*(HEAP_PTR*)pReturnValue = (HEAP_PTR)pThread;
	pThread->hasParam = 1;
	return NULL;
}
예제 #14
0
	ThreadList Thread::GetList(UInt32 processId)
	{
		Handle hSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, processId);
		if (!hSnapshot.IsValid())
		{
			THROW_LAST_ERROR_EXCEPTION();
		}

		THREADENTRY32 threadEntry = {0};
		threadEntry.dwSize = sizeof(threadEntry);

		BOOL success = ::Thread32First(hSnapshot, &threadEntry);
		if (!success)
		{
			THROW_LAST_ERROR_EXCEPTION();
		}

		ThreadList list;
		while (success)
		{
			if (threadEntry.th32OwnerProcessID == processId)
			{
				list.push_back(Thread(threadEntry.th32ThreadID));
			}
			success = ::Thread32Next(hSnapshot, &threadEntry);
		}

		return list;
	}
예제 #15
0
int _tmain(int argc, _TCHAR* argv[])
{
	UNREFERENCED_PARAMETER(argc);
	UNREFERENCED_PARAMETER(argv);

	srand((unsigned int)time(NULL));

	try
	{
		AC::SharedQueue<Pair> InputQueue(NUM_POLYNOMIALS), OutputQueue(NUM_POLYNOMIALS);
		AC::Thread Thread(new MathTask(InputQueue, OutputQueue));
		Thread.Start();
		
		for (unsigned short i = 0; i < NUM_POLYNOMIALS; i++)
		{
			Pair p;
			p.first = rand();
			InputQueue.Push(p);
		}
		for (unsigned short i = 0; i < NUM_POLYNOMIALS; i++)
		{
			Pair p = OutputQueue.Pop();
			printf( "El valor del polinomio para x=%f es y=%f\n", p.first, p.second);
		}		

		Thread.Wait();
	}
	catch(std::exception& ex)
	{
		fprintf(stderr, "Exception: %s\n", ex.what());
	}
	
	return 0;
}
예제 #16
0
void BenchmarkPlayback::DemuxNextSample() {
  MOZ_ASSERT(OnThread());

  RefPtr<Benchmark> ref(mGlobalState);
  RefPtr<MediaTrackDemuxer::SamplesPromise> promise =
      mTrackDemuxer->GetSamples();
  promise->Then(
      Thread(), __func__,
      [this, ref](RefPtr<MediaTrackDemuxer::SamplesHolder> aHolder) {
        mSamples.AppendElements(std::move(aHolder->mSamples));
        if (ref->mParameters.mStopAtFrame &&
            mSamples.Length() == ref->mParameters.mStopAtFrame.ref()) {
          InitDecoder(std::move(*mTrackDemuxer->GetInfo()));
        } else {
          Dispatch(
              NS_NewRunnableFunction("BenchmarkPlayback::DemuxNextSample",
                                     [this, ref]() { DemuxNextSample(); }));
        }
      },
      [this, ref](const MediaResult& aError) {
        switch (aError.Code()) {
          case NS_ERROR_DOM_MEDIA_END_OF_STREAM:
            InitDecoder(std::move(*mTrackDemuxer->GetInfo()));
            break;
          default:
            Error(aError);
            break;
        }
      });
}
예제 #17
0
	void Music::Play()
	{
		#if NAZARA_AUDIO_SAFE
		if (!m_impl)
		{
			NazaraError("Music not created");
			return;
		}
		#endif

		// Maybe we are already playing
		if (m_impl->streaming)
		{
			switch (GetStatus())
			{
				case SoundStatus_Playing:
					SetPlayingOffset(0);
					break;

				case SoundStatus_Paused:
					alSourcePlay(m_source);
					break;

				default:
					break; // We shouldn't be stopped
			}
		}
		else
		{
			// Starting streaming's thread
			m_impl->streaming = true;
			m_impl->thread = Thread(&Music::MusicThread, this);
		}
	}
예제 #18
0
void LauncherApp::ReadyToRun()
{
	// Since we will essentially run the GUI...
	set_thread_priority(Thread(), B_DISPLAY_PRIORITY);

    BWebPage::InitializeOnce();
    BWebPage::SetCacheModel(B_WEBKIT_CACHE_MODEL_WEB_BROWSER);

	BFile settingsFile;
	BRect windowFrameFromSettings = m_lastWindowFrame;
	if (openSettingsFile(settingsFile, B_READ_ONLY)) {
		BMessage settingsArchive;
		settingsArchive.Unflatten(&settingsFile);
		settingsArchive.FindRect("window frame", &windowFrameFromSettings);
	}
	m_lastWindowFrame = windowFrameFromSettings;

	m_initialized = true;

	if (m_launchRefsMessage) {
		RefsReceived(m_launchRefsMessage);
		delete m_launchRefsMessage;
		m_launchRefsMessage = 0;
	} else {
	    LauncherWindow* window = new LauncherWindow(m_lastWindowFrame);
	    window->Show();
	}
}
예제 #19
0
	/*!
	* \brief Plays the music
	*
	* Plays/Resume the music.
	* If the music is currently playing, resets the playing offset to the beginning offset.
	* If the music is currently paused,  resumes the playing.
	* If the music is currently stopped, starts the playing at the previously set playing offset.
	*
	* \remark Music must be valid when calling this function
	*/
	void Music::Play()
	{
		NazaraAssert(m_impl, "Music not created");

		// Maybe we are already playing
		if (m_impl->streaming)
		{
			switch (GetStatus())
			{
				case SoundStatus_Playing:
					SetPlayingOffset(0);
					break;

				case SoundStatus_Paused:
					alSourcePlay(m_source);
					break;

				default:
					break; // We shouldn't be stopped
			}
		}
		else
		{
			// Starting streaming's thread
			m_impl->streaming = true;
			m_impl->thread = Thread(&Music::MusicThread, this);
		}
	}
예제 #20
0
파일: Program.cpp 프로젝트: ozzi/webzavod1
Program::Program(const Params & aParams)
	: input(aParams.GetUrl()),
	  output(aParams.GetOutput().empty() ? input.GetFileName() : aParams.GetOutput(), input.GetFileSize()),
	  threadsNumber(input.AcceptRanges() ? aParams.GetThreadsCount() : 1),
	  barrier(threadsNumber, aParams.GetRefresh()),
	  threads(threadsNumber, Thread(input.GetAddress(), &output, &barrier))
{}
예제 #21
0
int main(int argc, char **argv)
{
   int i, retval;
   long long elapsed_us, elapsed_cyc;

   tests_quiet(argc, argv);     /* Set TESTS_QUIET variable */

   retval = PAPI_library_init(PAPI_VER_CURRENT);
   if (retval != PAPI_VER_CURRENT)
      test_fail(__FILE__, __LINE__, "PAPI_library_init", retval);

   hw_info = PAPI_get_hardware_info();
   if (hw_info == NULL)
     test_fail(__FILE__, __LINE__, "PAPI_get_hardware_info", 2);

   elapsed_us = PAPI_get_real_usec();

   elapsed_cyc = PAPI_get_real_cyc();

#if defined(_AIX)
   retval = PAPI_thread_init((unsigned long (*)(void)) (pthread_self));
   if (retval != PAPI_OK) {
      if (retval == PAPI_ESBSTR)
         test_skip(__FILE__, __LINE__, "PAPI_thread_init", retval);
      else
         test_fail(__FILE__, __LINE__, "PAPI_thread_init", retval);
   }
#pragma ibm parallel_loop
#elif defined(sgi) && defined(mips)
   retval = PAPI_thread_init((unsigned long (*)(void)) (mp_my_threadnum));
   if (retval != PAPI_OK) {
      test_fail(__FILE__, __LINE__, "PAPI_thread_init", retval);
   }
#pragma parallel
#pragma local(i)
#pragma pfor
#elif defined(sun) && defined(sparc)
   retval = PAPI_thread_init((unsigned long (*)(void)) (thr_self));
   if (retval != PAPI_OK) {
      test_fail(__FILE__, __LINE__, "PAPI_thread_init", retval);
   }
#pragma MP taskloop private(i)
#else
#error "Architecture not included in this test file yet."
#endif
   for (i = 1; i < 3; i++)
      Thread(i, 10000000 * i);

   elapsed_cyc = PAPI_get_real_cyc() - elapsed_cyc;

   elapsed_us = PAPI_get_real_usec() - elapsed_us;

   if (!TESTS_QUIET) {
      printf("Master real usec   : \t%lld\n", elapsed_us);
      printf("Master real cycles : \t%lld\n", elapsed_cyc);
   }
   test_pass(__FILE__, NULL, 0);
   exit(1);
}
예제 #22
0
파일: vm.cpp 프로젝트: queer1/liblightgrep
inline void Vm::_executeFrame(const ByteSet& first, ThreadList::iterator t, const Instruction* const base, const byte* const cur, const uint64_t offset) {
  // run old threads at this offset
  // uint32_t count = 0;

  while (t != Active.end()) {
    _executeThread(base, t, cur, offset);
    ++t;
    // ++count;
  }

  // create new threads at this offset
  if (first[*cur]) {
    const size_t oldsize = Active.size();

    for (t = First.begin(); t != First.end(); ++t) {
      #ifdef LBT_TRACE_ENABLED
      Active.emplace_back(
        #ifdef _MSC_VER
        Thread(t->PC, Thread::NOLABEL, NextId++, offset, Thread::NONE)
        #else
        t->PC, Thread::NOLABEL, NextId++, offset, Thread::NONE
        #endif
      );
      #else
      Active.emplace_back(
        #ifdef _MSC_VER
        Thread(t->PC, Thread::NOLABEL, offset, Thread::NONE)
        #else
        t->PC, Thread::NOLABEL, offset, Thread::NONE
        #endif
      );
      #endif

      #ifdef LBT_TRACE_ENABLED
      new_thread_json.insert(Active.back().Id);
      #endif
    }

    for (t = Active.begin() + oldsize; t != Active.end(); ++t) {
      _executeThread(base, t, cur, offset);
      // ++count;
    }
  }
  // ThreadCountHist.resize(count + 1, 0);
  // ++ThreadCountHist[count];
}
예제 #23
0
void BenchmarkPlayback::InputExhausted() {
  MOZ_ASSERT(OnThread());
  MOZ_ASSERT(!mFinished);

  if (mSampleIndex >= mSamples.Length()) {
    Error(MediaResult(NS_ERROR_FAILURE, "Nothing left to decode"));
    return;
  }

  RefPtr<MediaRawData> sample = mSamples[mSampleIndex];
  RefPtr<Benchmark> ref(mGlobalState);
  RefPtr<MediaDataDecoder::DecodePromise> p = mDecoder->Decode(sample);

  mSampleIndex++;
  if (mSampleIndex == mSamples.Length() && !ref->mParameters.mStopAtFrame) {
    // Complete current frame decode then drain if still necessary.
    p->Then(Thread(), __func__,
            [ref, this](MediaDataDecoder::DecodedData&& aResults) {
              Output(std::move(aResults));
              if (!mFinished) {
                mDecoder->Drain()->Then(
                    Thread(), __func__,
                    [ref, this](MediaDataDecoder::DecodedData&& aResults) {
                      mDrained = true;
                      Output(std::move(aResults));
                      MOZ_ASSERT(mFinished, "We must be done now");
                    },
                    [ref, this](const MediaResult& aError) { Error(aError); });
              }
            },
            [ref, this](const MediaResult& aError) { Error(aError); });
  } else {
    if (mSampleIndex == mSamples.Length() && ref->mParameters.mStopAtFrame) {
      mSampleIndex = 0;
    }
    // Continue decoding
    p->Then(Thread(), __func__,
            [ref, this](MediaDataDecoder::DecodedData&& aResults) {
              Output(std::move(aResults));
              if (!mFinished) {
                InputExhausted();
              }
            },
            [ref, this](const MediaResult& aError) { Error(aError); });
  }
}
예제 #24
0
void ThreadPool::Start(void * (*Routine)(void * argv), ThreadPoolServer* tps)
{
	for(int i = 0; i < capacity; ++i)
	{
		pool.push_back(Thread(i, Routine));
		pool.back().Run(tps);
	}
}
예제 #25
0
void wm_listener::Check()
{
	if (!m_Thread.joinable() || m_Thread.Signaled())
	{
		Event ReadyEvent(Event::automatic, Event::nonsignaled);
		m_Thread = Thread(&Thread::join, &wm_listener::WindowThreadRoutine, this, &ReadyEvent);
		ReadyEvent.Wait();
	}
}
예제 #26
0
RefPtr<Benchmark::BenchmarkPromise> Benchmark::Run() {
  RefPtr<Benchmark> self = this;
  return InvokeAsync(Thread(), __func__, [self] {
    RefPtr<BenchmarkPromise> p = self->mPromise.Ensure(__func__);
    self->mPlaybackState.Dispatch(NS_NewRunnableFunction(
        "Benchmark::Run", [self]() { self->mPlaybackState.DemuxSamples(); }));
    return p;
  });
}
PyrideRemoteDataHandler::PyrideRemoteDataHandler(void) :
  robotID_( -1 )
{
  ConsoleDataProcessor::instance()->init( this );

  Thread ^ dataThread = gcnew Thread( gcnew ThreadStart( &PyrideRemoteDataHandler::DataThreadProc ) );
  dataThread->IsBackground = true;
  dataThread->Start();
}
예제 #28
0
Benchmark::Benchmark(MediaDataDemuxer* aDemuxer, const Parameters& aParameters)
  : QueueObject(AbstractThread::GetCurrent())
  , mParameters(aParameters)
  , mKeepAliveUntilComplete(this)
  , mPlaybackState(this, aDemuxer)
{
  MOZ_COUNT_CTOR(Benchmark);
  MOZ_ASSERT(Thread(), "Must be run in task queue");
}
예제 #29
0
// Ejects a module (fully qualified path) via process id
void Injector::EjectLib(DWORD ProcID, const std::wstring& Path)
{
	// Grab a new snapshot of the process
	EnsureCloseHandle Snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, ProcID));
	if (Snapshot == INVALID_HANDLE_VALUE)
		throw std::runtime_error("Could not get module snapshot for remote process.");;

	// Get the HMODULE of the desired library
	MODULEENTRY32W ModEntry = { sizeof(ModEntry) };
	bool Found = false;
	BOOL bMoreMods = Module32FirstW(Snapshot, &ModEntry);
	for (; bMoreMods; bMoreMods = Module32NextW(Snapshot, &ModEntry)) 
	{
		std::wstring ModuleName(ModEntry.szModule);
		std::wstring ExePath(ModEntry.szExePath);
		Found = (ModuleName == Path || ExePath == Path);
		if (Found) break;
	}
	if (!Found)
		throw std::runtime_error("Could not find module in remote process.");;

	// Get a handle for the target process.
	EnsureCloseHandle Process(OpenProcess(
		PROCESS_QUERY_INFORMATION |   
		PROCESS_CREATE_THREAD     | 
		PROCESS_VM_OPERATION,  // For CreateRemoteThread
		FALSE, ProcID));
	if (!Process) 
		throw std::runtime_error("Could not get handle to process.");

	// Get the real address of LoadLibraryW in Kernel32.dll
	HMODULE hKernel32 = GetModuleHandle(TEXT("Kernel32"));
	if (hKernel32 == NULL) 
		throw std::runtime_error("Could not get handle to Kernel32.");
	PTHREAD_START_ROUTINE pfnThreadRtn = (PTHREAD_START_ROUTINE)
		GetProcAddress(hKernel32, "FreeLibrary");
	if (pfnThreadRtn == NULL) 
		throw std::runtime_error("Could not get pointer to FreeLibrary.");

	// Create a remote thread that calls FreeLibrary()
	EnsureCloseHandle Thread(CreateRemoteThread(Process, NULL, 0, 
		pfnThreadRtn, ModEntry.modBaseAddr, 0, NULL));
	if (!Thread) 
		throw std::runtime_error("Could not create thread in remote process.");

	// Wait for the remote thread to terminate
	WaitForSingleObject(Thread, INFINITE);

	// Get thread exit code
	DWORD ExitCode;
	if (!GetExitCodeThread(Thread,&ExitCode))
		throw std::runtime_error("Could not get thread exit code.");

	// Check LoadLibrary succeeded and returned a module base
	if(!ExitCode)
		throw std::runtime_error("Call to FreeLibrary in remote process failed.");
}
예제 #30
0
void HiloControl::iniciarHilo()
{
	hilo = gcnew Thread(gcnew ThreadStart(this, &HiloControl::metodoHilo));
	hilo->Start();

	/*while (!myThread->IsAlive);   // wait for the thread to start
	Thread::Sleep(100);
	*/
}