2
0

RunWithStats.cpp 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <windows.h>
  3. #include <string>
  4. #include <psapi.h>
  5. #include <shlobj.h>
  6. #include <algorithm>
  7. #include <stdio.h>
  8. #include <time.h>
  9. std::string GetEnv(const std::string& name)
  10. {
  11. char envStr[1024];
  12. envStr[0] = 0;
  13. ::GetEnvironmentVariableA(name.c_str(), envStr, sizeof(envStr));
  14. return envStr;
  15. }
  16. static bool CreatePipeWithSecurityAttributes(HANDLE& hReadPipe, HANDLE& hWritePipe, SECURITY_ATTRIBUTES* lpPipeAttributes, int nSize)
  17. {
  18. hReadPipe = 0;
  19. hWritePipe = 0;
  20. bool ret = ::CreatePipe(&hReadPipe, &hWritePipe, lpPipeAttributes, nSize);
  21. if (!ret || (hReadPipe == INVALID_HANDLE_VALUE) || (hWritePipe == INVALID_HANDLE_VALUE))
  22. return false;
  23. return true;
  24. }
  25. // Using synchronous Anonymous pipes for process input/output redirection means we would end up
  26. // wasting a worker threadpool thread per pipe instance. Overlapped pipe IO is desirable, since
  27. // it will take advantage of the NT IO completion port infrastructure. But we can't really use
  28. // Overlapped I/O for process input/output as it would break Console apps (managed Console class
  29. // methods such as WriteLine as well as native CRT functions like printf) which are making an
  30. // assumption that the console standard handles (obtained via GetStdHandle()) are opened
  31. // for synchronous I/O and hence they can work fine with ReadFile/WriteFile synchrnously!
  32. bool CreatePipe(HANDLE& parentHandle, HANDLE& childHandle, bool parentInputs)
  33. {
  34. SECURITY_ATTRIBUTES securityAttributesParent = { 0 };
  35. securityAttributesParent.bInheritHandle = 1;
  36. HANDLE hTmp = INVALID_HANDLE_VALUE;
  37. if (parentInputs)
  38. CreatePipeWithSecurityAttributes(childHandle, hTmp, &securityAttributesParent, 0);
  39. else
  40. CreatePipeWithSecurityAttributes(hTmp, childHandle, &securityAttributesParent, 0);
  41. HANDLE dupHandle = 0;
  42. // Duplicate the parent handle to be non-inheritable so that the child process
  43. // doesn't have access. This is done for correctness sake, exact reason is unclear.
  44. // One potential theory is that child process can do something brain dead like
  45. // closing the parent end of the pipe and there by getting into a blocking situation
  46. // as parent will not be draining the pipe at the other end anymore.
  47. if (!::DuplicateHandle(GetCurrentProcess(), hTmp,
  48. GetCurrentProcess(), &dupHandle,
  49. 0, false, DUPLICATE_SAME_ACCESS))
  50. {
  51. return false;
  52. }
  53. parentHandle = dupHandle;
  54. if (hTmp != INVALID_HANDLE_VALUE)
  55. ::CloseHandle(hTmp);
  56. return true;
  57. }
  58. struct ProcParams
  59. {
  60. HANDLE mReadHandle;
  61. HANDLE mWriteHandle;
  62. };
  63. DWORD WINAPI ReadProc(void* lpThreadParameter)
  64. {
  65. ProcParams* procParams = (ProcParams*)lpThreadParameter;
  66. while (true)
  67. {
  68. char buffer[2048];
  69. DWORD bytesRead = 0;
  70. if (::ReadFile(procParams->mReadHandle, buffer, (DWORD)2048, &bytesRead, NULL))
  71. {
  72. DWORD bytesWritten;
  73. ::WriteFile(procParams->mWriteHandle, buffer, bytesRead, &bytesWritten, NULL);
  74. }
  75. else
  76. {
  77. int err = GetLastError();
  78. break;
  79. }
  80. }
  81. return 0;
  82. }
  83. int main()
  84. {
  85. std::string changeListStr = GetEnv("P4_CHANGELIST");
  86. std::string statsFileStr = GetEnv("STATS_FILE");
  87. char* cmdLineStr = ::GetCommandLineA();
  88. DWORD flags = CREATE_DEFAULT_ERROR_MODE;
  89. void* envPtr = NULL;
  90. char* useCmdLineStr = cmdLineStr;
  91. if (cmdLineStr[0] != 0)
  92. {
  93. bool nameQuoted = cmdLineStr[0] == '\"';
  94. std::string passedName;
  95. int i;
  96. for (i = (nameQuoted ? 1 : 0); cmdLineStr[i] != 0; i++)
  97. {
  98. wchar_t c = cmdLineStr[i];
  99. if (((nameQuoted) && (c == '"')) ||
  100. ((!nameQuoted) && (c == ' ')))
  101. {
  102. i++;
  103. break;
  104. }
  105. passedName += cmdLineStr[i];
  106. }
  107. useCmdLineStr += i;
  108. while (*useCmdLineStr == L' ')
  109. useCmdLineStr++;
  110. }
  111. std::string cmdLine = useCmdLineStr;
  112. PROCESS_INFORMATION processInfo;
  113. STARTUPINFOA si;
  114. ZeroMemory(&si, sizeof(si));
  115. si.cb = sizeof(si);
  116. memset(&processInfo, 0, sizeof(processInfo));
  117. si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
  118. HANDLE stdOut;
  119. CreatePipe(stdOut, si.hStdOutput, false);
  120. HANDLE stdErr;
  121. CreatePipe(stdErr, si.hStdError, false);
  122. si.dwFlags = STARTF_USESTDHANDLES;
  123. DWORD startTick = GetTickCount();
  124. BOOL worked = CreateProcessA(NULL, (char*)cmdLine.c_str(), NULL, NULL, TRUE,
  125. flags, envPtr, NULL, &si, &processInfo);
  126. ::CloseHandle(si.hStdOutput);
  127. ::CloseHandle(si.hStdError);
  128. if (!worked)
  129. return 1;
  130. int maxWorkingSet = 0;
  131. DWORD threadId;
  132. ProcParams stdOutParams = { stdOut, GetStdHandle(STD_OUTPUT_HANDLE) };
  133. HANDLE stdOutThread = ::CreateThread(NULL, (SIZE_T)128 * 1024, (LPTHREAD_START_ROUTINE)ReadProc, (void*)&stdOutParams, 0, &threadId);
  134. ProcParams stdErrParams = { stdErr, GetStdHandle(STD_ERROR_HANDLE) };
  135. HANDLE stdErrThread = ::CreateThread(NULL, (SIZE_T)128 * 1024, (LPTHREAD_START_ROUTINE)ReadProc, (void*)&stdErrParams, 0, &threadId);
  136. while (true)
  137. {
  138. if (::WaitForSingleObject(processInfo.hProcess, 20) == WAIT_OBJECT_0)
  139. break;
  140. }
  141. ::WaitForSingleObject(stdOutThread, INFINITE);
  142. ::WaitForSingleObject(stdErrThread, INFINITE);
  143. DWORD exitCode = 0;
  144. ::GetExitCodeProcess(processInfo.hProcess, &exitCode);
  145. int elaspedTime = (int)(GetTickCount() - startTick);
  146. PROCESS_MEMORY_COUNTERS processMemCounters;
  147. processMemCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS);
  148. GetProcessMemoryInfo(processInfo.hProcess, &processMemCounters, sizeof(PROCESS_MEMORY_COUNTERS));
  149. time_t rawtime;
  150. struct tm * timeinfo;
  151. time(&rawtime);
  152. timeinfo = localtime(&rawtime);
  153. //printf("Current local time and date: %s", asctime(timeinfo));
  154. printf("Elapsed Time : %dms\n", elaspedTime);
  155. printf("Working Set : %dk\n", (int)(processMemCounters.PeakWorkingSetSize / 1024));
  156. printf("Virtual Memory: %dk\n", (int)(processMemCounters.PeakPagefileUsage / 1024));
  157. if (!statsFileStr.empty())
  158. {
  159. FILE* fp = fopen(statsFileStr.c_str(), "a+");
  160. if (fp == NULL)
  161. {
  162. fprintf(stderr, "Failed to open stats file: %s\n", statsFileStr.c_str());
  163. return 1;
  164. }
  165. fprintf(fp, "%d-%d-%d %d:%02d:%02d, %s, %d, %d, %d\n",
  166. timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec,
  167. changeListStr.c_str(), elaspedTime, (int)(processMemCounters.PeakWorkingSetSize / 1024), (int)(processMemCounters.PeakPagefileUsage / 1024));
  168. fclose(fp);
  169. }
  170. return exitCode;
  171. }