1 // Copyright 2023 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "aemu/base/EintrWrapper.h"
16 #include "aemu/base/StringFormat.h"
17 #include "aemu/base/system/System.h"
18 #include "aemu/base/threads/Thread.h"
19 
20 #ifdef _WIN32
21 #include <windows.h>
22 
23 #include "aemu/base/system/Win32UnicodeString.h"
24 #include "aemu/base/msvc.h"
25 #endif
26 
27 #include <vector>
28 
29 #ifdef __QNX__
30 #include <fcntl.h>
31 #include <devctl.h>
32 #include <sys/procfs.h>
33 #endif
34 
35 #ifdef __APPLE__
36 #include <libproc.h>
37 #include <mach/clock.h>
38 #include <mach/mach.h>
39 #endif  // __APPLE__
40 
41 #ifdef _MSC_VER
42 // #include "aemu/base/msvc.h"
43 // #include <dirent.h>
44 #else
45 #include <time.h>
46 #include <sys/time.h>
47 #include <sys/stat.h>
48 #include <sys/types.h>
49 #include <sys/resource.h>
50 #include <unistd.h>
51 #endif
52 
53 #include <string.h>
54 
55 using FileSize = uint64_t;
56 
57 #ifdef _WIN32
58 
59 using android::base::Win32UnicodeString;
60 
61 // Return |path| as a Unicode string, while discarding trailing separators.
win32Path(const char * path)62 Win32UnicodeString win32Path(const char* path) {
63     Win32UnicodeString wpath(path);
64     // Get rid of trailing directory separators, Windows doesn't like them.
65     size_t size = wpath.size();
66     while (size > 0U &&
67            (wpath[size - 1U] == L'\\' || wpath[size - 1U] == L'/')) {
68         size--;
69     }
70     if (size < wpath.size()) {
71         wpath.resize(size);
72     }
73     return wpath;
74 }
75 
76 using PathStat = struct _stat64;
77 
78 #else  // _WIN32
79 
80 using PathStat = struct stat;
81 
82 #endif  // _WIN32
83 
84 namespace {
85 
86 struct TickCountImpl {
87 private:
88     uint64_t mStartTimeUs;
89 #ifdef _WIN32
90     long long mFreqPerSec = 0;    // 0 means 'high perf counter isn't available'
91 #elif defined(__APPLE__)
92     clock_serv_t mClockServ;
93 #endif
94 
95 public:
TickCountImpl__anond7d37e150111::TickCountImpl96     TickCountImpl() {
97 #ifdef _WIN32
98         LARGE_INTEGER freq;
99         if (::QueryPerformanceFrequency(&freq)) {
100             mFreqPerSec = freq.QuadPart;
101         }
102 #elif defined(__APPLE__)
103         host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &mClockServ);
104 #endif
105         mStartTimeUs = getUs();
106     }
107 
108 #ifdef __APPLE__
~TickCountImpl__anond7d37e150111::TickCountImpl109     ~TickCountImpl() {
110         mach_port_deallocate(mach_task_self(), mClockServ);
111     }
112 #endif
113 
getStartTimeUs__anond7d37e150111::TickCountImpl114     uint64_t getStartTimeUs() const {
115         return mStartTimeUs;
116     }
117 
getUs__anond7d37e150111::TickCountImpl118     uint64_t getUs() const {
119 #ifdef _WIN32
120     if (!mFreqPerSec) {
121         return ::GetTickCount() * 1000;
122     }
123     LARGE_INTEGER now;
124     ::QueryPerformanceCounter(&now);
125     return (now.QuadPart * 1000000ULL) / mFreqPerSec;
126 #elif defined __linux__ || defined __QNX__
127     timespec ts;
128     clock_gettime(CLOCK_MONOTONIC, &ts);
129     return ts.tv_sec * 1000000LL + ts.tv_nsec / 1000;
130 #else // APPLE
131     mach_timespec_t mts;
132     clock_get_time(mClockServ, &mts);
133     return mts.tv_sec * 1000000LL + mts.tv_nsec / 1000;
134 #endif
135     }
136 };
137 
138 // This is, maybe, the only static variable that may not be a LazyInstance:
139 // it holds the actual timestamp at startup, and has to be initialized as
140 // soon as possible after the application launch.
141 static const TickCountImpl kTickCount;
142 
143 }  // namespace
144 
145 namespace android {
146 namespace base {
147 
getEnvironmentVariable(const std::string & key)148 std::string getEnvironmentVariable(const std::string& key) {
149 #ifdef _WIN32
150     Win32UnicodeString varname_unicode(key);
151     const wchar_t* value = _wgetenv(varname_unicode.c_str());
152     if (!value) {
153         return std::string();
154     } else {
155         return Win32UnicodeString::convertToUtf8(value);
156     }
157 #else
158     const char* value = getenv(key.c_str());
159     if (!value) {
160         value = "";
161     }
162     return std::string(value);
163 #endif
164 }
165 
setEnvironmentVariable(const std::string & key,const std::string & value)166 void setEnvironmentVariable(const std::string& key, const std::string& value) {
167 #ifdef _WIN32
168     std::string envStr =
169         StringFormat("%s=%s", key, value);
170     // Note: this leaks the result of release().
171     _wputenv(Win32UnicodeString(envStr).release());
172 #else
173     if (value.empty()) {
174         unsetenv(key.c_str());
175     } else {
176         setenv(key.c_str(), value.c_str(), 1);
177     }
178 #endif
179 }
180 
fdStat(int fd,PathStat * st)181 int fdStat(int fd, PathStat* st) {
182 #ifdef _WIN32
183     return _fstat64(fd, st);
184 #else   // !_WIN32
185     return HANDLE_EINTR(fstat(fd, st));
186 #endif  // !_WIN32
187 }
188 
getFileSize(int fd,uint64_t * outFileSize)189 bool getFileSize(int fd, uint64_t* outFileSize) {
190     if (fd < 0) {
191         return false;
192     }
193     PathStat st;
194     int ret = fdStat(fd, &st);
195 #ifdef _WIN32
196     if (ret < 0 || !(st.st_mode & _S_IFREG)) {
197         return false;
198     }
199 #else
200     if (ret < 0 || !S_ISREG(st.st_mode)) {
201         return false;
202     }
203 #endif
204     // This is off_t on POSIX and a 32/64 bit integral type on windows based on
205     // the host / compiler combination. We cast everything to 64 bit unsigned to
206     // play safe.
207     *outFileSize = static_cast<FileSize>(st.st_size);
208     return true;
209 }
210 
sleepMs(uint64_t n)211 void sleepMs(uint64_t n) {
212 #ifdef _WIN32
213     ::Sleep(n);
214 #else
215     usleep(n * 1000);
216 #endif
217 }
218 
sleepUs(uint64_t n)219 void sleepUs(uint64_t n) {
220 #ifdef _WIN32
221     ::Sleep(n / 1000);
222 #else
223     usleep(n);
224 #endif
225 }
226 
sleepToUs(uint64_t absTimeUs)227 void sleepToUs(uint64_t absTimeUs) {
228     // Approach will vary based on platform.
229     //
230     // Linux/QNX has clock_nanosleep with TIMER_ABSTIME which does
231     // exactly what we want, a sleep to some absolute time.
232     //
233     // Mac only has relative nanosleep(), so we'll need to calculate a time
234     // difference.
235     //
236     // Windows has waitable timers. Pre Windows 10 1803, 1 ms was the best resolution. Past that, we can use high resolution waitable timers.
237 #ifdef __APPLE__
238     uint64_t current = getHighResTimeUs();
239 
240     // Already passed deadline, return.
241     if (absTimeUs < current) return;
242     uint64_t diff = absTimeUs - current;
243 
244     struct timespec ts;
245     ts.tv_sec = diff / 1000000ULL;
246     ts.tv_nsec = diff * 1000ULL - ts.tv_sec * 1000000000ULL;
247     int ret;
248     do {
249         ret = nanosleep(&ts, nullptr);
250     } while (ret == -1 && errno == EINTR);
251 #elif defined __linux__ || defined __QNX__
252     struct timespec ts;
253     ts.tv_sec = absTimeUs / 1000000ULL;
254     ts.tv_nsec = absTimeUs * 1000ULL - ts.tv_sec * 1000000000ULL;
255     int ret;
256     do {
257         ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, nullptr);
258     } while (ret == -1 && errno == EINTR);
259 #else // _WIN32
260 
261     // Create a persistent thread local timer object
262     struct ThreadLocalTimerState {
263         ThreadLocalTimerState() {
264             timerHandle = CreateWaitableTimerEx(
265                 nullptr /* no security attributes */,
266                 nullptr /* no timer name */,
267                 CREATE_WAITABLE_TIMER_HIGH_RESOLUTION,
268                 TIMER_ALL_ACCESS);
269 
270             if (!timerHandle) {
271                 // Use an older version of waitable timer as backup.
272                 timerHandle = CreateWaitableTimer(nullptr, FALSE, nullptr);
273             }
274         }
275 
276         ~ThreadLocalTimerState() {
277             if (timerHandle) {
278                 CloseHandle(timerHandle);
279             }
280         }
281 
282         HANDLE timerHandle = 0;
283     };
284 
285     static thread_local ThreadLocalTimerState tl_timerInfo;
286 
287     uint64_t current = getHighResTimeUs();
288     // Already passed deadline, return.
289     if (absTimeUs < current) return;
290     uint64_t diff = absTimeUs - current;
291 
292     // Waitable Timer appraoch
293 
294     // We failed to create ANY usable timer. Sleep instead.
295     if (!tl_timerInfo.timerHandle) {
296         Thread::sleepUs(diff);
297         return;
298     }
299 
300     LARGE_INTEGER dueTime;
301     dueTime.QuadPart = -1LL * diff * 10LL; // 1 us = 1x 100ns
302     SetWaitableTimer(
303         tl_timerInfo.timerHandle,
304         &dueTime,
305         0 /* one shot timer */,
306         0 /* no callback on finish */,
307         NULL /* no arg to completion routine */,
308         FALSE /* no suspend */);
309     WaitForSingleObject(tl_timerInfo.timerHandle, INFINITE);
310 #endif
311 }
312 
getUnixTimeUs()313 uint64_t getUnixTimeUs() {
314     timeval tv;
315     gettimeofday(&tv, nullptr);
316     return tv.tv_sec * 1000000LL + tv.tv_usec;
317 }
318 
getHighResTimeUs()319 uint64_t getHighResTimeUs() {
320     return kTickCount.getUs();
321 }
322 
getUptimeMs()323 uint64_t getUptimeMs() {
324     return (kTickCount.getUs() - kTickCount.getStartTimeUs()) / 1000;
325 }
326 
getProgramDirectoryFromPlatform()327 std::string getProgramDirectoryFromPlatform() {
328     std::string res;
329 #if defined(__linux__)
330     char path[1024];
331     memset(path, 0, sizeof(path));  // happy valgrind!
332     int len = readlink("/proc/self/exe", path, sizeof(path));
333     if (len > 0 && len < (int)sizeof(path)) {
334         char* x = ::strrchr(path, '/');
335         if (x) {
336             *x = '\0';
337             res.assign(path);
338         }
339     }
340 #elif defined(__APPLE__)
341     char s[PATH_MAX];
342     auto pid = getpid();
343     proc_pidpath(pid, s, sizeof(s));
344     char* x = ::strrchr(s, '/');
345     if (x) {
346         // skip all slashes - there might be more than one
347         while (x > s && x[-1] == '/') {
348             --x;
349         }
350         *x = '\0';
351         res.assign(s);
352     } else {
353         res.assign("<unknown-application-dir>");
354     }
355 #elif defined(_WIN32)
356     Win32UnicodeString appDir(PATH_MAX);
357     int len = GetModuleFileNameW(0, appDir.data(), appDir.size());
358     res.assign("<unknown-application-dir>");
359     if (len > 0) {
360         if (len > (int)appDir.size()) {
361             appDir.resize(static_cast<size_t>(len));
362             GetModuleFileNameW(0, appDir.data(), appDir.size());
363         }
364         std::string dir = appDir.toString();
365         char* sep = ::strrchr(&dir[0], '\\');
366         if (sep) {
367             *sep = '\0';
368             res.assign(dir.c_str());
369         }
370     }
371 #elif defined(__QNX__)
372     char path[1024];
373     memset(path, 0, sizeof(path));
374     int fd = open ("/proc/self/exefile", O_RDONLY);
375     if (fd != -1) {
376         ssize_t len = read(fd, path, sizeof(path));
377         if (len > 0 && len < sizeof(path)) {
378             char* x = ::strrchr(path, '/');
379             if (x) {
380                 *x = '\0';
381                 res.assign(path);
382             }
383         }
384         close(fd);
385     }
386 #else
387 #error "Unsupported platform!"
388 #endif
389     return res;
390 }
getProgramDirectory()391 std::string getProgramDirectory() {
392     static std::string progDir;
393     if (progDir.empty()) {
394         progDir.assign(getProgramDirectoryFromPlatform());
395     }
396     return progDir;
397 }
398 
getLauncherDirectory()399 std::string getLauncherDirectory() {
400     return getProgramDirectory();
401 }
402 
403 #ifdef __APPLE__
404 void cpuUsageCurrentThread_macImpl(uint64_t* user, uint64_t* sys);
405 #endif  // __APPLE__
406 
cpuTime()407 CpuTime cpuTime() {
408     CpuTime res;
409 
410     res.wall_time_us = kTickCount.getUs();
411 
412 #ifdef __APPLE__
413     cpuUsageCurrentThread_macImpl(
414         &res.user_time_us,
415         &res.system_time_us);
416 #elif __linux__
417     struct rusage usage;
418     getrusage(RUSAGE_THREAD, &usage);
419     res.user_time_us =
420         usage.ru_utime.tv_sec * 1000000ULL +
421         usage.ru_utime.tv_usec;
422     res.system_time_us =
423         usage.ru_stime.tv_sec * 1000000ULL +
424         usage.ru_stime.tv_usec;
425 #elif __QNX__
426     int fd = open("/proc/self/as", O_RDONLY);
427     if (fd != -1) {
428         procfs_info info;
429         if (devctl(fd, DCMD_PROC_INFO, &info, sizeof(info), NULL) == EOK) {
430             res.user_time_us = info.utime / 1000; // time is in nanoseconds
431             res.system_time_us = info.stime / 1000;
432         }
433         close(fd);
434     }
435 #else // Windows
436     FILETIME creation_time_struct;
437     FILETIME exit_time_struct;
438     FILETIME kernel_time_struct;
439     FILETIME user_time_struct;
440     GetThreadTimes(
441         GetCurrentThread(),
442         &creation_time_struct,
443         &exit_time_struct,
444         &kernel_time_struct,
445         &user_time_struct);
446     (void)creation_time_struct;
447     (void)exit_time_struct;
448     uint64_t user_time_100ns =
449         user_time_struct.dwLowDateTime |
450         ((uint64_t)user_time_struct.dwHighDateTime << 32);
451     uint64_t system_time_100ns =
452         kernel_time_struct.dwLowDateTime |
453         ((uint64_t)kernel_time_struct.dwHighDateTime << 32);
454     res.user_time_us = user_time_100ns / 10;
455     res.system_time_us = system_time_100ns / 10;
456 #endif
457 
458     return res;
459 }
460 
461 
462 #ifdef _WIN32
463 // Based on chromium/src/base/file_version_info_win.cc's CreateFileVersionInfoWin
464 // Currently used to query Vulkan DLL's on the system and blacklist known
465 // problematic DLLs
466 // static
467 // Windows 10 funcs
468 typedef DWORD (*get_file_version_info_size_w_t)(LPCWSTR, LPDWORD);
469 typedef DWORD (*get_file_version_info_w_t)(LPCWSTR, DWORD, DWORD, LPVOID);
470 // Windows 8 funcs
471 typedef DWORD (*get_file_version_info_size_ex_w_t)(DWORD, LPCWSTR, LPDWORD);
472 typedef DWORD (*get_file_version_info_ex_w_t)(DWORD, LPCWSTR, DWORD, DWORD, LPVOID);
473 // common
474 typedef int (*ver_query_value_w_t)(LPCVOID, LPCWSTR, LPVOID, PUINT);
475 static get_file_version_info_size_w_t getFileVersionInfoSizeW_func = 0;
476 static get_file_version_info_w_t getFileVersionInfoW_func = 0;
477 static get_file_version_info_size_ex_w_t getFileVersionInfoSizeExW_func = 0;
478 static get_file_version_info_ex_w_t getFileVersionInfoExW_func = 0;
479 static ver_query_value_w_t verQueryValueW_func = 0;
480 static bool getFileVersionInfoFuncsAvailable = false;
481 static bool getFileVersionInfoExFuncsAvailable = false;
482 static bool canQueryFileVersion = false;
483 
initFileVersionInfoFuncs()484 bool initFileVersionInfoFuncs() {
485     // LOG(VERBOSE) << "querying file version info API...";
486     if (canQueryFileVersion) return true;
487     HMODULE kernelLib = GetModuleHandleA("kernelbase");
488     if (!kernelLib) return false;
489     // LOG(VERBOSE) << "found kernelbase.dll";
490     getFileVersionInfoSizeW_func =
491         (get_file_version_info_size_w_t)GetProcAddress(kernelLib, "GetFileVersionInfoSizeW");
492     if (!getFileVersionInfoSizeW_func) {
493         // LOG(VERBOSE) << "GetFileVersionInfoSizeW not found. Not on Windows 10?";
494     } else {
495         // LOG(VERBOSE) << "GetFileVersionInfoSizeW found. On Windows 10?";
496     }
497     getFileVersionInfoW_func =
498         (get_file_version_info_w_t)GetProcAddress(kernelLib, "GetFileVersionInfoW");
499     if (!getFileVersionInfoW_func) {
500         // LOG(VERBOSE) << "GetFileVersionInfoW not found. Not on Windows 10?";
501     } else {
502         // LOG(VERBOSE) << "GetFileVersionInfoW found. On Windows 10?";
503     }
504     getFileVersionInfoFuncsAvailable =
505         getFileVersionInfoSizeW_func && getFileVersionInfoW_func;
506     if (!getFileVersionInfoFuncsAvailable) {
507         getFileVersionInfoSizeExW_func =
508             (get_file_version_info_size_ex_w_t)GetProcAddress(kernelLib, "GetFileVersionInfoSizeExW");
509         getFileVersionInfoExW_func =
510             (get_file_version_info_ex_w_t)GetProcAddress(kernelLib, "GetFileVersionInfoExW");
511         getFileVersionInfoExFuncsAvailable =
512             getFileVersionInfoSizeExW_func && getFileVersionInfoExW_func;
513     }
514     if (!getFileVersionInfoFuncsAvailable &&
515         !getFileVersionInfoExFuncsAvailable) {
516         // LOG(VERBOSE) << "Cannot get file version info funcs";
517         return false;
518     }
519     verQueryValueW_func =
520         (ver_query_value_w_t)GetProcAddress(kernelLib, "VerQueryValueW");
521     if (!verQueryValueW_func) {
522         // LOG(VERBOSE) << "VerQueryValueW not found";
523         return false;
524     }
525     // LOG(VERBOSE) << "VerQueryValueW found. Can query file versions";
526     canQueryFileVersion = true;
527     return true;
528 }
529 
queryFileVersionInfo(const char * path,int * major,int * minor,int * build_1,int * build_2)530 bool queryFileVersionInfo(const char* path, int* major, int* minor, int* build_1, int* build_2) {
531     if (!initFileVersionInfoFuncs()) return false;
532     if (!canQueryFileVersion) return false;
533     const Win32UnicodeString pathWide(path);
534     DWORD dummy;
535     DWORD length = 0;
536     const DWORD fileVerGetNeutral = 0x02;
537     if (getFileVersionInfoFuncsAvailable) {
538         length = getFileVersionInfoSizeW_func(pathWide.c_str(), &dummy);
539     } else if (getFileVersionInfoExFuncsAvailable) {
540         length = getFileVersionInfoSizeExW_func(fileVerGetNeutral, pathWide.c_str(), &dummy);
541     }
542     if (length == 0) {
543         // LOG(VERBOSE) << "queryFileVersionInfo: path not found: " << path.str().c_str();
544         return false;
545     }
546     std::vector<uint8_t> data(length, 0);
547     if (getFileVersionInfoFuncsAvailable) {
548         if (!getFileVersionInfoW_func(pathWide.c_str(), dummy, length, data.data())) {
549             // LOG(VERBOSE) << "GetFileVersionInfoW failed";
550             return false;
551         }
552     } else if (getFileVersionInfoExFuncsAvailable) {
553         if (!getFileVersionInfoExW_func(fileVerGetNeutral, pathWide.c_str(), dummy, length, data.data())) {
554             // LOG(VERBOSE) << "GetFileVersionInfoExW failed";
555             return false;
556         }
557     }
558     VS_FIXEDFILEINFO* fixedFileInfo = nullptr;
559     UINT fixedFileInfoLength;
560     if (!verQueryValueW_func(
561             data.data(),
562             L"\\",
563             reinterpret_cast<void**>(&fixedFileInfo),
564             &fixedFileInfoLength)) {
565         // LOG(VERBOSE) << "VerQueryValueW failed";
566         return false;
567     }
568     if (major) *major = HIWORD(fixedFileInfo->dwFileVersionMS);
569     if (minor) *minor = LOWORD(fixedFileInfo->dwFileVersionMS);
570     if (build_1) *build_1 = HIWORD(fixedFileInfo->dwFileVersionLS);
571     if (build_2) *build_2 = LOWORD(fixedFileInfo->dwFileVersionLS);
572     return true;
573 }
574 #else
queryFileVersionInfo(const char *,int *,int *,int *,int *)575 bool queryFileVersionInfo(const char*, int*, int*, int*, int*) {
576     return false;
577 }
578 #endif // _WIN32
579 
getCpuCoreCount()580 int getCpuCoreCount() {
581 #ifdef _WIN32
582     SYSTEM_INFO si = {};
583     ::GetSystemInfo(&si);
584     return si.dwNumberOfProcessors < 1 ? 1 : si.dwNumberOfProcessors;
585 #else
586     auto res = (int)sysconf(_SC_NPROCESSORS_ONLN);
587     return res < 1 ? 1 : res;
588 #endif
589 }
590 
591 } // namespace base
592 } // namespace android
593