platform-cocoa.m 12 KB

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