Ejemplo n.º 1
0
int main()
{
    time_t t;
    srand((unsigned) time(&t));
    commandLine();
    return 0;
}
Ejemplo n.º 2
0
int main(int argumentCount, const CHAR** arguments)
{
    CommandLine commandLine(argumentCount, arguments);
    
    BOOL continueLoop = !Tp2Constants::SKIP_DATA_INPUT;
    do
    {
        Vector4d initialLinearVelocity  = Tp2Constants::INITIAL_LINEAR_VELOCITY;
        Vector4d initialAngularVelocity = Tp2Constants::INITIAL_ANGULAR_VELOCITY;

        if ( !Tp2Constants::SKIP_DATA_INPUT )
        {
            BOOL breakLoop = promptData(initialLinearVelocity, initialAngularVelocity);
            if ( breakLoop )
                return 0;
        }
        
        cout << endl << "Fermer la fenetre pour recommencer pour revenir a la console" << endl << endl;

        ApplicationManager::get()->startApplication(new Tp2Simulation(&commandLine, 
                                                                      initialLinearVelocity, 
                                                                      initialAngularVelocity));

        // Les resultat sont afficher dans la simulation directement
        ApplicationManager::destroy();

    } while( continueLoop );

    // Will never get to this point
    return 0;
}
Ejemplo n.º 3
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QTime t;
    t.start();

    Log::Write(LOG_TYPE_NORMAL, "     _                               ");
    Log::Write(LOG_TYPE_NORMAL, "    | |   /\\                         ");
    Log::Write(LOG_TYPE_NORMAL, "  __| |  /  \\   _ __ ___ _ __   __ _ ");
    Log::Write(LOG_TYPE_NORMAL, " / _` | / /\\ \\ | '__/ _ \\ '_ \\ / _` |");
    Log::Write(LOG_TYPE_NORMAL, "| (_| |/ ____ \\| | |  __/ | | | (_| |      Dofus Arena Emulator");
    Log::Write(LOG_TYPE_NORMAL, " \\__,_/_/    \\_\\_|  \\___|_| |_|\\__,_|           by Sgt Fatality");
    Log::Write(LOG_TYPE_NORMAL, " ==============================================================");
    Log::Write(LOG_TYPE_NORMAL, "");

    if (!WorldServer::Instance()->Initialize())
        return close();

    Log::Write(LOG_TYPE_NORMAL, "Press ctrl + c to quit.");
    Log::Write(LOG_TYPE_NORMAL, "dArena started in %s sec.", QString::number(t.elapsed() / IN_MILLISECONDS).toLatin1().data());

    Chat::Instance();
    CommandLine commandLine(&a);
    commandLine.start();

    signal(SIGINT, &stop);
    signal(SIGTERM, &stop);
    #ifdef Q_OS_UNIX
        signal(SIGHUP, &stop);
    #elif defined(Q_OS_WIN)
        signal(SIGBREAK, &stop);
    #endif
    return a.exec();
}
Ejemplo n.º 4
0
void ProcessLauncher::launchProcess()
{
    // First, create the server and client identifiers.
    HANDLE serverIdentifier, clientIdentifier;
    if (!CoreIPC::Connection::createServerAndClientIdentifiers(serverIdentifier, clientIdentifier)) {
        // FIXME: What should we do here?
        ASSERT_NOT_REACHED();
    }

    // Ensure that the child process inherits the client identifier.
    ::SetHandleInformation(clientIdentifier, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);

    // To get the full file path to WebKit2WebProcess.exe, we fild the location of WebKit.dll,
    // remove the last path component, and then append WebKit2WebProcess(_debug).exe.
    HMODULE webKitModule = ::GetModuleHandleW(webKitDLLName);
    ASSERT(webKitModule);
    if (!webKitModule)
        return;

    WCHAR pathStr[MAX_PATH];
    if (!::GetModuleFileNameW(webKitModule, pathStr, WTF_ARRAY_LENGTH(pathStr)))
        return;

    ::PathRemoveFileSpecW(pathStr);
    if (!::PathAppendW(pathStr, webProcessName))
        return;

    String commandLine(pathStr);

    // FIXME: It would be nice if we could just create a CommandLine object and output a command line vector from it.
    Vector<UChar> commandLineVector;
    append(commandLineVector, "\"");
    append(commandLineVector, commandLine);
    append(commandLineVector, "\"");
    append(commandLineVector, " -type webprocess");
    append(commandLineVector, " -clientIdentifier ");
    append(commandLineVector, String::number(reinterpret_cast<uintptr_t>(clientIdentifier)));
    commandLineVector.append('\0');

    STARTUPINFO startupInfo = { 0 };
    startupInfo.cb = sizeof(startupInfo);
    PROCESS_INFORMATION processInformation = { 0 };
    BOOL result = ::CreateProcessW(0, commandLineVector.data(), 0, 0, true, 0, 0, 0, &startupInfo, &processInformation);

    // We can now close the client identifier handle.
    ::CloseHandle(clientIdentifier);

    if (!result) {
        // FIXME: What should we do here?
        DWORD error = ::GetLastError();
        ASSERT_NOT_REACHED();
    }

    // Don't leak the thread handle.
    ::CloseHandle(processInformation.hThread);

    // We've finished launching the process, message back to the run loop.
    RunLoop::main()->dispatch(bind(&ProcessLauncher::didFinishLaunchingProcess, this, processInformation.hProcess, serverIdentifier));
}
Ejemplo n.º 5
0
int main(int argumentCount, const CHAR** arguments)
{
    CommandLine commandLine(argumentCount, arguments);
    ApplicationManager::get()->startApplication(new BrickShaderApplication(&commandLine));

    ApplicationManager::destroy();
    return 0;
}
Ejemplo n.º 6
0
void ProcessWin::ForkAndExec()
{
    nativeIn->CreateHandles();
    nativeOut->CreateHandles();
    nativeErr->CreateHandles();

    STARTUPINFO startupInfo;
    startupInfo.cb          = sizeof(STARTUPINFO);
    startupInfo.lpReserved  = NULL;
    startupInfo.lpDesktop   = NULL;
    startupInfo.lpTitle     = NULL;
    startupInfo.dwFlags     = STARTF_FORCEOFFFEEDBACK | STARTF_USESTDHANDLES;
    startupInfo.cbReserved2 = 0;
    startupInfo.lpReserved2 = NULL;
    //startupInfo.hStdInput = nativeIn->GetReadHandle();
    //startupInfo.hStdOutput = nativeOut->GetWriteHandle();
    //startupInfo.hStdError = nativeErr->GetWriteHandle();
    
    HANDLE hProc = GetCurrentProcess();
    nativeIn->DuplicateRead(hProc, &startupInfo.hStdInput);
    nativeOut->DuplicateWrite(hProc, &startupInfo.hStdOutput);
    nativeErr->DuplicateWrite(hProc, &startupInfo.hStdError);
    
    std::string commandLine(ArgListToString(args));
    std::wstring commandLineW(::UTF8ToWide(commandLine));
    logger->Debug("Launching: %s", commandLine.c_str());

    PROCESS_INFORMATION processInfo;
    BOOL rc = CreateProcessW(NULL,
        (wchar_t*) commandLineW.c_str(),
        NULL,
        NULL,
        TRUE,
        CREATE_NO_WINDOW, // If this is a console application,
           NULL,             // don't open a console window.
        NULL,
        &startupInfo,
        &processInfo);
    
    //CloseHandle(nativeIn->GetReadHandle());
    
    CloseHandle(startupInfo.hStdInput);
    CloseHandle(startupInfo.hStdOutput);
    CloseHandle(startupInfo.hStdError);
    
    if (!rc) {
        std::string message = "Error launching: " + commandLine;
        logger->Error(message);
        throw ValueException::FromString(message);
    }
    else {
        CloseHandle(processInfo.hThread);
        this->pid = processInfo.dwProcessId;
        this->process = processInfo.hProcess;
        this->running = true;
    }
}
Ejemplo n.º 7
0
// main processing
void process(int connfd, struct sockaddr_in address) {
   // Local variables
   char buf[MAXDATASIZE + 1];

   // while data is read
   while (Read(connfd, buf, MAXDATASIZE) > 0) { 
      // executes command
      commandLine(connfd, address, buf);
   }
}
Ejemplo n.º 8
0
//---------------------------------------------------------------------------------
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, 	_In_opt_ HINSTANCE hPrevInstance,	_In_ LPWSTR    lpCmdLine, _In_ int       nCmdShow)
{	
	int argc = 0;	char* argv = "";

	// Exit handler to check memory on exit.
	const int result_1 = std::atexit(CheckMemCallback);

	std::wstring commandLine(lpCmdLine);
	gEditorMode = commandLine.find(L"-Editor") != std::string::npos;

	// Setup glut.
	glutInit(&argc, &argv);
	glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
	glutInitWindowPosition(100, 100);
	int glutWind = glutCreateWindow(APP_WINDOW_TITLE);	
	HDC dc = wglGetCurrentDC();
	MAIN_WINDOW_HANDLE = WindowFromDC(dc);
	glutIdleFunc(Idle);
	glutDisplayFunc(Display);       // Register callback handler for window re-paint event	
	glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
	InitGL();                       // Our own OpenGL initialization

	// Init sounds system.
	CSimpleSound::GetInstance().Initialize(MAIN_WINDOW_HANDLE);
	
	// Call user defined init.
	if (gEditorMode)
	{
		EditorInit();
	}
	else
	{
		Init();
	}

	// Enter glut the event-processing loop				
	glutMainLoop();
	
	// Call user shutdown.
	if (gEditorMode)
	{
		EditorShutdown();
	}
	else
	{
		Shutdown();
	}

	// Shutdown sound system.
	CSimpleSound::GetInstance().Shutdown();

	// And we are done.
	return 0;
}
Ejemplo n.º 9
0
int main(int argumentCount, const CHAR** arguments)
{
    CommandLine commandLine(argumentCount, arguments);
    
    do
    {
        STRING simulationType;
        cout << "Entrez le type de simulation (1 ou 2 ou q pour quitter) : ";
        getline(cin, simulationType);

        UINT quitLetterPosition = simulationType.find("q");
        if ( quitLetterPosition != string::npos )
            return 0;

        UINT automaticLetterPosition = simulationType.find("a");

        BOOL promptPosition = automaticLetterPosition == string::npos;
        BOOL promptVelocity = automaticLetterPosition == string::npos;

        Vector initialPosition = Tp1Constants::INITIAL_POSITION;
        Vector initialVelocity = Tp1Constants::INITIAL_VELOCITY;

        if ( promptPosition )
            promptInitialPosition(initialPosition);
        if ( promptVelocity )
            promptInitialVelocity(initialVelocity);

        cout << endl << "Fermer la fenetre pour recommencer une simulation ou terminer le programme" << endl << endl;

        UINT type1Position = simulationType.find("1");
        if ( type1Position != string::npos ) // Simulation 1 
            ApplicationManager::get()->startApplication(new Tp1Simulation1(&commandLine, 
                                                                           initialPosition, 
                                                                           initialVelocity));
        else                                 // Simulation 2
            ApplicationManager::get()->startApplication(new Tp1Simulation2(&commandLine, 
                                                                           initialPosition, 
                                                                           initialVelocity));

        // Les resultat sont afficher dans la simulation directement

        ApplicationManager::destroy();

    } while( TRUE );

    return 0;
}
Ejemplo n.º 10
0
int main(int argc, char *argv[])
{
	int retVal=0;

	if (argc <= 1)
		retVal = menu();

	else if (argv[1][0] == '-')
		retVal = commandLine(argc, argv);

	else
		retVal = legacyCommandLine(argc, argv);

	// Close the log file if logging
	gp_Log(NULL);

	return retVal;
}
Ejemplo n.º 11
0
 bool MetaParser::isShellCommand(MetaSema::ActionResult& actionResult,
                                 Value* resultValue) {
   if (resultValue)
     *resultValue = Value();
   const Token& Tok = getCurTok();
   if (Tok.is(tok::excl_mark)) {
     consumeAnyStringToken(tok::eof);
     const Token& NextTok = getCurTok();
     if (NextTok.is(tok::raw_ident)) {
        llvm::StringRef commandLine(NextTok.getIdent());
        if (!commandLine.empty())
           actionResult = m_Actions->actOnShellCommand(commandLine,
                                                       resultValue);
     }
     return true;
   }
   return false;
 }
