platform-cocoa.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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 = 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 *pi = [NSProcessInfo processInfo];
  179. SEL sel = @selector(beginActivityWithOptions:reason:);
  180. if (![pi respondsToSelector:sel])
  181. return nil;
  182. //taken from http://stackoverflow.com/a/20100906
  183. id activity = [pi beginActivityWithOptions:0x00FFFFFF reason:@(reason)];
  184. return CFBridgingRetain(activity);
  185. }
  186. }
  187. void os_end_high_performance(os_performance_token_t *token)
  188. {
  189. @autoreleasepool {
  190. NSProcessInfo *pi = [NSProcessInfo processInfo];
  191. SEL sel = @selector(beginActivityWithOptions:reason:);
  192. if (![pi respondsToSelector:sel])
  193. return;
  194. [pi endActivity:CFBridgingRelease(token)];
  195. }
  196. }
  197. struct os_inhibit_info {
  198. CFStringRef reason;
  199. IOPMAssertionID sleep_id;
  200. IOPMAssertionID user_id;
  201. bool active;
  202. };
  203. os_inhibit_t *os_inhibit_sleep_create(const char *reason)
  204. {
  205. struct os_inhibit_info *info = bzalloc(sizeof(*info));
  206. if (!reason)
  207. info->reason = CFStringCreateWithCString(kCFAllocatorDefault, reason, kCFStringEncodingUTF8);
  208. else
  209. info->reason = CFStringCreateCopy(kCFAllocatorDefault, CFSTR(""));
  210. return info;
  211. }
  212. bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active)
  213. {
  214. IOReturn success;
  215. if (!info)
  216. return false;
  217. if (info->active == active)
  218. return false;
  219. if (active) {
  220. IOPMAssertionDeclareUserActivity(info->reason, kIOPMUserActiveLocal, &info->user_id);
  221. success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, info->reason,
  222. &info->sleep_id);
  223. if (success != kIOReturnSuccess) {
  224. blog(LOG_WARNING, "Failed to disable sleep");
  225. return false;
  226. }
  227. } else {
  228. IOPMAssertionRelease(info->sleep_id);
  229. }
  230. info->active = active;
  231. return true;
  232. }
  233. void os_inhibit_sleep_destroy(os_inhibit_t *info)
  234. {
  235. if (info) {
  236. os_inhibit_sleep_set_active(info, false);
  237. CFRelease(info->reason);
  238. bfree(info);
  239. }
  240. }
  241. static int physical_cores = 0;
  242. static int logical_cores = 0;
  243. static bool core_count_initialized = false;
  244. bool os_get_emulation_status(void)
  245. {
  246. #ifdef __aarch64__
  247. return false;
  248. #else
  249. int rosettaTranslated = 0;
  250. size_t size = sizeof(rosettaTranslated);
  251. if (sysctlbyname("sysctl.proc_translated", &rosettaTranslated, &size, NULL, 0) == -1)
  252. return false;
  253. return rosettaTranslated == 1;
  254. #endif
  255. }
  256. static void os_get_cores_internal(void)
  257. {
  258. if (core_count_initialized)
  259. return;
  260. core_count_initialized = true;
  261. size_t size;
  262. int ret;
  263. size = sizeof(physical_cores);
  264. ret = sysctlbyname("machdep.cpu.core_count", &physical_cores, &size, NULL, 0);
  265. if (ret != 0)
  266. return;
  267. ret = sysctlbyname("machdep.cpu.thread_count", &logical_cores, &size, NULL, 0);
  268. }
  269. int os_get_physical_cores(void)
  270. {
  271. if (!core_count_initialized)
  272. os_get_cores_internal();
  273. return physical_cores;
  274. }
  275. int os_get_logical_cores(void)
  276. {
  277. if (!core_count_initialized)
  278. os_get_cores_internal();
  279. return logical_cores;
  280. }
  281. static inline bool os_get_sys_memory_usage_internal(vm_statistics_t vmstat)
  282. {
  283. mach_msg_type_number_t out_count = HOST_VM_INFO_COUNT;
  284. if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t) vmstat, &out_count) != KERN_SUCCESS)
  285. return false;
  286. return true;
  287. }
  288. uint64_t os_get_sys_free_size(void)
  289. {
  290. vm_statistics_data_t vmstat = {};
  291. if (!os_get_sys_memory_usage_internal(&vmstat))
  292. return 0;
  293. return vmstat.free_count * vm_page_size;
  294. }
  295. static uint64_t total_memory = 0;
  296. static bool total_memory_initialized = false;
  297. static void os_get_sys_total_size_internal()
  298. {
  299. total_memory_initialized = true;
  300. size_t size;
  301. int ret;
  302. size = sizeof(total_memory);
  303. ret = sysctlbyname("hw.memsize", &total_memory, &size, NULL, 0);
  304. }
  305. uint64_t os_get_sys_total_size(void)
  306. {
  307. if (!total_memory_initialized)
  308. os_get_sys_total_size_internal();
  309. return total_memory;
  310. }
  311. static inline bool os_get_proc_memory_usage_internal(mach_task_basic_info_data_t *taskinfo)
  312. {
  313. const task_flavor_t flavor = MACH_TASK_BASIC_INFO;
  314. mach_msg_type_number_t out_count = MACH_TASK_BASIC_INFO_COUNT;
  315. if (task_info(mach_task_self(), flavor, (task_info_t) taskinfo, &out_count) != KERN_SUCCESS)
  316. return false;
  317. return true;
  318. }
  319. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  320. {
  321. mach_task_basic_info_data_t taskinfo = {};
  322. if (!os_get_proc_memory_usage_internal(&taskinfo))
  323. return false;
  324. usage->resident_size = taskinfo.resident_size;
  325. usage->virtual_size = taskinfo.virtual_size;
  326. return true;
  327. }
  328. uint64_t os_get_proc_resident_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.resident_size;
  334. }
  335. uint64_t os_get_proc_virtual_size(void)
  336. {
  337. mach_task_basic_info_data_t taskinfo = {};
  338. if (!os_get_proc_memory_usage_internal(&taskinfo))
  339. return 0;
  340. return taskinfo.virtual_size;
  341. }
  342. /* Obtains a copy of the contents of a CFString in specified encoding.
  343. * Returns char* (must be bfree'd by caller) or NULL on failure.
  344. */
  345. char *cfstr_copy_cstr(CFStringRef cfstring, CFStringEncoding cfstring_encoding)
  346. {
  347. if (!cfstring)
  348. return NULL;
  349. // Try the quick way to obtain the buffer
  350. const char *tmp_buffer = CFStringGetCStringPtr(cfstring, cfstring_encoding);
  351. if (tmp_buffer != NULL)
  352. return bstrdup(tmp_buffer);
  353. // The quick way did not work, try the more expensive one
  354. CFIndex length = CFStringGetLength(cfstring);
  355. CFIndex max_size = CFStringGetMaximumSizeForEncoding(length, cfstring_encoding);
  356. // If result would exceed LONG_MAX, kCFNotFound is returned
  357. if (max_size == kCFNotFound)
  358. return NULL;
  359. // Account for the null terminator
  360. max_size++;
  361. char *buffer = bmalloc(max_size);
  362. if (buffer == NULL) {
  363. return NULL;
  364. }
  365. // Copy CFString in requested encoding to buffer
  366. Boolean success = CFStringGetCString(cfstring, buffer, max_size, cfstring_encoding);
  367. if (!success) {
  368. bfree(buffer);
  369. buffer = NULL;
  370. }
  371. return buffer;
  372. }
  373. /* Copies the contents of a CFString in specified encoding to a given dstr.
  374. * Returns true on success or false on failure.
  375. * In case of failure, the dstr capacity but not size is changed.
  376. */
  377. bool cfstr_copy_dstr(CFStringRef cfstring, CFStringEncoding cfstring_encoding, struct dstr *str)
  378. {
  379. if (!cfstring)
  380. return false;
  381. // Try the quick way to obtain the buffer
  382. const char *tmp_buffer = CFStringGetCStringPtr(cfstring, cfstring_encoding);
  383. if (tmp_buffer != NULL) {
  384. dstr_copy(str, tmp_buffer);
  385. return true;
  386. }
  387. // The quick way did not work, try the more expensive one
  388. CFIndex length = CFStringGetLength(cfstring);
  389. CFIndex max_size = CFStringGetMaximumSizeForEncoding(length, cfstring_encoding);
  390. // If result would exceed LONG_MAX, kCFNotFound is returned
  391. if (max_size == kCFNotFound)
  392. return NULL;
  393. // Account for the null terminator
  394. max_size++;
  395. dstr_ensure_capacity(str, max_size);
  396. // Copy CFString in requested encoding to dstr buffer
  397. Boolean success = CFStringGetCString(cfstring, str->array, max_size, cfstring_encoding);
  398. if (success)
  399. dstr_resize(str, max_size);
  400. return (bool) success;
  401. }