platform-cocoa.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. /*
  2. * Copyright (c) 2013-2018 Ruwen Hahn <[email protected]>
  3. * Hugh "Jim" 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,
  40. NSSearchPathDomainMask domainMask)
  41. {
  42. NSArray *paths = NSSearchPathForDirectoriesInDomains(
  43. NSApplicationSupportDirectory, domainMask, YES);
  44. if ([paths count] == 0)
  45. bcrash("Could not get home directory (platform-cocoa)");
  46. NSString *application_support = paths[0];
  47. const char *base_path = [application_support UTF8String];
  48. if (!name || !*name)
  49. return snprintf(dst, size, "%s", base_path);
  50. else
  51. return snprintf(dst, size, "%s/%s", base_path, name);
  52. }
  53. static char *os_get_path_ptr_internal(const char *name,
  54. NSSearchPathDomainMask domainMask)
  55. {
  56. NSArray *paths = NSSearchPathForDirectoriesInDomains(
  57. NSApplicationSupportDirectory, domainMask, YES);
  58. if ([paths count] == 0)
  59. bcrash("Could not get home directory (platform-cocoa)");
  60. NSString *application_support = paths[0];
  61. NSUInteger len = [application_support
  62. lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  63. char *path_ptr = bmalloc(len + 1);
  64. path_ptr[len] = 0;
  65. memcpy(path_ptr, [application_support UTF8String], len);
  66. struct dstr path;
  67. dstr_init_move_array(&path, path_ptr);
  68. dstr_cat(&path, "/");
  69. dstr_cat(&path, name);
  70. return path.array;
  71. }
  72. int os_get_config_path(char *dst, size_t size, const char *name)
  73. {
  74. return os_get_path_internal(dst, size, name, NSUserDomainMask);
  75. }
  76. char *os_get_config_path_ptr(const char *name)
  77. {
  78. return os_get_path_ptr_internal(name, NSUserDomainMask);
  79. }
  80. int os_get_program_data_path(char *dst, size_t size, const char *name)
  81. {
  82. return os_get_path_internal(dst, size, name, NSLocalDomainMask);
  83. }
  84. char *os_get_program_data_path_ptr(const char *name)
  85. {
  86. return os_get_path_ptr_internal(name, NSLocalDomainMask);
  87. }
  88. char *os_get_executable_path_ptr(const char *name)
  89. {
  90. char exe[PATH_MAX];
  91. char abs_path[PATH_MAX];
  92. uint32_t size = sizeof(exe);
  93. struct dstr path;
  94. char *slash;
  95. if (_NSGetExecutablePath(exe, &size) != 0) {
  96. return NULL;
  97. }
  98. if (!realpath(exe, abs_path)) {
  99. return NULL;
  100. }
  101. dstr_init_copy(&path, abs_path);
  102. slash = strrchr(path.array, '/');
  103. if (slash) {
  104. size_t len = slash - path.array + 1;
  105. dstr_resize(&path, len);
  106. }
  107. if (name && *name) {
  108. dstr_cat(&path, name);
  109. }
  110. return path.array;
  111. }
  112. struct os_cpu_usage_info {
  113. int64_t last_cpu_time;
  114. int64_t last_sys_time;
  115. int core_count;
  116. };
  117. static inline void add_time_value(time_value_t *dst, time_value_t *a,
  118. time_value_t *b)
  119. {
  120. dst->microseconds = a->microseconds + b->microseconds;
  121. dst->seconds = a->seconds + b->seconds;
  122. if (dst->microseconds >= 1000000) {
  123. dst->seconds += dst->microseconds / 1000000;
  124. dst->microseconds %= 1000000;
  125. }
  126. }
  127. static bool get_time_info(int64_t *cpu_time, int64_t *sys_time)
  128. {
  129. mach_port_t task = mach_task_self();
  130. struct task_thread_times_info thread_data;
  131. struct task_basic_info_64 task_data;
  132. mach_msg_type_number_t count;
  133. kern_return_t kern_ret;
  134. time_value_t cur_time;
  135. *cpu_time = 0;
  136. *sys_time = 0;
  137. count = TASK_THREAD_TIMES_INFO_COUNT;
  138. kern_ret = task_info(task, TASK_THREAD_TIMES_INFO,
  139. (task_info_t)&thread_data, &count);
  140. if (kern_ret != KERN_SUCCESS)
  141. return false;
  142. count = TASK_BASIC_INFO_64_COUNT;
  143. kern_ret = task_info(task, TASK_BASIC_INFO_64, (task_info_t)&task_data,
  144. &count);
  145. if (kern_ret != KERN_SUCCESS)
  146. return false;
  147. add_time_value(&cur_time, &thread_data.user_time,
  148. &thread_data.system_time);
  149. add_time_value(&cur_time, &cur_time, &task_data.user_time);
  150. add_time_value(&cur_time, &cur_time, &task_data.system_time);
  151. *cpu_time = os_gettime_ns() / 1000;
  152. *sys_time = cur_time.seconds * 1000000 + cur_time.microseconds;
  153. return true;
  154. }
  155. os_cpu_usage_info_t *os_cpu_usage_info_start(void)
  156. {
  157. struct os_cpu_usage_info *info = bmalloc(sizeof(*info));
  158. if (!get_time_info(&info->last_cpu_time, &info->last_sys_time)) {
  159. bfree(info);
  160. return NULL;
  161. }
  162. info->core_count = sysconf(_SC_NPROCESSORS_ONLN);
  163. return info;
  164. }
  165. double os_cpu_usage_info_query(os_cpu_usage_info_t *info)
  166. {
  167. int64_t sys_time, cpu_time;
  168. int64_t sys_time_delta, cpu_time_delta;
  169. if (!info || !get_time_info(&cpu_time, &sys_time))
  170. return 0.0;
  171. sys_time_delta = sys_time - info->last_sys_time;
  172. cpu_time_delta = cpu_time - info->last_cpu_time;
  173. if (cpu_time_delta == 0)
  174. return 0.0;
  175. info->last_sys_time = sys_time;
  176. info->last_cpu_time = cpu_time;
  177. return (double)sys_time_delta * 100.0 / (double)cpu_time_delta /
  178. (double)info->core_count;
  179. }
  180. void os_cpu_usage_info_destroy(os_cpu_usage_info_t *info)
  181. {
  182. if (info)
  183. bfree(info);
  184. }
  185. os_performance_token_t *os_request_high_performance(const char *reason)
  186. {
  187. @autoreleasepool {
  188. NSProcessInfo *pi = [NSProcessInfo processInfo];
  189. SEL sel = @selector(beginActivityWithOptions:reason:);
  190. if (![pi respondsToSelector:sel])
  191. return nil;
  192. //taken from http://stackoverflow.com/a/20100906
  193. id activity = [pi beginActivityWithOptions:0x00FFFFFF
  194. reason:@(reason)];
  195. return CFBridgingRetain(activity);
  196. }
  197. }
  198. void os_end_high_performance(os_performance_token_t *token)
  199. {
  200. @autoreleasepool {
  201. NSProcessInfo *pi = [NSProcessInfo processInfo];
  202. SEL sel = @selector(beginActivityWithOptions:reason:);
  203. if (![pi respondsToSelector:sel])
  204. return;
  205. [pi endActivity:CFBridgingRelease(token)];
  206. }
  207. }
  208. struct os_inhibit_info {
  209. CFStringRef reason;
  210. IOPMAssertionID sleep_id;
  211. IOPMAssertionID user_id;
  212. bool active;
  213. };
  214. os_inhibit_t *os_inhibit_sleep_create(const char *reason)
  215. {
  216. struct os_inhibit_info *info = bzalloc(sizeof(*info));
  217. if (!reason)
  218. info->reason = CFStringCreateWithCString(
  219. kCFAllocatorDefault, reason, kCFStringEncodingUTF8);
  220. else
  221. info->reason =
  222. CFStringCreateCopy(kCFAllocatorDefault, CFSTR(""));
  223. return info;
  224. }
  225. bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active)
  226. {
  227. IOReturn success;
  228. if (!info)
  229. return false;
  230. if (info->active == active)
  231. return false;
  232. if (active) {
  233. IOPMAssertionDeclareUserActivity(
  234. info->reason, kIOPMUserActiveLocal, &info->user_id);
  235. success = IOPMAssertionCreateWithName(
  236. kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn,
  237. info->reason, &info->sleep_id);
  238. if (success != kIOReturnSuccess) {
  239. blog(LOG_WARNING, "Failed to disable sleep");
  240. return false;
  241. }
  242. } else {
  243. IOPMAssertionRelease(info->sleep_id);
  244. }
  245. info->active = active;
  246. return true;
  247. }
  248. void os_inhibit_sleep_destroy(os_inhibit_t *info)
  249. {
  250. if (info) {
  251. os_inhibit_sleep_set_active(info, false);
  252. CFRelease(info->reason);
  253. bfree(info);
  254. }
  255. }
  256. static int physical_cores = 0;
  257. static int logical_cores = 0;
  258. static bool core_count_initialized = false;
  259. bool os_get_emulation_status(void)
  260. {
  261. #ifdef __aarch64__
  262. return false;
  263. #else
  264. int rosettaTranslated = 0;
  265. size_t size = sizeof(rosettaTranslated);
  266. if (sysctlbyname("sysctl.proc_translated", &rosettaTranslated, &size,
  267. NULL, 0) == -1)
  268. return false;
  269. return rosettaTranslated == 1;
  270. #endif
  271. }
  272. static void os_get_cores_internal(void)
  273. {
  274. if (core_count_initialized)
  275. return;
  276. core_count_initialized = true;
  277. size_t size;
  278. int ret;
  279. size = sizeof(physical_cores);
  280. ret = sysctlbyname("machdep.cpu.core_count", &physical_cores, &size,
  281. NULL, 0);
  282. if (ret != 0)
  283. return;
  284. ret = sysctlbyname("machdep.cpu.thread_count", &logical_cores, &size,
  285. NULL, 0);
  286. }
  287. int os_get_physical_cores(void)
  288. {
  289. if (!core_count_initialized)
  290. os_get_cores_internal();
  291. return physical_cores;
  292. }
  293. int os_get_logical_cores(void)
  294. {
  295. if (!core_count_initialized)
  296. os_get_cores_internal();
  297. return logical_cores;
  298. }
  299. static inline bool os_get_sys_memory_usage_internal(vm_statistics_t vmstat)
  300. {
  301. mach_msg_type_number_t out_count = HOST_VM_INFO_COUNT;
  302. if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)vmstat,
  303. &out_count) != KERN_SUCCESS)
  304. return false;
  305. return true;
  306. }
  307. uint64_t os_get_sys_free_size(void)
  308. {
  309. vm_statistics_data_t vmstat = {};
  310. if (!os_get_sys_memory_usage_internal(&vmstat))
  311. return 0;
  312. return vmstat.free_count * vm_page_size;
  313. }
  314. static uint64_t total_memory = 0;
  315. static bool total_memory_initialized = false;
  316. static void os_get_sys_total_size_internal()
  317. {
  318. total_memory_initialized = true;
  319. size_t size;
  320. int ret;
  321. size = sizeof(total_memory);
  322. ret = sysctlbyname("hw.memsize", &total_memory, &size, NULL, 0);
  323. }
  324. uint64_t os_get_sys_total_size(void)
  325. {
  326. if (!total_memory_initialized)
  327. os_get_sys_total_size_internal();
  328. return total_memory;
  329. }
  330. #ifndef MACH_TASK_BASIC_INFO
  331. typedef task_basic_info_data_t mach_task_basic_info_data_t;
  332. #endif
  333. static inline bool
  334. os_get_proc_memory_usage_internal(mach_task_basic_info_data_t *taskinfo)
  335. {
  336. #ifdef MACH_TASK_BASIC_INFO
  337. const task_flavor_t flavor = MACH_TASK_BASIC_INFO;
  338. mach_msg_type_number_t out_count = MACH_TASK_BASIC_INFO_COUNT;
  339. #else
  340. const task_flavor_t flavor = TASK_BASIC_INFO;
  341. mach_msg_type_number_t out_count = TASK_BASIC_INFO_COUNT;
  342. #endif
  343. if (task_info(mach_task_self(), flavor, (task_info_t)taskinfo,
  344. &out_count) != KERN_SUCCESS)
  345. return false;
  346. return true;
  347. }
  348. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  349. {
  350. mach_task_basic_info_data_t taskinfo = {};
  351. if (!os_get_proc_memory_usage_internal(&taskinfo))
  352. return false;
  353. usage->resident_size = taskinfo.resident_size;
  354. usage->virtual_size = taskinfo.virtual_size;
  355. return true;
  356. }
  357. uint64_t os_get_proc_resident_size(void)
  358. {
  359. mach_task_basic_info_data_t taskinfo = {};
  360. if (!os_get_proc_memory_usage_internal(&taskinfo))
  361. return 0;
  362. return taskinfo.resident_size;
  363. }
  364. uint64_t os_get_proc_virtual_size(void)
  365. {
  366. mach_task_basic_info_data_t taskinfo = {};
  367. if (!os_get_proc_memory_usage_internal(&taskinfo))
  368. return 0;
  369. return taskinfo.virtual_size;
  370. }
  371. /* Obtains a copy of the contents of a CFString in specified encoding.
  372. * Returns char* (must be bfree'd by caller) or NULL on failure.
  373. */
  374. char *cfstr_copy_cstr(CFStringRef cfstring, CFStringEncoding cfstring_encoding)
  375. {
  376. if (!cfstring)
  377. return NULL;
  378. // Try the quick way to obtain the buffer
  379. const char *tmp_buffer =
  380. CFStringGetCStringPtr(cfstring, cfstring_encoding);
  381. if (tmp_buffer != NULL)
  382. return bstrdup(tmp_buffer);
  383. // The quick way did not work, try the more expensive one
  384. CFIndex length = CFStringGetLength(cfstring);
  385. CFIndex max_size =
  386. CFStringGetMaximumSizeForEncoding(length, cfstring_encoding);
  387. // If result would exceed LONG_MAX, kCFNotFound is returned
  388. if (max_size == kCFNotFound)
  389. return NULL;
  390. // Account for the null terminator
  391. max_size++;
  392. char *buffer = bmalloc(max_size);
  393. if (buffer == NULL) {
  394. return NULL;
  395. }
  396. // Copy CFString in requested encoding to buffer
  397. Boolean success = CFStringGetCString(cfstring, buffer, max_size,
  398. cfstring_encoding);
  399. if (!success) {
  400. bfree(buffer);
  401. buffer = NULL;
  402. }
  403. return buffer;
  404. }
  405. /* Copies the contents of a CFString in specified encoding to a given dstr.
  406. * Returns true on success or false on failure.
  407. * In case of failure, the dstr capacity but not size is changed.
  408. */
  409. bool cfstr_copy_dstr(CFStringRef cfstring, CFStringEncoding cfstring_encoding,
  410. struct dstr *str)
  411. {
  412. if (!cfstring)
  413. return false;
  414. // Try the quick way to obtain the buffer
  415. const char *tmp_buffer =
  416. CFStringGetCStringPtr(cfstring, cfstring_encoding);
  417. if (tmp_buffer != NULL) {
  418. dstr_copy(str, tmp_buffer);
  419. return true;
  420. }
  421. // The quick way did not work, try the more expensive one
  422. CFIndex length = CFStringGetLength(cfstring);
  423. CFIndex max_size =
  424. CFStringGetMaximumSizeForEncoding(length, cfstring_encoding);
  425. // If result would exceed LONG_MAX, kCFNotFound is returned
  426. if (max_size == kCFNotFound)
  427. return NULL;
  428. // Account for the null terminator
  429. max_size++;
  430. dstr_ensure_capacity(str, max_size);
  431. // Copy CFString in requested encoding to dstr buffer
  432. Boolean success = CFStringGetCString(cfstring, str->array, max_size,
  433. cfstring_encoding);
  434. if (success)
  435. dstr_resize(str, max_size);
  436. return (bool)success;
  437. }