platform-cocoa.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. static void os_get_cores_internal(void)
  260. {
  261. if (core_count_initialized)
  262. return;
  263. core_count_initialized = true;
  264. size_t size;
  265. int ret;
  266. size = sizeof(physical_cores);
  267. ret = sysctlbyname("machdep.cpu.core_count", &physical_cores, &size,
  268. NULL, 0);
  269. if (ret != 0)
  270. return;
  271. ret = sysctlbyname("machdep.cpu.thread_count", &logical_cores, &size,
  272. NULL, 0);
  273. }
  274. int os_get_physical_cores(void)
  275. {
  276. if (!core_count_initialized)
  277. os_get_cores_internal();
  278. return physical_cores;
  279. }
  280. int os_get_logical_cores(void)
  281. {
  282. if (!core_count_initialized)
  283. os_get_cores_internal();
  284. return logical_cores;
  285. }
  286. static inline bool os_get_sys_memory_usage_internal(vm_statistics_t vmstat)
  287. {
  288. mach_msg_type_number_t out_count = HOST_VM_INFO_COUNT;
  289. if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)vmstat,
  290. &out_count) != KERN_SUCCESS)
  291. return false;
  292. return true;
  293. }
  294. uint64_t os_get_sys_free_size(void)
  295. {
  296. vm_statistics_data_t vmstat = {};
  297. if (!os_get_sys_memory_usage_internal(&vmstat))
  298. return 0;
  299. return vmstat.free_count * vm_page_size;
  300. }
  301. #ifndef MACH_TASK_BASIC_INFO
  302. typedef task_basic_info_data_t mach_task_basic_info_data_t;
  303. #endif
  304. static inline bool
  305. os_get_proc_memory_usage_internal(mach_task_basic_info_data_t *taskinfo)
  306. {
  307. #ifdef MACH_TASK_BASIC_INFO
  308. const task_flavor_t flavor = MACH_TASK_BASIC_INFO;
  309. mach_msg_type_number_t out_count = MACH_TASK_BASIC_INFO_COUNT;
  310. #else
  311. const task_flavor_t flavor = TASK_BASIC_INFO;
  312. mach_msg_type_number_t out_count = TASK_BASIC_INFO_COUNT;
  313. #endif
  314. if (task_info(mach_task_self(), flavor, (task_info_t)taskinfo,
  315. &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 =
  351. CFStringGetCStringPtr(cfstring, cfstring_encoding);
  352. if (tmp_buffer != NULL)
  353. return bstrdup(tmp_buffer);
  354. // The quick way did not work, try the more expensive one
  355. CFIndex length = CFStringGetLength(cfstring);
  356. CFIndex max_size =
  357. CFStringGetMaximumSizeForEncoding(length, cfstring_encoding);
  358. // If result would exceed LONG_MAX, kCFNotFound is returned
  359. if (max_size == kCFNotFound)
  360. return NULL;
  361. // Account for the null terminator
  362. max_size++;
  363. char *buffer = bmalloc(max_size);
  364. if (buffer == NULL) {
  365. return NULL;
  366. }
  367. // Copy CFString in requested encoding to buffer
  368. Boolean success = CFStringGetCString(cfstring, buffer, max_size,
  369. cfstring_encoding);
  370. if (!success) {
  371. bfree(buffer);
  372. buffer = NULL;
  373. }
  374. return buffer;
  375. }
  376. /* Copies the contents of a CFString in specified encoding to a given dstr.
  377. * Returns true on success or false on failure.
  378. * In case of failure, the dstr capacity but not size is changed.
  379. */
  380. bool cfstr_copy_dstr(CFStringRef cfstring, CFStringEncoding cfstring_encoding,
  381. struct dstr *str)
  382. {
  383. if (!cfstring)
  384. return false;
  385. // Try the quick way to obtain the buffer
  386. const char *tmp_buffer =
  387. CFStringGetCStringPtr(cfstring, cfstring_encoding);
  388. if (tmp_buffer != NULL) {
  389. dstr_copy(str, tmp_buffer);
  390. return true;
  391. }
  392. // The quick way did not work, try the more expensive one
  393. CFIndex length = CFStringGetLength(cfstring);
  394. CFIndex max_size =
  395. CFStringGetMaximumSizeForEncoding(length, cfstring_encoding);
  396. // If result would exceed LONG_MAX, kCFNotFound is returned
  397. if (max_size == kCFNotFound)
  398. return NULL;
  399. // Account for the null terminator
  400. max_size++;
  401. dstr_ensure_capacity(str, max_size);
  402. // Copy CFString in requested encoding to dstr buffer
  403. Boolean success = CFStringGetCString(cfstring, str->array, max_size,
  404. cfstring_encoding);
  405. if (success)
  406. dstr_resize(str, max_size);
  407. return (bool)success;
  408. }