platform-cocoa.m 13 KB

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