Ejemplo n.º 12
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QCoreApplication::setOrganizationName("amakaseev");
    QCoreApplication::setOrganizationDomain("spicyminds-lab.com");
    QCoreApplication::setApplicationName("SpriteSheetPacker");
    QCoreApplication::setApplicationVersion("1.0.3");

    SpritePackerProjectFile::factory().set<SpritePackerProjectFile>("json");
    SpritePackerProjectFile::factory().set<SpritePackerProjectFileOLD>("sp");
    SpritePackerProjectFile::factory().set<SpritePackerProjectFileTPS>("tps");

    if (argc > 1) {
        return commandLine(app);
    } else {
        MainWindow w;
        w.show();
        return app.exec();
    }
}
Ejemplo n.º 13
0
std::map<std::string, Material> Run2D::readInput(int argc, char** argv) {
	GetPot commandLine(argc, argv);
	std::string Device2DFile;
	std::string MaterialFile;
    if( commandLine.search(2, "-2d", "--file") && commandLine.search(2, "-m", "--file") ) {
    	Device2DFile = commandLine.follow("", 2 , "-2d", "--file");
    	MaterialFile = commandLine.follow("", 2, "-m", "--file");
    }
    else {
    	cerr << "Error: input file missing. Use \" Leno -2d device2DFile -m materialFile \" " << endl ;
        exit(0);
    }

    // Create io
    io2D.readDevice2D(Device2DFile);
    io2D.readMaterial(MaterialFile);

	// create Materials, with default T = 300 K
	Params param;
	std::map<std::string, Material> matLib;
	int i = 0;
	for (std::map<std::string, std::vector<double>>::iterator it = io2D.matMap.begin();
			it  != io2D.matMap.end(); ++it) {
		Material t(i, (int)round(it->second[0]), it->first.c_str(), it->second[1], it->second[2],
				it->second[3], it->second[4], (int)round(it->second[5]), it->second[6],
				it->second[7], it->second[8], it->second[9], it->second[10],
				it->second[11], it->second[12]);
//		std::cout << i << "," << (int)round(it->second[0]) << "," << it->first.c_str() << "," << it->second[1] << ","
//				  << it->second[2] << "," << it->second[3] << "," << it->second[4] << "," << (int)round(it->second[5]) << "," << it->second[6]
//				  << "," << it->second[7] << "," << it->second[8] << "," << it->second[9] << "," << it->second[10] << "," << it->second[11] << ","
// 		          << it->second[12] << std::endl;
		matLib.insert(std::pair<std::string, Material>(it->first, t));
	}

	std::cout << " ** material library is completed." << std::endl;
	return ( matLib );
}
Ejemplo n.º 14
0
/**
  Launch a process

  @param aProcess The RProcess object to use to create the process
  @param aExeName File name of the executable to create the process from
  @param aCommandLine The command line to pass to the new process
  @return KErrNone on success, or one of the other system wide error codes
  */
TInt LaunchProcess(RProcess& aProcess, TDesC & aExeName, TPtr & aCommandLine )
    {

    TPtrC commandLine( aCommandLine );

    TInt err = aProcess.Create( aExeName, commandLine );

    // check that there was no error raised
    if(err != KErrNone)
        {
        return err;
        }

    TRequestStatus status = KRequestPending;
    aProcess.Rendezvous(status);

    if(KRequestPending != status.Int())
        {
        // startup failed so kill the process
        RDebug::Printf( "> RProcess Rendezvous() failed with %d. Killing process", status.Int() );
        aProcess.Kill(KErrNone);
        return status.Int();
        }
    else
        {
        // start up succeeded so resume the process
        aProcess.Resume();
        User::WaitForRequest(status);
        if(KErrNone != status.Int())
            {
            RDebug::Printf( "> RProcess Resume() failed with %d. Killing process", status.Int() );
            aProcess.Kill(KErrNone);
            }
        return status.Int();
        }
    }
