platform-cocoa.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. /*
  2. * Copyright (c) 2023 Ruwen Hahn <[email protected]>
  3. * Lain Bailey <[email protected]>
  4. * Marvin Scholz <[email protected]>
  5. *
  6. * Permission to use, copy, modify, and distribute this software for any
  7. * purpose with or without fee is hereby granted, provided that the above
  8. * copyright notice and this permission notice appear in all copies.
  9. *
  10. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  11. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  12. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  13. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  14. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  15. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  16. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  17. */
  18. #include "base.h"
  19. #include "platform.h"
  20. #include "dstr.h"
  21. #include <dlfcn.h>
  22. #include <time.h>
  23. #include <unistd.h>
  24. #include <sys/types.h>
  25. #include <sys/param.h>
  26. #include <sys/sysctl.h>
  27. #include <CoreServices/CoreServices.h>
  28. #include <mach/mach.h>
  29. #include <mach/mach_time.h>
  30. #include <mach-o/dyld.h>
  31. #include <IOKit/pwr_mgt/IOPMLib.h>
  32. #import <Cocoa/Cocoa.h>
  33. #include "apple/cfstring-utils.h"
  34. uint64_t os_gettime_ns(void)
  35. {
  36. return clock_gettime_nsec_np(CLOCK_UPTIME_RAW);
  37. }
  38. /* gets the location [domain mask]/Library/Application Support/[name] */
  39. static int os_get_path_internal(char *dst, size_t size, const char *name, NSSearchPathDomainMask domainMask)
  40. {
  41. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, domainMask, YES);
  42. if ([paths count] == 0)
  43. bcrash("Could not get home directory (platform-cocoa)");
  44. NSString *application_support = paths[0];
  45. const char *base_path = [application_support UTF8String];
  46. if (!name || !*name)
  47. return snprintf(dst, size, "%s", base_path);
  48. else
  49. return snprintf(dst, size, "%s/%s", base_path, name);
  50. }
  51. static char *os_get_path_ptr_internal(const char *name, NSSearchPathDomainMask domainMask)
  52. {
  53. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, domainMask, YES);
  54. if ([paths count] == 0)
  55. bcrash("Could not get home directory (platform-cocoa)");
  56. NSString *application_support = paths[0];
  57. NSUInteger len = [application_support lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  58. char *path_ptr = bmalloc(len + 1);
  59. path_ptr[len] = 0;
  60. memcpy(path_ptr, [application_support UTF8String], len);
  61. struct dstr path;
  62. dstr_init_move_array(&path, path_ptr);
  63. dstr_cat(&path, "/");
  64. dstr_cat(&path, name);
  65. return path.array;
  66. }
  67. int os_get_config_path(char *dst, size_t size, const char *name)
  68. {
  69. return os_get_path_internal(dst, size, name, NSUserDomainMask);
  70. }
  71. char *os_get_config_path_ptr(const char *name)
  72. {
  73. return os_get_path_ptr_internal(name, NSUserDomainMask);
  74. }
  75. int os_get_program_data_path(char *dst, size_t size, const char *name)
  76. {
  77. return os_get_path_internal(dst, size, name, NSLocalDomainMask);
  78. }
  79. char *os_get_program_data_path_ptr(const char *name)
  80. {
  81. return os_get_path_ptr_internal(name, NSLocalDomainMask);
  82. }
  83. char *os_get_executable_path_ptr(const char *name)
  84. {
  85. char exe[PATH_MAX];
  86. char abs_path[PATH_MAX];
  87. uint32_t size = sizeof(exe);
  88. struct dstr path;
  89. char *slash;
  90. if (_NSGetExecutablePath(exe, &size) != 0) {
  91. return NULL;
  92. }
  93. if (!realpath(exe, abs_path)) {
  94. return NULL;
  95. }
  96. dstr_init_copy(&path, abs_path);
  97. slash = strrchr(path.array, '/');
  98. if (slash) {
  99. size_t len = slash - path.array + 1;
  100. dstr_resize(&path, len);
  101. }
  102. if (name && *name) {
  103. dstr_cat(&path, name);
  104. }
  105. return path.array;
  106. }
  107. struct os_cpu_usage_info {
  108. int64_t last_cpu_time;
  109. int64_t last_sys_time;
  110. int core_count;
  111. };
  112. static inline void add_time_value(time_value_t *dst, time_value_t *a, time_value_t *b)
  113. {
  114. dst->microseconds = a->microseconds + b->microseconds;
  115. dst->seconds = a->seconds + b->seconds;
  116. if (dst->microseconds >= 1000000) {
  117. dst->seconds += dst->microseconds / 1000000;
  118. dst->microseconds %= 1000000;
  119. }
  120. }
  121. static bool get_time_info(int64_t *cpu_time, int64_t *sys_time)
  122. {
  123. mach_port_t task = mach_task_self();
  124. struct task_thread_times_info thread_data;
  125. struct task_basic_info_64 task_data;
  126. mach_msg_type_number_t count;
  127. kern_return_t kern_ret;
  128. time_value_t cur_time;
  129. *cpu_time = 0;
  130. *sys_time = 0;
  131. count = TASK_THREAD_TIMES_INFO_COUNT;
  132. kern_ret = task_info(task, TASK_THREAD_TIMES_INFO, (task_info_t) &thread_data, &count);
  133. if (kern_ret != KERN_SUCCESS)
  134. return false;
  135. count = TASK_BASIC_INFO_64_COUNT;
  136. kern_ret = task_info(task, TASK_BASIC_INFO_64, (task_info_t) &task_data, &count);
  137. if (kern_ret != KERN_SUCCESS)
  138. return false;
  139. add_time_value(&cur_time, &thread_data.user_time, &thread_data.system_time);
  140. add_time_value(&cur_time, &cur_time, &task_data.user_time);
  141. add_time_value(&cur_time, &cur_time, &task_data.system_time);
  142. *cpu_time = os_gettime_ns() / 1000;
  143. *sys_time = cur_time.seconds * 1000000 + cur_time.microseconds;
  144. return true;
  145. }
  146. os_cpu_usage_info_t *os_cpu_usage_info_start(void)
  147. {
  148. struct os_cpu_usage_info *info = bmalloc(sizeof(*info));
  149. if (!get_time_info(&info->last_cpu_time, &info->last_sys_time)) {
  150. bfree(info);
  151. return NULL;
  152. }
  153. info->core_count = (int) sysconf(_SC_NPROCESSORS_ONLN);
  154. return info;
  155. }
  156. double os_cpu_usage_info_query(os_cpu_usage_info_t *info)
  157. {
  158. int64_t sys_time, cpu_time;
  159. int64_t sys_time_delta, cpu_time_delta;
  160. if (!info || !get_time_info(&cpu_time, &sys_time))
  161. return 0.0;
  162. sys_time_delta = sys_time - info->last_sys_time;
  163. cpu_time_delta = cpu_time - info->last_cpu_time;
  164. if (cpu_time_delta == 0)
  165. return 0.0;
  166. info->last_sys_time = sys_time;
  167. info->last_cpu_time = cpu_time;
  168. return (double) sys_time_delta * 100.0 / (double) cpu_time_delta / (double) info->core_count;
  169. }
  170. void os_cpu_usage_info_destroy(os_cpu_usage_info_t *info)
  171. {
  172. if (info)
  173. bfree(info);
  174. }
  175. os_performance_token_t *os_request_high_performance(const char *reason)
  176. {
  177. @autoreleasepool {
  178. NSProcessInfo *processInfo = NSProcessInfo.processInfo;
  179. id activity = [processInfo beginActivityWithOptions:NSActivityUserInitiated reason:@(reason ? reason : "")];
  180. return CFBridgingRetain(activity);
  181. }
  182. }
  183. void os_end_high_performance(os_performance_token_t *token)
  184. {
  185. @autoreleasepool {
  186. NSProcessInfo *processInfo = NSProcessInfo.processInfo;
  187. [processInfo endActivity:CFBridgingRelease(token)];
  188. }
  189. }
  190. struct os_inhibit_info {
  191. CFStringRef reason;
  192. IOPMAssertionID sleep_id;
  193. IOPMAssertionID user_id;
  194. bool active;
  195. };
  196. os_inhibit_t *os_inhibit_sleep_create(const char *reason)
  197. {
  198. struct os_inhibit_info *info = bzalloc(sizeof(*info));
  199. if (!reason)
  200. info->reason = CFStringCreateWithCString(kCFAllocatorDefault, reason, kCFStringEncodingUTF8);
  201. else
  202. info->reason = CFStringCreateCopy(kCFAllocatorDefault, CFSTR(""));
  203. return info;
  204. }
  205. bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active)
  206. {
  207. IOReturn success;
  208. if (!info)
  209. return false;
  210. if (info->active == active)
  211. return false;
  212. if (active) {
  213. IOPMAssertionDeclareUserActivity(info->reason, kIOPMUserActiveLocal, &info->user_id);
  214. success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, info->reason,
  215. &info->sleep_id);
  216. if (success != kIOReturnSuccess) {
  217. blog(LOG_WARNING, "Failed to disable sleep");
  218. return false;
  219. }
  220. } else {
  221. IOPMAssertionRelease(info->sleep_id);
  222. }
  223. info->active = active;
  224. return true;
  225. }
  226. void os_inhibit_sleep_destroy(os_inhibit_t *info)
  227. {
  228. if (info) {
  229. os_inhibit_sleep_set_active(info, false);
  230. CFRelease(info->reason);
  231. bfree(info);
  232. }
  233. }
  234. static int physical_cores = 0;
  235. static int logical_cores = 0;
  236. static bool core_count_initialized = false;
  237. bool os_get_emulation_status(void)
  238. {
  239. #ifdef __aarch64__
  240. return false;
  241. #else
  242. int rosettaTranslated = 0;
  243. size_t size = sizeof(rosettaTranslated);
  244. if (sysctlbyname("sysctl.proc_translated", &rosettaTranslated, &size, NULL, 0) == -1)
  245. return false;
  246. return rosettaTranslated == 1;
  247. #endif
  248. }
  249. static void os_get_cores_internal(void)
  250. {
  251. if (core_count_initialized)
  252. return;
  253. core_count_initialized = true;
  254. size_t size;
  255. int ret;
  256. size = sizeof(physical_cores);
  257. ret = sysctlbyname("machdep.cpu.core_count", &physical_cores, &size, NULL, 0);
  258. if (ret != 0)
  259. return;
  260. ret = sysctlbyname("machdep.cpu.thread_count", &logical_cores, &size, NULL, 0);
  261. }
  262. int os_get_physical_cores(void)
  263. {
  264. if (!core_count_initialized)
  265. os_get_cores_internal();
  266. return physical_cores;
  267. }
  268. int os_get_logical_cores(void)
  269. {
  270. if (!core_count_initialized)
  271. os_get_cores_internal();
  272. return logical_cores;
  273. }
  274. static inline bool os_get_sys_memory_usage_internal(vm_statistics_t vmstat)
  275. {
  276. mach_msg_type_number_t out_count = HOST_VM_INFO_COUNT;
  277. if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t) vmstat, &out_count) != KERN_SUCCESS)
  278. return false;
  279. return true;
  280. }
  281. uint64_t os_get_sys_free_size(void)
  282. {
  283. vm_statistics_data_t vmstat = {};
  284. if (!os_get_sys_memory_usage_internal(&vmstat))
  285. return 0;
  286. return vmstat.free_count * vm_page_size;
  287. }
  288. static uint64_t total_memory = 0;
  289. static bool total_memory_initialized = false;
  290. static void os_get_sys_total_size_internal()
  291. {
  292. total_memory_initialized = true;
  293. size_t size;
  294. int ret;
  295. size = sizeof(total_memory);
  296. ret = sysctlbyname("hw.memsize", &total_memory, &size, NULL, 0);
  297. }
  298. uint64_t os_get_sys_total_size(void)
  299. {
  300. if (!total_memory_initialized)
  301. os_get_sys_total_size_internal();
  302. return total_memory;
  303. }
  304. static inline bool os_get_proc_memory_usage_internal(mach_task_basic_info_data_t *taskinfo)
  305. {
  306. const task_flavor_t flavor = MACH_TASK_BASIC_INFO;
  307. mach_msg_type_number_t out_count = MACH_TASK_BASIC_INFO_COUNT;
  308. if (task_info(mach_task_self(), flavor, (task_info_t) taskinfo, &out_count) != KERN_SUCCESS)
  309. return false;
  310. return true;
  311. }
  312. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  313. {
  314. mach_task_basic_info_data_t taskinfo = {};
  315. if (!os_get_proc_memory_usage_internal(&taskinfo))
  316. return false;
  317. usage->resident_size = taskinfo.resident_size;
  318. usage->virtual_size = taskinfo.virtual_size;
  319. return true;
  320. }
  321. uint64_t os_get_proc_resident_size(void)
  322. {
  323. mach_task_basic_info_data_t taskinfo = {};
  324. if (!os_get_proc_memory_usage_internal(&taskinfo))
  325. return 0;
  326. return taskinfo.resident_size;
  327. }
  328. uint64_t os_get_proc_virtual_size(void)
  329. {
  330. mach_task_basic_info_data_t taskinfo = {};
  331. if (!os_get_proc_memory_usage_internal(&taskinfo))
  332. return 0;
  333. return taskinfo.virtual_size;
  334. }
  335. /* Obtains a copy of the contents of a CFString in specified encoding.
  336. * Returns char* (must be bfree'd by caller) or NULL on failure.
  337. */
  338. char *cfstr_copy_cstr(CFStringRef cfstring, CFStringEncoding cfstring_encoding)
  339. {
  340. if (!cfstring)
  341. return NULL;
  342. // Try the quick way to obtain the buffer
  343. const char *tmp_buffer = CFStringGetCStringPtr(cfstring, cfstring_encoding);
  344. if (tmp_buffer != NULL)
  345. return bstrdup(tmp_buffer);
  346. // The quick way did not work, try the more expensive one
  347. CFIndex length = CFStringGetLength(cfstring);
  348. CFIndex max_size = CFStringGetMaximumSizeForEncoding(length, cfstring_encoding);
  349. // If result would exceed LONG_MAX, kCFNotFound is returned
  350. if (max_size == kCFNotFound)
  351. return NULL;
  352. // Account for the null terminator
  353. max_size++;
  354. char *buffer = bmalloc(max_size);
  355. if (buffer == NULL) {
  356. return NULL;
  357. }
  358. // Copy CFString in requested encoding to buffer
  359. Boolean success = CFStringGetCString(cfstring, buffer, max_size, cfstring_encoding);
  360. if (!success) {
  361. bfree(buffer);
  362. buffer = NULL;
  363. }
  364. return buffer;
  365. }
  366. /* Copies the contents of a CFString in specified encoding to a given dstr.
  367. * Returns true on success or false on failure.
  368. * In case of failure, the dstr capacity but not size is changed.
  369. */
  370. bool cfstr_copy_dstr(CFStringRef cfstring, CFStringEncoding cfstring_encoding, struct dstr *str)
  371. {
  372. if (!cfstring)
  373. return false;
  374. // Try the quick way to obtain the buffer
  375. const char *tmp_buffer = CFStringGetCStringPtr(cfstring, cfstring_encoding);
  376. if (tmp_buffer != NULL) {
  377. dstr_copy(str, tmp_buffer);
  378. return true;
  379. }
  380. // The quick way did not work, try the more expensive one
  381. CFIndex length = CFStringGetLength(cfstring);
  382. CFIndex max_size = CFStringGetMaximumSizeForEncoding(length, cfstring_encoding);
  383. // If result would exceed LONG_MAX, kCFNotFound is returned
  384. if (max_size == kCFNotFound)
  385. return NULL;
  386. // Account for the null terminator
  387. max_size++;
  388. dstr_ensure_capacity(str, max_size);
  389. // Copy CFString in requested encoding to dstr buffer
  390. Boolean success = CFStringGetCString(cfstring, str->array, max_size, cfstring_encoding);
  391. if (success)
  392. dstr_resize(str, max_size);
  393. return (bool) success;
  394. }