platform-cocoa.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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 "mac/mac-version.h"
  22. #include <dlfcn.h>
  23. #include <time.h>
  24. #include <unistd.h>
  25. #include <sys/types.h>
  26. #include <sys/param.h>
  27. #include <sys/sysctl.h>
  28. #include <CoreServices/CoreServices.h>
  29. #include <mach/mach.h>
  30. #include <mach/mach_time.h>
  31. #include <mach-o/dyld.h>
  32. #include <IOKit/pwr_mgt/IOPMLib.h>
  33. #import <Cocoa/Cocoa.h>
  34. #include "apple/cfstring-utils.h"
  35. /* clock function selection taken from libc++ */
  36. static uint64_t ns_time_simple()
  37. {
  38. return mach_absolute_time();
  39. }
  40. static double ns_time_compute_factor()
  41. {
  42. mach_timebase_info_data_t info = {1, 1};
  43. mach_timebase_info(&info);
  44. return ((double)info.numer) / info.denom;
  45. }
  46. static uint64_t ns_time_full()
  47. {
  48. static double factor = 0.;
  49. if (factor == 0.) 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) f = ns_time_select_func();
  65. return f();
  66. }
  67. /* gets the location [domain mask]/Library/Application Support/[name] */
  68. static int os_get_path_internal(char *dst, size_t size, const char *name,
  69. NSSearchPathDomainMask domainMask)
  70. {
  71. NSArray *paths = NSSearchPathForDirectoriesInDomains(
  72. NSApplicationSupportDirectory, domainMask, YES);
  73. if([paths count] == 0)
  74. bcrash("Could not get home directory (platform-cocoa)");
  75. NSString *application_support = paths[0];
  76. const char *base_path = [application_support UTF8String];
  77. if (!name || !*name)
  78. return snprintf(dst, size, "%s", base_path);
  79. else
  80. return snprintf(dst, size, "%s/%s", base_path, name);
  81. }
  82. static char *os_get_path_ptr_internal(const char *name,
  83. NSSearchPathDomainMask domainMask)
  84. {
  85. NSArray *paths = NSSearchPathForDirectoriesInDomains(
  86. NSApplicationSupportDirectory, domainMask, YES);
  87. if([paths count] == 0)
  88. bcrash("Could not get home directory (platform-cocoa)");
  89. NSString *application_support = paths[0];
  90. NSUInteger len = [application_support
  91. lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  92. char *path_ptr = bmalloc(len+1);
  93. path_ptr[len] = 0;
  94. memcpy(path_ptr, [application_support UTF8String], len);
  95. struct dstr path;
  96. dstr_init_move_array(&path, path_ptr);
  97. dstr_cat(&path, "/");
  98. dstr_cat(&path, name);
  99. return path.array;
  100. }
  101. int os_get_config_path(char *dst, size_t size, const char *name)
  102. {
  103. return os_get_path_internal(dst, size, name, NSUserDomainMask);
  104. }
  105. char *os_get_config_path_ptr(const char *name)
  106. {
  107. return os_get_path_ptr_internal(name, NSUserDomainMask);
  108. }
  109. int os_get_program_data_path(char *dst, size_t size, const char *name)
  110. {
  111. return os_get_path_internal(dst, size, name, NSLocalDomainMask);
  112. }
  113. char *os_get_program_data_path_ptr(const char *name)
  114. {
  115. return os_get_path_ptr_internal(name, NSLocalDomainMask);
  116. }
  117. char *os_get_executable_path_ptr(const char *name)
  118. {
  119. char exe[PATH_MAX];
  120. char abs_path[PATH_MAX];
  121. uint32_t size = sizeof(exe);
  122. struct dstr path;
  123. char *slash;
  124. if (_NSGetExecutablePath(exe, &size) != 0) {
  125. return NULL;
  126. }
  127. if (!realpath(exe, abs_path)) {
  128. return NULL;
  129. }
  130. dstr_init_copy(&path, abs_path);
  131. slash = strrchr(path.array, '/');
  132. if (slash) {
  133. size_t len = slash - path.array + 1;
  134. dstr_resize(&path, len);
  135. }
  136. if (name && *name) {
  137. dstr_cat(&path, name);
  138. }
  139. return path.array;
  140. }
  141. struct os_cpu_usage_info {
  142. int64_t last_cpu_time;
  143. int64_t last_sys_time;
  144. int core_count;
  145. };
  146. static inline void add_time_value(time_value_t *dst, time_value_t *a,
  147. time_value_t *b)
  148. {
  149. dst->microseconds = a->microseconds + b->microseconds;
  150. dst->seconds = a->seconds + b->seconds;
  151. if (dst->microseconds >= 1000000) {
  152. dst->seconds += dst->microseconds / 1000000;
  153. dst->microseconds %= 1000000;
  154. }
  155. }
  156. static bool get_time_info(int64_t *cpu_time, int64_t *sys_time)
  157. {
  158. mach_port_t task = mach_task_self();
  159. struct task_thread_times_info thread_data;
  160. struct task_basic_info_64 task_data;
  161. mach_msg_type_number_t count;
  162. kern_return_t kern_ret;
  163. time_value_t cur_time;
  164. *cpu_time = 0;
  165. *sys_time = 0;
  166. count = TASK_THREAD_TIMES_INFO_COUNT;
  167. kern_ret = task_info(task, TASK_THREAD_TIMES_INFO,
  168. (task_info_t)&thread_data, &count);
  169. if (kern_ret != KERN_SUCCESS)
  170. return false;
  171. count = TASK_BASIC_INFO_64_COUNT;
  172. kern_ret = task_info(task, TASK_BASIC_INFO_64,
  173. (task_info_t)&task_data, &count);
  174. if (kern_ret != KERN_SUCCESS)
  175. return false;
  176. add_time_value(&cur_time, &thread_data.user_time,
  177. &thread_data.system_time);
  178. add_time_value(&cur_time, &cur_time, &task_data.user_time);
  179. add_time_value(&cur_time, &cur_time, &task_data.system_time);
  180. *cpu_time = os_gettime_ns() / 1000;
  181. *sys_time = cur_time.seconds * 1000000 + cur_time.microseconds;
  182. return true;
  183. }
  184. os_cpu_usage_info_t *os_cpu_usage_info_start(void)
  185. {
  186. struct os_cpu_usage_info *info = bmalloc(sizeof(*info));
  187. if (!get_time_info(&info->last_cpu_time, &info->last_sys_time)) {
  188. bfree(info);
  189. return NULL;
  190. }
  191. info->core_count = sysconf(_SC_NPROCESSORS_ONLN);
  192. return info;
  193. }
  194. double os_cpu_usage_info_query(os_cpu_usage_info_t *info)
  195. {
  196. int64_t sys_time, cpu_time;
  197. int64_t sys_time_delta, cpu_time_delta;
  198. if (!info || !get_time_info(&cpu_time, &sys_time))
  199. return 0.0;
  200. sys_time_delta = sys_time - info->last_sys_time;
  201. cpu_time_delta = cpu_time - info->last_cpu_time;
  202. if (cpu_time_delta == 0)
  203. return 0.0;
  204. info->last_sys_time = sys_time;
  205. info->last_cpu_time = cpu_time;
  206. return (double)sys_time_delta * 100.0 / (double)cpu_time_delta /
  207. (double)info->core_count;
  208. }
  209. void os_cpu_usage_info_destroy(os_cpu_usage_info_t *info)
  210. {
  211. if (info)
  212. bfree(info);
  213. }
  214. os_performance_token_t *os_request_high_performance(const char *reason)
  215. {
  216. @autoreleasepool {
  217. NSProcessInfo *pi = [NSProcessInfo processInfo];
  218. SEL sel = @selector(beginActivityWithOptions:reason:);
  219. if (![pi respondsToSelector:sel])
  220. return nil;
  221. //taken from http://stackoverflow.com/a/20100906
  222. id activity = [pi beginActivityWithOptions:0x00FFFFFF
  223. reason:@(reason)];
  224. return CFBridgingRetain(activity);
  225. }
  226. }
  227. void os_end_high_performance(os_performance_token_t *token)
  228. {
  229. @autoreleasepool {
  230. NSProcessInfo *pi = [NSProcessInfo processInfo];
  231. SEL sel = @selector(beginActivityWithOptions:reason:);
  232. if (![pi respondsToSelector:sel])
  233. return;
  234. [pi endActivity:CFBridgingRelease(token)];
  235. }
  236. }
  237. struct os_inhibit_info {
  238. CFStringRef reason;
  239. IOPMAssertionID sleep_id;
  240. IOPMAssertionID user_id;
  241. bool active;
  242. };
  243. os_inhibit_t *os_inhibit_sleep_create(const char *reason)
  244. {
  245. struct os_inhibit_info *info = bzalloc(sizeof(*info));
  246. if (!reason)
  247. info->reason = CFStringCreateWithCString(kCFAllocatorDefault,
  248. reason, kCFStringEncodingUTF8);
  249. else
  250. info->reason = CFStringCreateCopy(kCFAllocatorDefault,
  251. CFSTR(""));
  252. return info;
  253. }
  254. bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active)
  255. {
  256. IOReturn success;
  257. if (!info)
  258. return false;
  259. if (info->active == active)
  260. return false;
  261. if (active) {
  262. IOPMAssertionDeclareUserActivity(info->reason,
  263. kIOPMUserActiveLocal, &info->user_id);
  264. success = IOPMAssertionCreateWithName(
  265. kIOPMAssertionTypeNoDisplaySleep,
  266. kIOPMAssertionLevelOn, info->reason,
  267. &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,
  298. &size, NULL, 0);
  299. if (ret != 0)
  300. return;
  301. ret = sysctlbyname("machdep.cpu.thread_count", &logical_cores,
  302. &size, 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,
  320. (host_info_t)vmstat, &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 os_get_proc_memory_usage_internal(
  335. 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,
  345. (task_info_t)taskinfo, &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 = CFStringGetCStringPtr(cfstring,
  381. 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 =
  399. CFStringGetCString(cfstring, buffer, max_size, 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,
  411. CFStringEncoding cfstring_encoding, struct dstr *str)
  412. {
  413. if (!cfstring)
  414. return false;
  415. // Try the quick way to obtain the buffer
  416. const char *tmp_buffer = CFStringGetCStringPtr(cfstring,
  417. 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(
  434. cfstring, str->array, max_size, cfstring_encoding);
  435. if (success)
  436. dstr_resize(str, max_size);
  437. return (bool)success;
  438. }
  439. void get_mac_ver(struct mac_version_info *info)
  440. {
  441. static struct mac_version_info ver = {0};
  442. static bool got_version = false;
  443. if (!info)
  444. return;
  445. if (!got_version) {
  446. @autoreleasepool {
  447. NSDictionary *dict = [NSDictionary
  448. dictionaryWithContentsOfFile:
  449. @"/System/Library/CoreServices/"
  450. "SystemVersion.plist"];
  451. NSString *version =
  452. [dict objectForKey:@"ProductVersion"];
  453. const char *str = version.UTF8String;
  454. const char *p = str;
  455. ver.major = atoi(p);
  456. if ((p = strchr(p, '.')) != NULL) {
  457. p++;
  458. ver.minor = atoi(p);
  459. }
  460. if ((p = strchr(p, '.')) != NULL) {
  461. p++;
  462. ver.bug_fix = atoi(p);
  463. }
  464. }
  465. got_version = true;
  466. }
  467. *info = ver;
  468. }