platform-cocoa.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. /*
  2. * Copyright (c) 2013-2014 Ruwen Hahn <[email protected]>
  3. * Hugh "Jim" Bailey <[email protected]>
  4. *
  5. * Permission to use, copy, modify, and distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. */
  17. #include "base.h"
  18. #include "platform.h"
  19. #include "dstr.h"
  20. #include <dlfcn.h>
  21. #include <time.h>
  22. #include <unistd.h>
  23. #include <sys/types.h>
  24. #include <sys/sysctl.h>
  25. #include <CoreServices/CoreServices.h>
  26. #include <mach/mach.h>
  27. #include <mach/mach_time.h>
  28. #include <IOKit/pwr_mgt/IOPMLib.h>
  29. #import <Cocoa/Cocoa.h>
  30. /* clock function selection taken from libc++ */
  31. static uint64_t ns_time_simple()
  32. {
  33. return mach_absolute_time();
  34. }
  35. static double ns_time_compute_factor()
  36. {
  37. mach_timebase_info_data_t info = {1, 1};
  38. mach_timebase_info(&info);
  39. return ((double)info.numer) / info.denom;
  40. }
  41. static uint64_t ns_time_full()
  42. {
  43. static double factor = 0.;
  44. if (factor == 0.) factor = ns_time_compute_factor();
  45. return (uint64_t)(mach_absolute_time() * factor);
  46. }
  47. typedef uint64_t (*time_func)();
  48. static time_func ns_time_select_func()
  49. {
  50. mach_timebase_info_data_t info = {1, 1};
  51. mach_timebase_info(&info);
  52. if (info.denom == info.numer)
  53. return ns_time_simple;
  54. return ns_time_full;
  55. }
  56. uint64_t os_gettime_ns(void)
  57. {
  58. static time_func f = NULL;
  59. if (!f) f = ns_time_select_func();
  60. return f();
  61. }
  62. /* gets the location [domain mask]/Library/Application Support/[name] */
  63. static int os_get_path_internal(char *dst, size_t size, const char *name,
  64. NSSearchPathDomainMask domainMask)
  65. {
  66. NSArray *paths = NSSearchPathForDirectoriesInDomains(
  67. NSApplicationSupportDirectory, domainMask, YES);
  68. if([paths count] == 0)
  69. bcrash("Could not get home directory (platform-cocoa)");
  70. NSString *application_support = paths[0];
  71. const char *base_path = [application_support UTF8String];
  72. if (!name || !*name)
  73. return snprintf(dst, size, "%s", base_path);
  74. else
  75. return snprintf(dst, size, "%s/%s", base_path, name);
  76. }
  77. static char *os_get_path_ptr_internal(const char *name,
  78. NSSearchPathDomainMask domainMask)
  79. {
  80. NSArray *paths = NSSearchPathForDirectoriesInDomains(
  81. NSApplicationSupportDirectory, domainMask, YES);
  82. if([paths count] == 0)
  83. bcrash("Could not get home directory (platform-cocoa)");
  84. NSString *application_support = paths[0];
  85. NSUInteger len = [application_support
  86. lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  87. char *path_ptr = bmalloc(len+1);
  88. path_ptr[len] = 0;
  89. memcpy(path_ptr, [application_support UTF8String], len);
  90. struct dstr path;
  91. dstr_init_move_array(&path, path_ptr);
  92. dstr_cat(&path, "/");
  93. dstr_cat(&path, name);
  94. return path.array;
  95. }
  96. int os_get_config_path(char *dst, size_t size, const char *name)
  97. {
  98. return os_get_path_internal(dst, size, name, NSUserDomainMask);
  99. }
  100. char *os_get_config_path_ptr(const char *name)
  101. {
  102. return os_get_path_ptr_internal(name, NSUserDomainMask);
  103. }
  104. int os_get_program_data_path(char *dst, size_t size, const char *name)
  105. {
  106. return os_get_path_internal(dst, size, name, NSLocalDomainMask);
  107. }
  108. char *os_get_program_data_path_ptr(const char *name)
  109. {
  110. return os_get_path_ptr_internal(name, NSLocalDomainMask);
  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,
  144. (task_info_t)&task_data, &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(kCFAllocatorDefault,
  219. reason, kCFStringEncodingUTF8);
  220. else
  221. info->reason = CFStringCreateCopy(kCFAllocatorDefault,
  222. 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(info->reason,
  234. kIOPMUserActiveLocal, &info->user_id);
  235. success = IOPMAssertionCreateWithName(
  236. kIOPMAssertionTypeNoDisplaySleep,
  237. kIOPMAssertionLevelOn, info->reason,
  238. &info->sleep_id);
  239. if (success != kIOReturnSuccess) {
  240. blog(LOG_WARNING, "Failed to disable sleep");
  241. return false;
  242. }
  243. } else {
  244. IOPMAssertionRelease(info->sleep_id);
  245. }
  246. info->active = active;
  247. return true;
  248. }
  249. void os_inhibit_sleep_destroy(os_inhibit_t *info)
  250. {
  251. if (info) {
  252. os_inhibit_sleep_set_active(info, false);
  253. CFRelease(info->reason);
  254. bfree(info);
  255. }
  256. }
  257. static int physical_cores = 0;
  258. static int logical_cores = 0;
  259. static bool core_count_initialized = false;
  260. static void os_get_cores_internal(void)
  261. {
  262. if (core_count_initialized)
  263. return;
  264. core_count_initialized = true;
  265. size_t size;
  266. int ret;
  267. size = sizeof(physical_cores);
  268. ret = sysctlbyname("machdep.cpu.core_count", &physical_cores,
  269. &size, NULL, 0);
  270. if (ret != 0)
  271. return;
  272. ret = sysctlbyname("machdep.cpu.thread_count", &logical_cores,
  273. &size, NULL, 0);
  274. }
  275. int os_get_physical_cores(void)
  276. {
  277. if (!core_count_initialized)
  278. os_get_cores_internal();
  279. return physical_cores;
  280. }
  281. int os_get_logical_cores(void)
  282. {
  283. if (!core_count_initialized)
  284. os_get_cores_internal();
  285. return logical_cores;
  286. }
  287. static inline bool os_get_sys_memory_usage_internal(vm_statistics_t vmstat)
  288. {
  289. mach_msg_type_number_t out_count = HOST_VM_INFO_COUNT;
  290. if (host_statistics(mach_host_self(), HOST_VM_INFO,
  291. (host_info_t)vmstat, &out_count) != KERN_SUCCESS)
  292. return false;
  293. return true;
  294. }
  295. uint64_t os_get_sys_free_size(void)
  296. {
  297. vm_statistics_data_t vmstat = {};
  298. if (!os_get_sys_memory_usage_internal(&vmstat))
  299. return 0;
  300. return vmstat.free_count * vm_page_size;
  301. }
  302. #ifndef MACH_TASK_BASIC_INFO
  303. typedef task_basic_info_data_t mach_task_basic_info_data_t;
  304. #endif
  305. static inline bool os_get_proc_memory_usage_internal(
  306. mach_task_basic_info_data_t *taskinfo)
  307. {
  308. #ifdef MACH_TASK_BASIC_INFO
  309. const task_flavor_t flavor = MACH_TASK_BASIC_INFO;
  310. mach_msg_type_number_t out_count = MACH_TASK_BASIC_INFO_COUNT;
  311. #else
  312. const task_flavor_t flavor = TASK_BASIC_INFO;
  313. mach_msg_type_number_t out_count = TASK_BASIC_INFO_COUNT;
  314. #endif
  315. if (task_info(mach_task_self(), flavor,
  316. (task_info_t)taskinfo, &out_count) != KERN_SUCCESS)
  317. return false;
  318. return true;
  319. }
  320. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  321. {
  322. mach_task_basic_info_data_t taskinfo = {};
  323. if (!os_get_proc_memory_usage_internal(&taskinfo))
  324. return false;
  325. usage->resident_size = taskinfo.resident_size;
  326. usage->virtual_size = taskinfo.virtual_size;
  327. return true;
  328. }
  329. uint64_t os_get_proc_resident_size(void)
  330. {
  331. mach_task_basic_info_data_t taskinfo = {};
  332. if (!os_get_proc_memory_usage_internal(&taskinfo))
  333. return 0;
  334. return taskinfo.resident_size;
  335. }
  336. uint64_t os_get_proc_virtual_size(void)
  337. {
  338. mach_task_basic_info_data_t taskinfo = {};
  339. if (!os_get_proc_memory_usage_internal(&taskinfo))
  340. return 0;
  341. return taskinfo.virtual_size;
  342. }