1 /**************************************************************************
2 *
3 * Copyright 2008-2010 VMware, Inc.
4 * All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sub license, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
16 * of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21 * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
22 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 *
26 **************************************************************************/
27
28
29 #include "hash_table.h"
30 #include "macros.h"
31 #include "os_misc.h"
32 #include "os_file.h"
33 #include "ralloc.h"
34 #include "simple_mtx.h"
35
36 #include <stdarg.h>
37
38
39 #if DETECT_OS_WINDOWS
40
41 #include <windows.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44
45 #else
46
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <inttypes.h>
51
52 #endif
53
54
55 #if DETECT_OS_ANDROID
56 # define LOG_TAG "MESA"
57 # include <unistd.h>
58 # include <log/log.h>
59 # include <cutils/properties.h>
60 #elif DETECT_OS_LINUX || DETECT_OS_CYGWIN || DETECT_OS_SOLARIS || DETECT_OS_HURD || DETECT_OS_MANAGARM
61 # include <unistd.h>
62 #elif DETECT_OS_OPENBSD || DETECT_OS_FREEBSD
63 # include <sys/resource.h>
64 # include <sys/sysctl.h>
65 #elif DETECT_OS_APPLE || DETECT_OS_BSD
66 # include <sys/sysctl.h>
67 # if DETECT_OS_APPLE
68 # include <mach/mach_host.h>
69 # include <mach/vm_param.h>
70 # include <mach/vm_statistics.h>
71 # endif
72 #elif DETECT_OS_HAIKU
73 # include <kernel/OS.h>
74 #elif DETECT_OS_WINDOWS
75 # include <windows.h>
76 #elif DETECT_OS_FUCHSIA
77 #include <unistd.h>
78 #include <zircon/syscalls.h>
79 #else
80 #error unexpected platform in os_sysinfo.c
81 #endif
82
83
84 void
os_log_message(const char * message)85 os_log_message(const char *message)
86 {
87 /* If the GALLIUM_LOG_FILE environment variable is set to a valid filename,
88 * write all messages to that file.
89 */
90 static FILE *fout = NULL;
91
92 if (!fout) {
93 #if MESA_DEBUG
94 /* one-time init */
95 const char *filename = os_get_option("GALLIUM_LOG_FILE");
96 if (filename) {
97 if (strcmp(filename, "stdout") == 0) {
98 fout = stdout;
99 } else {
100 const char *mode = "w";
101 if (filename[0] == '+') {
102 /* If the filename is prefixed with '+' then open the file for
103 * appending instead of normal writing.
104 */
105 mode = "a";
106 filename++; /* skip the '+' */
107 }
108 fout = fopen(filename, mode);
109 }
110 }
111 #endif
112 if (!fout)
113 fout = stderr;
114 }
115
116 #if DETECT_OS_WINDOWS
117 OutputDebugStringA(message);
118 #if !defined(_GAMING_XBOX)
119 if(GetConsoleWindow() && !IsDebuggerPresent()) {
120 fflush(stdout);
121 fputs(message, fout);
122 fflush(fout);
123 }
124 else if (fout != stderr) {
125 fputs(message, fout);
126 fflush(fout);
127 }
128 #endif
129 #else /* !DETECT_OS_WINDOWS */
130 fflush(stdout);
131 fputs(message, fout);
132 fflush(fout);
133 # if DETECT_OS_ANDROID
134 LOG_PRI(ANDROID_LOG_ERROR, LOG_TAG, "%s", message);
135 # endif
136 #endif
137 }
138
139 #if DETECT_OS_ANDROID
140 # include <ctype.h>
141 # include "c11/threads.h"
142
143 /**
144 * Get an option value from android's property system, as a fallback to
145 * getenv() (which is generally less useful on android due to processes
146 * typically being forked from the zygote.
147 *
148 * The option name used for getenv is translated into a property name
149 * by:
150 *
151 * 1) convert to lowercase
152 * 2) replace '_' with '.'
153 * 3) if necessary, prepend "mesa."
154 *
155 * For example:
156 * - MESA_EXTENSION_OVERRIDE -> mesa.extension.override
157 * - GALLIUM_HUD -> mesa.gallium.hud
158 *
159 */
160 static char *
os_get_android_option(const char * name)161 os_get_android_option(const char *name)
162 {
163 static thread_local char os_android_option_value[PROPERTY_VALUE_MAX];
164 char key[PROPERTY_KEY_MAX];
165 char *p = key, *end = key + PROPERTY_KEY_MAX;
166 /* add "mesa." prefix if necessary: */
167 if (strstr(name, "MESA_") != name)
168 p += strlcpy(p, "mesa.", end - p);
169 p += strlcpy(p, name, end - p);
170 for (int i = 0; key[i]; i++) {
171 if (key[i] == '_') {
172 key[i] = '.';
173 } else {
174 key[i] = tolower(key[i]);
175 }
176 }
177
178 int len = property_get(key, os_android_option_value, NULL);
179 if (len > 1) {
180 return os_android_option_value;
181 }
182 return NULL;
183 }
184 #endif
185
186 #if DETECT_OS_WINDOWS
187
188 /* getenv doesn't necessarily reflect changes to the environment
189 * that have been made during the process lifetime, if either the
190 * setter uses a different CRT (e.g. due to static linking) or the
191 * setter used the Win32 API directly. */
192 const char *
os_get_option(const char * name)193 os_get_option(const char *name)
194 {
195 static thread_local char value[_MAX_ENV];
196 DWORD size = GetEnvironmentVariableA(name, value, _MAX_ENV);
197 return (size > 0 && size < _MAX_ENV) ? value : NULL;
198 }
199
200 #else
201
202 const char *
os_get_option(const char * name)203 os_get_option(const char *name)
204 {
205 const char *opt = getenv(name);
206 #if DETECT_OS_ANDROID
207 if (!opt) {
208 opt = os_get_android_option(name);
209 }
210 #endif
211 return opt;
212 }
213
214 #endif
215
216 static struct hash_table *options_tbl;
217 static bool options_tbl_exited = false;
218 static simple_mtx_t options_tbl_mtx = SIMPLE_MTX_INITIALIZER;
219
220 /**
221 * NOTE: The strings that allocated with ralloc_strdup(options_tbl, ...)
222 * are freed by _mesa_hash_table_destroy automatically
223 */
224 static void
options_tbl_fini(void)225 options_tbl_fini(void)
226 {
227 simple_mtx_lock(&options_tbl_mtx);
228 _mesa_hash_table_destroy(options_tbl, NULL);
229 options_tbl = NULL;
230 options_tbl_exited = true;
231 simple_mtx_unlock(&options_tbl_mtx);
232 }
233
234 const char *
os_get_option_cached(const char * name)235 os_get_option_cached(const char *name)
236 {
237 const char *opt = NULL;
238 simple_mtx_lock(&options_tbl_mtx);
239 if (options_tbl_exited) {
240 opt = os_get_option(name);
241 goto exit_mutex;
242 }
243
244 if (!options_tbl) {
245 options_tbl = _mesa_hash_table_create(NULL, _mesa_hash_string,
246 _mesa_key_string_equal);
247 if (options_tbl == NULL) {
248 goto exit_mutex;
249 }
250 atexit(options_tbl_fini);
251 }
252 struct hash_entry *entry = _mesa_hash_table_search(options_tbl, name);
253 if (entry) {
254 opt = entry->data;
255 goto exit_mutex;
256 }
257
258 char *name_dup = ralloc_strdup(options_tbl, name);
259 if (name_dup == NULL) {
260 goto exit_mutex;
261 }
262 opt = ralloc_strdup(options_tbl, os_get_option(name));
263 _mesa_hash_table_insert(options_tbl, name_dup, (void *)opt);
264 exit_mutex:
265 simple_mtx_unlock(&options_tbl_mtx);
266 return opt;
267 }
268
269 /**
270 * Return the size of the total physical memory.
271 * \param size returns the size of the total physical memory
272 * \return true for success, or false on failure
273 */
274 bool
os_get_total_physical_memory(uint64_t * size)275 os_get_total_physical_memory(uint64_t *size)
276 {
277 #if DETECT_OS_LINUX || DETECT_OS_CYGWIN || DETECT_OS_SOLARIS || DETECT_OS_HURD || DETECT_OS_MANAGARM
278 const long phys_pages = sysconf(_SC_PHYS_PAGES);
279 const long page_size = sysconf(_SC_PAGE_SIZE);
280
281 if (phys_pages <= 0 || page_size <= 0)
282 return false;
283
284 *size = (uint64_t)phys_pages * (uint64_t)page_size;
285 return true;
286 #elif DETECT_OS_APPLE || DETECT_OS_BSD
287 size_t len = sizeof(*size);
288 int mib[2];
289
290 mib[0] = CTL_HW;
291 #if DETECT_OS_APPLE
292 mib[1] = HW_MEMSIZE;
293 #elif DETECT_OS_NETBSD || DETECT_OS_OPENBSD
294 mib[1] = HW_PHYSMEM64;
295 #elif DETECT_OS_FREEBSD
296 mib[1] = HW_REALMEM;
297 #elif DETECT_OS_DRAGONFLY
298 mib[1] = HW_PHYSMEM;
299 #else
300 #error Unsupported *BSD
301 #endif
302
303 return (sysctl(mib, 2, size, &len, NULL, 0) == 0);
304 #elif DETECT_OS_HAIKU
305 system_info info;
306 status_t ret;
307
308 ret = get_system_info(&info);
309 if (ret != B_OK || info.max_pages <= 0)
310 return false;
311
312 *size = (uint64_t)info.max_pages * (uint64_t)B_PAGE_SIZE;
313 return true;
314 #elif DETECT_OS_WINDOWS
315 MEMORYSTATUSEX status;
316 BOOL ret;
317
318 status.dwLength = sizeof(status);
319 ret = GlobalMemoryStatusEx(&status);
320 *size = status.ullTotalPhys;
321 return (ret == true);
322 #elif DETECT_OS_FUCHSIA
323 *size = zx_system_get_physmem();
324 return true;
325 #else
326 #error unexpected platform in os_misc.c
327 return false;
328 #endif
329 }
330
331 bool
os_get_available_system_memory(uint64_t * size)332 os_get_available_system_memory(uint64_t *size)
333 {
334 #if DETECT_OS_LINUX
335 char *meminfo = os_read_file("/proc/meminfo", NULL);
336 if (!meminfo)
337 return false;
338
339 char *str = strstr(meminfo, "MemAvailable:");
340 if (!str) {
341 free(meminfo);
342 return false;
343 }
344
345 uint64_t kb_mem_available;
346 if (sscanf(str, "MemAvailable: %" PRIu64, &kb_mem_available) == 1) {
347 free(meminfo);
348 *size = kb_mem_available << 10;
349 return true;
350 }
351
352 free(meminfo);
353 return false;
354 #elif DETECT_OS_OPENBSD || DETECT_OS_FREEBSD
355 struct rlimit rl;
356 #if DETECT_OS_OPENBSD
357 int mib[] = { CTL_HW, HW_USERMEM64 };
358 #elif DETECT_OS_FREEBSD
359 int mib[] = { CTL_HW, HW_USERMEM };
360 #endif
361 int64_t mem_available;
362 size_t len = sizeof(mem_available);
363
364 /* physmem - wired */
365 if (sysctl(mib, 2, &mem_available, &len, NULL, 0) == -1)
366 return false;
367
368 /* static login.conf limit */
369 if (getrlimit(RLIMIT_DATA, &rl) == -1)
370 return false;
371
372 *size = MIN2(mem_available, rl.rlim_cur);
373 return true;
374 #elif DETECT_OS_WINDOWS
375 MEMORYSTATUSEX status;
376 BOOL ret;
377
378 status.dwLength = sizeof(status);
379 ret = GlobalMemoryStatusEx(&status);
380 *size = status.ullAvailPhys;
381 return (ret == true);
382 #elif DETECT_OS_APPLE
383 vm_statistics64_data_t vm_stats;
384 mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
385 if (host_statistics64(mach_host_self(), HOST_VM_INFO,
386 (host_info64_t)&vm_stats, &count) != KERN_SUCCESS) {
387 return false;
388 }
389
390 *size = ((uint64_t)vm_stats.free_count + (uint64_t)vm_stats.inactive_count) * PAGE_SIZE;
391 return true;
392 #else
393 return false;
394 #endif
395 }
396
397 /**
398 * Return the size of a page
399 * \param size returns the size of a page
400 * \return true for success, or false on failure
401 */
402 bool
os_get_page_size(uint64_t * size)403 os_get_page_size(uint64_t *size)
404 {
405 #if DETECT_OS_POSIX_LITE && !DETECT_OS_APPLE && !DETECT_OS_HAIKU
406 const long page_size = sysconf(_SC_PAGE_SIZE);
407
408 if (page_size <= 0)
409 return false;
410
411 *size = (uint64_t)page_size;
412 return true;
413 #elif DETECT_OS_HAIKU
414 *size = (uint64_t)B_PAGE_SIZE;
415 return true;
416 #elif DETECT_OS_WINDOWS
417 SYSTEM_INFO SysInfo;
418
419 GetSystemInfo(&SysInfo);
420 *size = SysInfo.dwPageSize;
421 return true;
422 #elif DETECT_OS_APPLE
423 *size = PAGE_SIZE;
424 return true;
425 #else
426 #error unexpected platform in os_sysinfo.c
427 return false;
428 #endif
429 }
430