Ejemplo n.º 15
0
bool
PluginHangUIParent::Init(const nsString& aPluginName)
{
  if (mHangUIProcessHandle) {
    return false;
  }

  nsresult rv;
  rv = mMiniShm.Init(this, ::IsDebuggerPresent() ? INFINITE : mIPCTimeoutMs);
  NS_ENSURE_SUCCESS(rv, false);
  nsCOMPtr<nsIProperties>
    directoryService(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID));
  if (!directoryService) {
    return false;
  }
  nsCOMPtr<nsIFile> greDir;
  rv = directoryService->Get(NS_GRE_DIR,
                             NS_GET_IID(nsIFile),
                             getter_AddRefs(greDir));
  if (NS_FAILED(rv)) {
    return false;
  }
  nsAutoString path;
  greDir->GetPath(path);

  FilePath exePath(path.get());
  exePath = exePath.AppendASCII(MOZ_HANGUI_PROCESS_NAME);
  CommandLine commandLine(exePath.value());

  nsXPIDLString localizedStr;
  const PRUnichar* formatParams[] = { aPluginName.get() };
  rv = nsContentUtils::FormatLocalizedString(nsContentUtils::eDOM_PROPERTIES,
                                             "PluginHangUIMessage",
                                             formatParams,
                                             localizedStr);
  if (NS_FAILED(rv)) {
    return false;
  }
  commandLine.AppendLooseValue(localizedStr.get());

  const char* keys[] = { "PluginHangUITitle",
                         "PluginHangUIWaitButton",
                         "PluginHangUIStopButton",
                         "DontAskAgain" };
  for (unsigned int i = 0; i < ArrayLength(keys); ++i) {
    rv = nsContentUtils::GetLocalizedString(nsContentUtils::eDOM_PROPERTIES,
                                            keys[i],
                                            localizedStr);
    if (NS_FAILED(rv)) {
      return false;
    }
    commandLine.AppendLooseValue(localizedStr.get());
  }

  rv = GetHangUIOwnerWindowHandle(mMainWindowHandle);
  if (NS_FAILED(rv)) {
    return false;
  }
  nsAutoString hwndStr;
  hwndStr.AppendPrintf("%p", mMainWindowHandle);
  commandLine.AppendLooseValue(hwndStr.get());

  ScopedHandle procHandle(::OpenProcess(SYNCHRONIZE,
                                        TRUE,
                                        GetCurrentProcessId()));
  if (!procHandle.IsValid()) {
    return false;
  }
  nsAutoString procHandleStr;
  procHandleStr.AppendPrintf("%p", procHandle.Get());
  commandLine.AppendLooseValue(procHandleStr.get());

  // On Win7+, pass the application user model to the child, so it can
  // register with it. This insures windows created by the Hang UI
  // properly group with the parent app on the Win7 taskbar.
  nsCOMPtr<nsIWinTaskbar> taskbarInfo = do_GetService(NS_TASKBAR_CONTRACTID);
  if (taskbarInfo) {
    bool isSupported = false;
    taskbarInfo->GetAvailable(&isSupported);
    nsAutoString appId;
    if (isSupported && NS_SUCCEEDED(taskbarInfo->GetDefaultGroupId(appId))) {
      commandLine.AppendLooseValue(appId.get());
    } else {
      commandLine.AppendLooseValue(L"-");
    }
  } else {
    commandLine.AppendLooseValue(L"-");
  }

  nsAutoString ipcTimeoutStr;
  ipcTimeoutStr.AppendInt(mIPCTimeoutMs);
  commandLine.AppendLooseValue(ipcTimeoutStr.get());

  std::wstring ipcCookie;
  rv = mMiniShm.GetCookie(ipcCookie);
  if (NS_FAILED(rv)) {
    return false;
  }
  commandLine.AppendLooseValue(ipcCookie);

  ScopedHandle showEvent(::CreateEvent(nullptr, FALSE, FALSE, nullptr));
  if (!showEvent.IsValid()) {
    return false;
  }
  mShowEvent = showEvent.Get();

  MutexAutoLock lock(mMutex);
  STARTUPINFO startupInfo = { sizeof(STARTUPINFO) };
  PROCESS_INFORMATION processInfo = { nullptr };
  BOOL isProcessCreated = ::CreateProcess(exePath.value().c_str(),
                                          const_cast<wchar_t*>(commandLine.command_line_string().c_str()),
                                          nullptr,
                                          nullptr,
                                          TRUE,
                                          DETACHED_PROCESS,
                                          nullptr,
                                          nullptr,
                                          &startupInfo,
                                          &processInfo);
  if (isProcessCreated) {
    ::CloseHandle(processInfo.hThread);
    mHangUIProcessHandle = processInfo.hProcess;
    ::RegisterWaitForSingleObject(&mRegWait,
                                  processInfo.hProcess,
                                  &SOnHangUIProcessExit,
                                  this,
                                  INFINITE,
                                  WT_EXECUTEDEFAULT | WT_EXECUTEONLYONCE);
    ::WaitForSingleObject(mShowEvent, ::IsDebuggerPresent() ? INFINITE
                                                            : mIPCTimeoutMs);
    // Setting this to true even if we time out on mShowEvent. This timeout 
    // typically occurs when the machine is thrashing so badly that 
    // plugin-hang-ui.exe is taking a while to start. If we didn't set 
    // this to true, Firefox would keep spawning additional plugin-hang-ui 
    // processes, which is not what we want.
    mIsShowing = true;
  }
  mShowEvent = nullptr;
  return !(!isProcessCreated);
}
Ejemplo n.º 16
0
static void parse_commandline(int argc, char* const argv[], SkTArray<SkString>* inputs,
                              sk_tools::PictureBenchmark* benchmark) {
    const char* argv0 = argv[0];
    char* const* stop = argv + argc;

    int repeats = DEFAULT_REPEATS;
    sk_tools::PictureRenderer::SkDeviceTypes deviceType =
        sk_tools::PictureRenderer::kBitmap_DeviceType;

    SkAutoTUnref<sk_tools::PictureRenderer> renderer(NULL);

    // Create a string to show our current settings.
    // TODO: Make it prettier. Currently it just repeats the command line.
    SkString commandLine("bench_pictures:");
    for (int i = 1; i < argc; i++) {
        commandLine.appendf(" %s", *(argv+i));
    }
    commandLine.append("\n");

    bool usePipe = false;
    int numThreads = 1;
    bool useTiles = false;
    const char* widthString = NULL;
    const char* heightString = NULL;
    int gridWidth = 0;
    int gridHeight = 0;
    bool isPowerOf2Mode = false;
    bool isCopyMode = false;
    const char* xTilesString = NULL;
    const char* yTilesString = NULL;
    const char* mode = NULL;
    bool gridSupported = false;
    sk_tools::PictureRenderer::BBoxHierarchyType bbhType =
        sk_tools::PictureRenderer::kNone_BBoxHierarchyType;
    sk_tools::PictureRenderer::DrawFilterFlags drawFilters[SkDrawFilter::kTypeCount];
    sk_bzero(drawFilters, sizeof(drawFilters));
    SkISize viewport;
    viewport.setEmpty();
    for (++argv; argv < stop; ++argv) {
        if (0 == strcmp(*argv, "--repeat")) {
            ++argv;
            if (argv < stop) {
                repeats = atoi(*argv);
                if (repeats < 1) {
                    gLogger.logError("--repeat must be given a value > 0\n");
                    PRINT_USAGE_AND_EXIT;
                }
            } else {
                gLogger.logError("Missing arg for --repeat\n");
                PRINT_USAGE_AND_EXIT;
            }
        } else if (0 == strcmp(*argv, "--pipe")) {
            usePipe = true;
        } else if (0 == strcmp(*argv, "--logFile")) {
            argv++;
            if (argv < stop) {
                if (!gLogger.SetLogFile(*argv)) {
                    SkString str;
                    str.printf("Could not open %s for writing.", *argv);
                    gLogger.logError(str);
                    usage(argv0);
                    // TODO(borenet): We're disabling this for now, due to
                    // write-protected Android devices.  The very short-term
                    // solution is to ignore the fact that we have no log file.
                    //exit(-1);
                }
            } else {
                gLogger.logError("Missing arg for --logFile\n");
                PRINT_USAGE_AND_EXIT;
            }
        } else if (0 == strcmp(*argv, "--multi")) {
            ++argv;
            if (argv >= stop) {
                gLogger.logError("Missing arg for --multi\n");
                PRINT_USAGE_AND_EXIT;
            }
            numThreads = atoi(*argv);
            if (numThreads < 2) {
                gLogger.logError("Number of threads must be at least 2.\n");
                PRINT_USAGE_AND_EXIT;
            }
        } else if (0 == strcmp(*argv, "--bbh")) {
            ++argv;
            if (argv >= stop) {
                gLogger.logError("Missing value for --bbh\n");
                PRINT_USAGE_AND_EXIT;
            }
            if (0 == strcmp(*argv, "none")) {
                bbhType = sk_tools::PictureRenderer::kNone_BBoxHierarchyType;
            } else if (0 == strcmp(*argv, "rtree")) {
                bbhType = sk_tools::PictureRenderer::kRTree_BBoxHierarchyType;
            } else if (0 == strcmp(*argv, "grid")) {
                bbhType = sk_tools::PictureRenderer::kTileGrid_BBoxHierarchyType;
                ++argv;
                if (argv >= stop) {
                    gLogger.logError("Missing width for --bbh grid\n");
                    PRINT_USAGE_AND_EXIT;
                }
                gridWidth = atoi(*argv);
                ++argv;
                if (argv >= stop) {
                    gLogger.logError("Missing height for --bbh grid\n");
                    PRINT_USAGE_AND_EXIT;
                }
                gridHeight = atoi(*argv);
            } else {
                SkString err;
                err.printf("%s is not a valid value for --bbhType\n", *argv);
                gLogger.logError(err);
                PRINT_USAGE_AND_EXIT;
            }

        } else if (0 == strcmp(*argv, "--mode")) {
            if (renderer.get() != NULL) {
                SkDebugf("Cannot combine modes.\n");
                PRINT_USAGE_AND_EXIT;
            }

            ++argv;
            if (argv >= stop) {
                gLogger.logError("Missing mode for --mode\n");
                PRINT_USAGE_AND_EXIT;
            }

            if (0 == strcmp(*argv, "record")) {
                renderer.reset(SkNEW(sk_tools::RecordPictureRenderer));
                gridSupported = true;
            } else if (0 == strcmp(*argv, "clone")) {
                renderer.reset(sk_tools::CreatePictureCloneRenderer());
            } else if (0 == strcmp(*argv, "simple")) {
                renderer.reset(SkNEW(sk_tools::SimplePictureRenderer));
            } else if ((0 == strcmp(*argv, "tile")) || (0 == strcmp(*argv, "pow2tile"))
                       || 0 == strcmp(*argv, "copyTile")) {
                useTiles = true;
                mode = *argv;

                if (0 == strcmp(*argv, "pow2tile")) {
                    isPowerOf2Mode = true;
                } else if (0 == strcmp(*argv, "copyTile")) {
                    isCopyMode = true;
                } else {
                    gridSupported = true;
                }

                ++argv;
                if (argv >= stop) {
                    SkString err;
                    err.printf("Missing width for --mode %s\n", mode);
                    gLogger.logError(err);
                    PRINT_USAGE_AND_EXIT;
                }

                widthString = *argv;
                ++argv;
                if (argv >= stop) {
                    SkString err;
                    err.appendf("Missing height for --mode %s\n", mode);
                    gLogger.logError(err);
                    PRINT_USAGE_AND_EXIT;
                }
                heightString = *argv;
            } else if (0 == strcmp(*argv, "playbackCreation")) {
                renderer.reset(SkNEW(sk_tools::PlaybackCreationRenderer));
                gridSupported = true;
            } else if (0 == strcmp(*argv, "gatherPixelRefs")) {
                renderer.reset(sk_tools::CreateGatherPixelRefsRenderer());
            } else {
                SkString err;
                err.printf("%s is not a valid mode for --mode\n", *argv);
                gLogger.logError(err);
                PRINT_USAGE_AND_EXIT;
            }
        } else if (0 == strcmp(*argv, "--viewport")) {
            ++argv;
            if (argv >= stop) {
                gLogger.logError("Missing width for --viewport\n");
                PRINT_USAGE_AND_EXIT;
            }
            viewport.fWidth = atoi(*argv);
            ++argv;
            if (argv >= stop) {
                gLogger.logError("Missing height for --viewport\n");
                PRINT_USAGE_AND_EXIT;
            }
            viewport.fHeight = atoi(*argv);
        } else if (0 == strcmp(*argv, "--tiles")) {
            ++argv;
            if (argv >= stop) {
                gLogger.logError("Missing x for --tiles\n");
                PRINT_USAGE_AND_EXIT;
            }
            xTilesString = *argv;
            ++argv;
            if (argv >= stop) {
                gLogger.logError("Missing y for --tiles\n");
                PRINT_USAGE_AND_EXIT;
            }
            yTilesString = *argv;
        }  else if (0 == strcmp(*argv, "--device")) {
            ++argv;
            if (argv >= stop) {
                gLogger.logError("Missing mode for --device\n");
                PRINT_USAGE_AND_EXIT;
            }

            if (0 == strcmp(*argv, "bitmap")) {
                deviceType = sk_tools::PictureRenderer::kBitmap_DeviceType;
            }
#if SK_SUPPORT_GPU
            else if (0 == strcmp(*argv, "gpu")) {
                deviceType = sk_tools::PictureRenderer::kGPU_DeviceType;
            }
#endif
            else {
                SkString err;
                err.printf("%s is not a valid mode for --device\n", *argv);
                gLogger.logError(err);
                PRINT_USAGE_AND_EXIT;
            }
        } else if (0 == strcmp(*argv, "--timers")) {
            ++argv;
            if (argv < stop) {
                bool timerWall = false;
                bool truncatedTimerWall = false;
                bool timerCpu = false;
                bool truncatedTimerCpu = false;
                bool timerGpu = false;
                for (char* t = *argv; *t; ++t) {
                    switch (*t) {
                        case 'w':
                            timerWall = true;
                            break;
                        case 'c':
                            timerCpu = true;
                            break;
                        case 'W':
                            truncatedTimerWall = true;
                            break;
                        case 'C':
                            truncatedTimerCpu = true;
                            break;
                        case 'g':
                            timerGpu = true;
                            break;
                        default: {
                            break;
                        }
                    }
                }
                benchmark->setTimersToShow(timerWall, truncatedTimerWall, timerCpu,
                                           truncatedTimerCpu, timerGpu);
            } else {
                gLogger.logError("Missing arg for --timers\n");
                PRINT_USAGE_AND_EXIT;
            }
        } else if (0 == strcmp(*argv, "--timeIndividualTiles")) {
            benchmark->setTimeIndividualTiles(true);
        } else if (0 == strcmp(*argv, "--min")) {
            benchmark->setPrintMin(true);
        } else if (0 == strcmp(*argv, "--logPerIter")) {
            ++argv;
            if (argv < stop) {
                bool log = atoi(*argv) != 0;
                benchmark->setLogPerIter(log);
            } else {
                gLogger.logError("Missing arg for --logPerIter\n");
                PRINT_USAGE_AND_EXIT;
            }
        } else if (0 == strcmp(*argv, "--filter")) {
            ++argv;
            if (argv < stop) {
                const char* colon = strchr(*argv, ':');
                if (colon) {
                    int type = -1;
                    size_t typeLen = colon - *argv;
                    for (size_t tIndex = 0; tIndex < kFilterTypesCount; ++tIndex) {
                        if (typeLen == strlen(gFilterTypes[tIndex])
                                && !strncmp(*argv, gFilterTypes[tIndex], typeLen)) {
                            type = tIndex;
                            break;
                        }
                    }
                    if (type < 0) {
                        SkString err;
                        err.printf("Unknown type for --filter %s\n", *argv);
                        gLogger.logError(err);
                        PRINT_USAGE_AND_EXIT;
                    }
                    int flag = -1;
                    size_t flagLen = strlen(*argv) - typeLen - 1;
                    for (size_t fIndex = 0; fIndex < kFilterFlagsCount; ++fIndex) {
                        if (flagLen == strlen(gFilterFlags[fIndex])
                                && !strncmp(colon + 1, gFilterFlags[fIndex], flagLen)) {
                            flag = 1 << fIndex;
                            break;
                        }
                    }
                    if (flag < 0) {
                        SkString err;
                        err.printf("Unknown flag for --filter %s\n", *argv);
                        gLogger.logError(err);
                        PRINT_USAGE_AND_EXIT;
                    }
                    for (int index = 0; index < SkDrawFilter::kTypeCount; ++index) {
                        if (type != SkDrawFilter::kTypeCount && index != type) {
                            continue;
                        }
                        drawFilters[index] = (sk_tools::PictureRenderer::DrawFilterFlags)
                                (drawFilters[index] | flag);
                    }
                } else {
                    SkString err;
                    err.printf("Unknown arg for --filter %s : missing colon\n", *argv);
                    gLogger.logError(err);
                    PRINT_USAGE_AND_EXIT;
                }
            } else {
                gLogger.logError("Missing arg for --filter\n");
                PRINT_USAGE_AND_EXIT;
            }
        } else if (0 == strcmp(*argv, "--help") || 0 == strcmp(*argv, "-h")) {
            PRINT_USAGE_AND_EXIT;
        } else {
            inputs->push_back(SkString(*argv));
        }
    }

    if (numThreads > 1 && !useTiles) {
        gLogger.logError("Multithreaded drawing requires tiled rendering.\n");
        PRINT_USAGE_AND_EXIT;
    }

    if (usePipe && sk_tools::PictureRenderer::kNone_BBoxHierarchyType != bbhType) {
        gLogger.logError("--pipe and --bbh cannot be used together\n");
        PRINT_USAGE_AND_EXIT;
    }

    if (sk_tools::PictureRenderer::kTileGrid_BBoxHierarchyType == bbhType &&
        !gridSupported) {
        gLogger.logError("'--bbh grid' is not compatible with specified --mode.\n");
        PRINT_USAGE_AND_EXIT;
    }

    if (useTiles) {
        SkASSERT(NULL == renderer);
        sk_tools::TiledPictureRenderer* tiledRenderer;
        if (isCopyMode) {
            int x, y;
            if (xTilesString != NULL) {
                SkASSERT(yTilesString != NULL);
                x = atoi(xTilesString);
                y = atoi(yTilesString);
                if (x <= 0 || y <= 0) {
                    gLogger.logError("--tiles must be given values > 0\n");
                    PRINT_USAGE_AND_EXIT;
                }
            } else {
                x = y = 4;
            }
            tiledRenderer = SkNEW_ARGS(sk_tools::CopyTilesRenderer, (x, y));
            if (benchmark->timeIndividualTiles()) {
                gLogger.logError("timeIndividualTiles is not compatible with copyTile\n");
                PRINT_USAGE_AND_EXIT;
            }
        } else if (numThreads > 1) {
            tiledRenderer = SkNEW_ARGS(sk_tools::MultiCorePictureRenderer, (numThreads));
        } else {
            tiledRenderer = SkNEW(sk_tools::TiledPictureRenderer);
        }
        if (isPowerOf2Mode) {
            int minWidth = atoi(widthString);
            if (!SkIsPow2(minWidth) || minWidth < 0) {
                tiledRenderer->unref();
                SkString err;
                err.printf("-mode %s must be given a width"
                         " value that is a power of two\n", mode);
                gLogger.logError(err);
                PRINT_USAGE_AND_EXIT;
            }
            tiledRenderer->setTileMinPowerOf2Width(minWidth);
        } else if (sk_tools::is_percentage(widthString)) {
            if (isCopyMode) {
                tiledRenderer->unref();
                SkString err;
                err.printf("--mode %s does not support percentages.\n", mode);
                gLogger.logError(err.c_str());
                PRINT_USAGE_AND_EXIT;
            }
            tiledRenderer->setTileWidthPercentage(atof(widthString));
            if (!(tiledRenderer->getTileWidthPercentage() > 0)) {
                tiledRenderer->unref();
                SkString err;
                err.appendf("--mode %s must be given a width percentage > 0\n", mode);
                gLogger.logError(err);
                PRINT_USAGE_AND_EXIT;
            }
        } else {
            tiledRenderer->setTileWidth(atoi(widthString));
            if (!(tiledRenderer->getTileWidth() > 0)) {
                tiledRenderer->unref();
                SkString err;
                err.appendf("--mode %s must be given a width > 0\n", mode);
                gLogger.logError(err);
                PRINT_USAGE_AND_EXIT;
            }
        }

        if (sk_tools::is_percentage(heightString)) {
            if (isCopyMode) {
                tiledRenderer->unref();
                SkString err;
                err.printf("--mode %s does not support percentages.\n", mode);
                gLogger.logError(err.c_str());
                PRINT_USAGE_AND_EXIT;
            }
            tiledRenderer->setTileHeightPercentage(atof(heightString));
            if (!(tiledRenderer->getTileHeightPercentage() > 0)) {
                tiledRenderer->unref();
                SkString err;
                err.appendf("--mode %s must be given a height percentage > 0\n", mode);
                gLogger.logError(err);
                PRINT_USAGE_AND_EXIT;
            }
        } else {
            tiledRenderer->setTileHeight(atoi(heightString));
            if (!(tiledRenderer->getTileHeight() > 0)) {
                tiledRenderer->unref();
                SkString err;
                err.appendf("--mode %s must be given a height > 0\n", mode);
                gLogger.logError(err);
                PRINT_USAGE_AND_EXIT;
            }
        }
        if (numThreads > 1) {
#if SK_SUPPORT_GPU
            if (sk_tools::PictureRenderer::kGPU_DeviceType == deviceType) {
                tiledRenderer->unref();
                gLogger.logError("GPU not compatible with multithreaded tiling.\n");
                PRINT_USAGE_AND_EXIT;
            }
#endif
        }
        renderer.reset(tiledRenderer);
        if (usePipe) {
            gLogger.logError("Pipe rendering is currently not compatible with tiling.\n"
                     "Turning off pipe.\n");
        }
    } else {
        if (benchmark->timeIndividualTiles()) {
            gLogger.logError("timeIndividualTiles requires tiled rendering.\n");
            PRINT_USAGE_AND_EXIT;
        }
        if (usePipe) {
            if (renderer.get() != NULL) {
                gLogger.logError("Pipe is incompatible with other modes.\n");
                PRINT_USAGE_AND_EXIT;
            }
            renderer.reset(SkNEW(sk_tools::PipePictureRenderer));
        }
    }
    if (inputs->count() < 1) {
        PRINT_USAGE_AND_EXIT;
    }

    if (NULL == renderer) {
        renderer.reset(SkNEW(sk_tools::SimplePictureRenderer));
    }

    renderer->setBBoxHierarchyType(bbhType);
    renderer->setDrawFilters(drawFilters, filtersName(drawFilters));
    renderer->setGridSize(gridWidth, gridHeight);
    renderer->setViewport(viewport);
    benchmark->setRenderer(renderer);
    benchmark->setRepeats(repeats);
    benchmark->setDeviceType(deviceType);
    benchmark->setLogger(&gLogger);
    // Report current settings:
    gLogger.logProgress(commandLine);
}
Ejemplo n.º 17
0
Result<ExitCode> ProcessAsUser::Run(const Settings& settings, ProcessTracker& processTracker) const
{
	Trace trace(settings.GetLogLevel());
	trace < L"ProcessAsUser::Attempt to log a user on to the local computer";
	StringBuffer userName(settings.GetUserName());
	StringBuffer domain(settings.GetDomain());
	StringBuffer password(settings.GetPassword());
	StringBuffer workingDirectory(settings.GetWorkingDirectory());
	StringBuffer commandLine(settings.GetCommandLine());

	SecurityManager securityManager;
	auto setPrivilegesResult = securityManager.SetPrivileges(trace, { SE_TCB_NAME, SE_ASSIGNPRIMARYTOKEN_NAME }, true);
	if(setPrivilegesResult.HasError())
	{
		return setPrivilegesResult.GetError();
	}

	auto newUserSecurityTokenHandle = Handle(L"New user security token");
	unsigned long logonTypeCount = sizeof(allLogonTypes) / sizeof(allLogonTypes[0]);
	for (unsigned long logonTypeIndex = 0; logonTypeIndex < logonTypeCount; logonTypeIndex++)
	{
		auto logonType = allLogonTypes[logonTypeIndex];
		trace < L"::LogonUser using logon type ";
		switch (logonType)
		{
			case LOGON32_LOGON_INTERACTIVE:
				trace << L"LOGON32_LOGON_INTERACTIVE";
				break;

			case LOGON32_LOGON_NETWORK:
				trace << L"LOGON32_LOGON_NETWORK";
				break;

			case LOGON32_LOGON_BATCH:
				trace << L"LOGON32_LOGON_BATCH";
				break;

			case LOGON32_LOGON_SERVICE:
				trace << L"LOGON32_LOGON_SERVICE";
				break;
		}

		if (LogonUser(
			userName.GetPointer(),
			domain.GetPointer(),
			password.GetPointer(),
			logonType,
			LOGON32_PROVIDER_DEFAULT,
			&newUserSecurityTokenHandle))
		{
			break;
		}
		
		auto error = Error(L"LogonUser");
		trace << L" - ";
		trace << error.GetDescription();

		if(logonTypeIndex == logonTypeCount -1)
		{
			return error;
		}
	}

	trace < L"ProcessAsUser::InitializeConsoleRedirection a new security descriptor";
	trace < L"::InitializeSecurityDescriptor";
	SECURITY_DESCRIPTOR securityDescriptor = {};
	if (!InitializeSecurityDescriptor(
		&securityDescriptor,
		SECURITY_DESCRIPTOR_REVISION))
	{
		return Error(L"InitializeSecurityDescriptor");
	}

	trace < L"::SetSecurityDescriptorDacl";
	if (!SetSecurityDescriptorDacl(
		&securityDescriptor,
		true,
		nullptr,
		false))
	{
		return Error(L"SetSecurityDescriptorDacl");
	}

	trace < L"ProcessAsUser::Creates a new access primary token that duplicates new process's token";
	auto primaryNewUserSecurityTokenHandle = Handle(L"Primary new user security token");
	SECURITY_ATTRIBUTES processSecAttributes = {};
	processSecAttributes.lpSecurityDescriptor = &securityDescriptor;
	processSecAttributes.nLength = sizeof(SECURITY_DESCRIPTOR);
	processSecAttributes.bInheritHandle = true;
	trace < L"::DuplicateTokenEx";
	if (!DuplicateTokenEx(
		newUserSecurityTokenHandle,
		0, // MAXIMUM_ALLOWED
		&processSecAttributes,
		SecurityImpersonation,
		TokenPrimary,
		&primaryNewUserSecurityTokenHandle))
	{
		return Error(L"DuplicateTokenEx");
	}	

	SECURITY_ATTRIBUTES threadSecAttributes = {};
	threadSecAttributes.lpSecurityDescriptor = nullptr;
	threadSecAttributes.nLength = 0;
	threadSecAttributes.bInheritHandle = false;	
	STARTUPINFO startupInfo = {};	

	trace < L"ProcessTracker::InitializeConsoleRedirection";
	auto error = processTracker.InitializeConsoleRedirection(processSecAttributes, startupInfo);
	if(error.HasError())
	{
		return Result<ExitCode>(error.GetError());
	}

	trace < L"::LoadUserProfile";
	PROFILEINFO profileInfo = {};
	profileInfo.dwSize = sizeof(PROFILEINFO);
	profileInfo.lpUserName = userName.GetPointer();
	if (!LoadUserProfile(primaryNewUserSecurityTokenHandle, &profileInfo))
	{
		return Error(L"LoadUserProfile");
	}

	auto newProcessEnvironmentResult = GetEnvironment(settings, primaryNewUserSecurityTokenHandle, settings.GetInheritanceMode(), trace);
	if (newProcessEnvironmentResult.HasError())
	{
		UnloadUserProfile(primaryNewUserSecurityTokenHandle, profileInfo.hProfile);
		return Result<ExitCode>(newProcessEnvironmentResult.GetError());
	}

	auto setIntegrityLevelResult = securityManager.SetIntegrityLevel(settings.GetIntegrityLevel(), primaryNewUserSecurityTokenHandle, trace);
	if (setIntegrityLevelResult.HasError())
	{
		return Result<ExitCode>(setIntegrityLevelResult.GetError());
	}

	trace < L"ProcessAsUser::Create a new process and its primary thread. The new process runs in the security context of the user represented by the specified token.";
	PROCESS_INFORMATION processInformation = {};
	startupInfo.dwFlags = STARTF_USESHOWWINDOW;
	startupInfo.wShowWindow = ShowModeConverter::ToShowWindowFlag(settings.GetShowMode());
	auto cmdLine = settings.GetCommandLine();
	trace < L"::CreateProcessAsUser";	
	if (!CreateProcessAsUser(
		primaryNewUserSecurityTokenHandle,
		nullptr,
		commandLine.GetPointer(),
		&processSecAttributes,
		&threadSecAttributes,
		true,
		CREATE_UNICODE_ENVIRONMENT,
		newProcessEnvironmentResult.GetResultValue().CreateEnvironment(),
		workingDirectory.GetPointer(),
		&startupInfo,
		&processInformation))
	{		
		auto result = Error(L"CreateProcessAsUser");
		UnloadUserProfile(primaryNewUserSecurityTokenHandle, profileInfo.hProfile);
		return result;
	}

	// ReSharper disable CppInitializedValueIsAlwaysRewritten
	// ReSharper disable CppEntityAssignedButNoRead
	
	auto processHandle = Handle(L"Service Process");
	processHandle = processInformation.hProcess;
	
	auto threadHandle = Handle(L"Thread");
	threadHandle = processInformation.hThread;

	auto exitCode = processTracker.WaiteForExit(processInformation.hProcess, trace);
	UnloadUserProfile(primaryNewUserSecurityTokenHandle, profileInfo.hProfile);	

	return exitCode;
}
Ejemplo n.º 18
0
Configuration::Configuration(int & argc, char ** argv)
  : runNormally_(true),
    observationToCheck_(0),
    logLevel_(milog::DEBUG),
    port_(0) {
const char * USER = std::getenv("USER");
const std::string databaseUser = USER ? USER : "******";

options_description commandLine("Command-line options");

options_description observation("Single observation");
observation.add_options()("station,s", value<int>(), "Check the given station")(
    "obstime,o", value<std::string>(), "Check the given obstime")(
    "typeid,t", value<int>(), "Check the given typeid")(
    "qcx",
    value<std::string>(),
    "Only run the given check. This also means that control flags will not be reset before checks are run")(
    "model-source", value<std::string>(&modelDataName_)->default_value("yr"),
    "Get model data from the given source (from model table in database");

options_description logging("Logging");
logging.add_options()(
    "runloglevel", value<std::string>()->default_value("info"),
    "Set loglevel (debug_all, debug, info, warn, error or fatal")(
    "runlogfile",
    value<std::string>(&runLogFile_)->default_value(
        kvalobs::kvPath(kvalobs::logdir) + "/kvQabased.log"),
    "Set file name for run log")(
    "logdir",
    value<std::string>(&baseLogDir_)->default_value(
        kvalobs::kvPath(kvalobs::logdir) + "/checks/"),
    "Use the given directory as base directory for script logs");

options_description database("Database");
database.add_options()(
    "database,d", value<std::string>(&databaseName_)->default_value("kvalobs"),
    "Name of database to connect to")("host,h", value<std::string>(&host_),
                                      "Hostname of database")(
    "port,p", value<int>(&port_), "Port of database")(
    "user,U", value<std::string>(&user_)->default_value(databaseUser),
    "Database user");

options_description generic("Generic");
generic.add_options()
    ("process-count", value<unsigned>(& processCount_)->default_value(4), "Run the given number of processes")
    ("config", value<std::string>(), "Read configuration from the given file")
    ("version", "Produce version information")
    ("help", "Produce help message");

commandLine.add(observation).add(logging).add(database).add(generic);

parsed_options parsed = command_line_parser(argc, argv).options(commandLine).
//allow_unregistered().
    run();
variables_map vm;
store(parsed, vm);
notify(vm);

if (vm.count("version")) {
  version(std::cout);
  runNormally_ = false;
  return;
}
if (vm.count("help")) {
  help(std::cout, commandLine);
  runNormally_ = false;
  return;
}

options_description configFileOptions;
configFileOptions.add(logging).add(database);

if (vm.count("config"))
  parse(vm["config"].as<std::string>(), vm, configFileOptions);

boost::filesystem::path defaultConfig = defaultConfigFile();
if (not defaultConfig.empty())
  parse(defaultConfig, vm, configFileOptions);

if (vm.count("qcx")) {
  std::string qcxFilter = vm["qcx"].as<std::string>();
  qcxFilter_.push_back(qcxFilter);
}

if (vm.count("runloglevel")) {
  std::string wantedLevel = vm["runloglevel"].as<std::string>();
  if (wantedLevel == "debug_all")
    logLevel_ = milog::DEBUG1;
  else if (wantedLevel == "debug")
    logLevel_ = milog::DEBUG;
  else if (wantedLevel == "info")
    logLevel_ = milog::INFO;
  else if (wantedLevel == "warn")
    logLevel_ = milog::WARN;
  else if (wantedLevel == "error")
    logLevel_ = milog::ERROR;
  else if (wantedLevel == "fatal")
    logLevel_ = milog::FATAL;
  else
    throw std::runtime_error(wantedLevel + " is not a valid loglevel");
}
//milog::Logger::logger().logLevel(logLevel_);

observationToCheck_ = getStationInfo(vm);
}
Ejemplo n.º 19
0
Result<ExitCode> ProcessWithLogon::RunInternal(Trace& trace, const Settings& settings, ProcessTracker& processTracker, Environment& environment, bool changeIntegrityLevel) const
{
	SECURITY_ATTRIBUTES securityAttributes = {};
	securityAttributes.nLength = sizeof(SECURITY_DESCRIPTOR);
	securityAttributes.bInheritHandle = true;

	STARTUPINFO startupInfo = {};
	startupInfo.dwFlags = STARTF_USESHOWWINDOW;
	startupInfo.wShowWindow = ShowModeConverter::ToShowWindowFlag(settings.GetShowMode());	
	PROCESS_INFORMATION processInformation = {};

	trace < L"ProcessTracker::InitializeConsoleRedirection";
	processTracker.InitializeConsoleRedirection(securityAttributes, startupInfo);	

	StringBuffer userName(settings.GetUserName());
	StringBuffer domain(settings.GetDomain());
	StringBuffer password(settings.GetPassword());
	StringBuffer workingDirectory(settings.GetWorkingDirectory());
	StringBuffer commandLine(settings.GetCommandLine());

	if (changeIntegrityLevel)
	{
		trace < L"::LogonUser";
		auto newUserSecurityTokenHandle = Handle(L"New user security token");
		if (!LogonUser(
			userName.GetPointer(),
			domain.GetPointer(),
			password.GetPointer(),
			LOGON32_LOGON_BATCH,
			LOGON32_PROVIDER_DEFAULT,
			&newUserSecurityTokenHandle))
		{
			return Error(L"LogonUser");
		}

		trace < L"::LoadUserProfile";
		PROFILEINFO profileInfo = {};
		profileInfo.dwSize = sizeof(PROFILEINFO);
		profileInfo.lpUserName = userName.GetPointer();
		if (!LoadUserProfile(newUserSecurityTokenHandle, &profileInfo))
		{
			return Error(L"LoadUserProfile");
		}

		SecurityManager securityManager;
		auto setIntegrityLevelResult = securityManager.SetIntegrityLevel(settings.GetIntegrityLevel(), newUserSecurityTokenHandle, trace);
		if (setIntegrityLevelResult.HasError())
		{
			return Result<ExitCode>(setIntegrityLevelResult.GetError());
		}

		trace < L"::CreateProcessWithTokenW";		
		if (!CreateProcessWithTokenW(
			newUserSecurityTokenHandle,
			LOGON_WITH_PROFILE,
			nullptr,
			commandLine.GetPointer(),
			CREATE_UNICODE_ENVIRONMENT,
			environment.CreateEnvironment(),
			workingDirectory.GetPointer(),
			&startupInfo,
			&processInformation))
		{
			return Error(L"CreateProcessWithLogonW");
		}
	}
	else
	{
		trace < L"::CreateProcessWithLogonW";		
		if (!CreateProcessWithLogonW(
			userName.GetPointer(),
			domain.GetPointer(),
			password.GetPointer(),
			LOGON_WITH_PROFILE,
			nullptr,
			commandLine.GetPointer(),
			CREATE_UNICODE_ENVIRONMENT,
			environment.CreateEnvironment(),
			workingDirectory.GetPointer(),
			&startupInfo,
			&processInformation))
		{
			return Error(L"CreateProcessWithLogonW");
		}
	}

	// ReSharper disable once CppInitializedValueIsAlwaysRewritten
	auto processHandle = Handle(L"Process");
	processHandle = processInformation.hProcess;

	// ReSharper disable once CppInitializedValueIsAlwaysRewritten
	auto threadHandle = Handle(L"Thread");
	threadHandle = processInformation.hThread;

	return processTracker.WaiteForExit(processInformation.hProcess, trace);
}
Ejemplo n.º 20
0
static void parse_commandline(int argc, char* const argv[], SkTArray<SkString>* inputs,
                              sk_tools::PictureBenchmark*& benchmark) {
    const char* argv0 = argv[0];
    char* const* stop = argv + argc;

    int repeats = DEFAULT_REPEATS;
    sk_tools::PictureRenderer::SkDeviceTypes deviceType =
        sk_tools::PictureRenderer::kBitmap_DeviceType;

    // Create a string to show our current settings.
    // TODO: Make it prettier. Currently it just repeats the command line.
    SkString commandLine("bench_pictures:");
    for (int i = 1; i < argc; i++) {
        commandLine.appendf(" %s", *(argv+i));
    }
    commandLine.append("\n");

    bool usePipe = false;
    bool multiThreaded = false;
    bool useTiles = false;
    const char* widthString = NULL;
    const char* heightString = NULL;
    bool isPowerOf2Mode = false;
    const char* mode = NULL;
    for (++argv; argv < stop; ++argv) {
        if (0 == strcmp(*argv, "--repeat")) {
            ++argv;
            if (argv < stop) {
                repeats = atoi(*argv);
                if (repeats < 1) {
                    SkDELETE(benchmark);
                    gLogger.logError("--repeat must be given a value > 0\n");
                    exit(-1);
                }
            } else {
                SkDELETE(benchmark);
                gLogger.logError("Missing arg for --repeat\n");
                usage(argv0);
                exit(-1);
            }
        } else if (0 == strcmp(*argv, "--pipe")) {
            usePipe = true;
        } else if (0 == strcmp(*argv, "--logFile")) {
            argv++;
            if (argv < stop) {
                if (!gLogger.SetLogFile(*argv)) {
                    SkString str;
                    str.printf("Could not open %s for writing.", *argv);
                    gLogger.logError(str);
                    usage(argv0);
                    exit(-1);
                }
            } else {
                gLogger.logError("Missing arg for --logFile\n");
                usage(argv0);
                exit(-1);
            }
        } else if (0 == strcmp(*argv, "--mode")) {
            SkDELETE(benchmark);

            ++argv;
            if (argv >= stop) {
                gLogger.logError("Missing mode for --mode\n");
                usage(argv0);
                exit(-1);
            }

            if (0 == strcmp(*argv, "record")) {
                benchmark = SkNEW(sk_tools::RecordPictureBenchmark);
            } else if (0 == strcmp(*argv, "simple")) {
                benchmark = SkNEW(sk_tools::SimplePictureBenchmark);
            } else if ((0 == strcmp(*argv, "tile")) || (0 == strcmp(*argv, "pow2tile"))) {
                useTiles = true;
                mode = *argv;

                if (0 == strcmp(*argv, "pow2tile")) {
                    isPowerOf2Mode = true;
                }

                ++argv;
                if (argv >= stop) {
                    SkString err;
                    err.printf("Missing width for --mode %s\n", mode);
                    gLogger.logError(err);
                    usage(argv0);
                    exit(-1);
                }

                widthString = *argv;
                ++argv;
                if (argv >= stop) {
                    gLogger.logError("Missing height for --mode tile\n");
                    usage(argv0);
                    exit(-1);
                }
                heightString = *argv;

                ++argv;
                if (argv < stop && 0 == strcmp(*argv, "multi")) {
                    multiThreaded = true;
                } else {
                    --argv;
                }
            } else if (0 == strcmp(*argv, "playbackCreation")) {
                benchmark = SkNEW(sk_tools::PlaybackCreationBenchmark);
            } else {
                SkString err;
                err.printf("%s is not a valid mode for --mode\n", *argv);
                gLogger.logError(err);
                usage(argv0);
                exit(-1);
            }
        }  else if (0 == strcmp(*argv, "--device")) {
            ++argv;
            if (argv >= stop) {
                gLogger.logError("Missing mode for --deivce\n");
                usage(argv0);
                exit(-1);
            }

            if (0 == strcmp(*argv, "bitmap")) {
                deviceType = sk_tools::PictureRenderer::kBitmap_DeviceType;
            }
#if SK_SUPPORT_GPU
            else if (0 == strcmp(*argv, "gpu")) {
                deviceType = sk_tools::PictureRenderer::kGPU_DeviceType;
            }
#endif
            else {
                SkString err;
                err.printf("%s is not a valid mode for --device\n", *argv);
                gLogger.logError(err);
                usage(argv0);
                exit(-1);
            }

        } else if (0 == strcmp(*argv, "--help") || 0 == strcmp(*argv, "-h")) {
            SkDELETE(benchmark);
            usage(argv0);
            exit(0);
        } else {
            inputs->push_back(SkString(*argv));
        }
    }

    if (useTiles) {
        sk_tools::TiledPictureBenchmark* tileBenchmark = SkNEW(sk_tools::TiledPictureBenchmark);
        if (isPowerOf2Mode) {
            int minWidth = atoi(widthString);
            if (!SkIsPow2(minWidth) || minWidth < 0) {
                SkDELETE(tileBenchmark);
                SkString err;
                err.printf("--mode %s must be given a width"
                         " value that is a power of two\n", mode);
                gLogger.logError(err);
                exit(-1);
            }
            tileBenchmark->setTileMinPowerOf2Width(minWidth);
        } else if (sk_tools::is_percentage(widthString)) {
            tileBenchmark->setTileWidthPercentage(atof(widthString));
            if (!(tileBenchmark->getTileWidthPercentage() > 0)) {
                SkDELETE(tileBenchmark);
                gLogger.logError("--mode tile must be given a width percentage > 0\n");
                exit(-1);
            }
        } else {
            tileBenchmark->setTileWidth(atoi(widthString));
            if (!(tileBenchmark->getTileWidth() > 0)) {
                SkDELETE(tileBenchmark);
                gLogger.logError("--mode tile must be given a width > 0\n");
                exit(-1);
            }
        }

        if (sk_tools::is_percentage(heightString)) {
            tileBenchmark->setTileHeightPercentage(atof(heightString));
            if (!(tileBenchmark->getTileHeightPercentage() > 0)) {
                SkDELETE(tileBenchmark);
                gLogger.logError("--mode tile must be given a height percentage > 0\n");
                exit(-1);
            }
        } else {
            tileBenchmark->setTileHeight(atoi(heightString));
            if (!(tileBenchmark->getTileHeight() > 0)) {
                SkDELETE(tileBenchmark);
                gLogger.logError("--mode tile must be given a height > 0\n");
                exit(-1);
            }
        }
        tileBenchmark->setThreading(multiThreaded);
        tileBenchmark->setUsePipe(usePipe);
        benchmark = tileBenchmark;
    } else if (usePipe) {
        SkDELETE(benchmark);
        benchmark = SkNEW(sk_tools::PipePictureBenchmark);
    }
    if (inputs->count() < 1) {
        SkDELETE(benchmark);
        usage(argv0);
        exit(-1);
    }

    if (NULL == benchmark) {
        benchmark = SkNEW(sk_tools::SimplePictureBenchmark);
    }

    benchmark->setRepeats(repeats);
    benchmark->setDeviceType(deviceType);
    benchmark->setLogger(&gLogger);
    // Report current settings:
    gLogger.logProgress(commandLine);
}
Ejemplo n.º 21
0
bool
PluginHangUIParent::Init(const nsString& aPluginName)
{
  if (mHangUIProcessHandle) {
    return false;
  }

  nsresult rv;
  rv = mMiniShm.Init(this, ::IsDebuggerPresent() ? INFINITE : kTimeout);
  NS_ENSURE_SUCCESS(rv, false);
  nsCOMPtr<nsIProperties>
    directoryService(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID));
  if (!directoryService) {
    return false;
  }
  nsCOMPtr<nsIFile> greDir;
  rv = directoryService->Get(NS_GRE_DIR,
                             NS_GET_IID(nsIFile),
                             getter_AddRefs(greDir));
  if (NS_FAILED(rv)) {
    return false;
  }
  nsAutoString path;
  greDir->GetPath(path);

  FilePath exePath(path.get());
  exePath = exePath.AppendASCII(MOZ_HANGUI_PROCESS_NAME);
  CommandLine commandLine(exePath.value());

  nsXPIDLString localizedStr;
  const PRUnichar* formatParams[] = { aPluginName.get() };
  rv = nsContentUtils::FormatLocalizedString(nsContentUtils::eDOM_PROPERTIES,
                                             "PluginHangUIMessage",
                                             formatParams,
                                             localizedStr);
  if (NS_FAILED(rv)) {
    return false;
  }
  commandLine.AppendLooseValue(localizedStr.get());

  const char* keys[] = { "PluginHangUITitle",
                         "PluginHangUIWaitButton",
                         "PluginHangUIStopButton",
                         "DontAskAgain" };
  for (unsigned int i = 0; i < ArrayLength(keys); ++i) {
    rv = nsContentUtils::GetLocalizedString(nsContentUtils::eDOM_PROPERTIES,
                                            keys[i],
                                            localizedStr);
    if (NS_FAILED(rv)) {
      return false;
    }
    commandLine.AppendLooseValue(localizedStr.get());
  }

  rv = GetHangUIOwnerWindowHandle(mMainWindowHandle);
  if (NS_FAILED(rv)) {
    return false;
  }
  nsAutoString hwndStr;
  hwndStr.AppendPrintf("%p", mMainWindowHandle);
  commandLine.AppendLooseValue(hwndStr.get());

  ScopedHandle procHandle(::OpenProcess(SYNCHRONIZE,
                                        TRUE,
                                        GetCurrentProcessId()));
  if (!procHandle.IsValid()) {
    return false;
  }
  nsAutoString procHandleStr;
  procHandleStr.AppendPrintf("%p", procHandle.Get());
  commandLine.AppendLooseValue(procHandleStr.get());

  std::wstring ipcCookie;
  rv = mMiniShm.GetCookie(ipcCookie);
  if (NS_FAILED(rv)) {
    return false;
  }
  commandLine.AppendLooseValue(ipcCookie);

  mShowEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
  ScopedHandle showEvent(::CreateEvent(NULL, FALSE, FALSE, NULL));
  if (!showEvent.IsValid()) {
    return false;
  }
  mShowEvent = showEvent.Get();

  STARTUPINFO startupInfo = { sizeof(STARTUPINFO) };
  PROCESS_INFORMATION processInfo = { NULL };
  BOOL isProcessCreated = ::CreateProcess(exePath.value().c_str(),
                                          const_cast<wchar_t*>(commandLine.command_line_string().c_str()),
                                          nullptr,
                                          nullptr,
                                          TRUE,
                                          DETACHED_PROCESS,
                                          nullptr,
                                          nullptr,
                                          &startupInfo,
                                          &processInfo);
  if (isProcessCreated) {
    ::CloseHandle(processInfo.hThread);
    mHangUIProcessHandle = processInfo.hProcess;
    ::RegisterWaitForSingleObject(&mRegWait,
                                  processInfo.hProcess,
                                  &SOnHangUIProcessExit,
                                  this,
                                  INFINITE,
                                  WT_EXECUTEDEFAULT | WT_EXECUTEONLYONCE);
    ::WaitForSingleObject(mShowEvent, kTimeout);
  }
  mShowEvent = NULL;
  return !(!isProcessCreated);
}