loader: Avoid use-after-free / use of uninitialized local variables
[mesa.git] / src / loader / loader.c
1 /*
2 * Copyright (C) 2013 Rob Clark <robclark@freedesktop.org>
3 * Copyright (C) 2014-2016 Emil Velikov <emil.l.velikov@gmail.com>
4 * Copyright (C) 2016 Intel Corporation
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice (including the next
14 * paragraph) shall be included in all copies or substantial portions of the
15 * Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE.
24 *
25 * Authors:
26 * Rob Clark <robclark@freedesktop.org>
27 */
28
29 #include <dlfcn.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <sys/stat.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <stdbool.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <stdlib.h>
39 #include <limits.h>
40 #include <sys/param.h>
41 #ifdef MAJOR_IN_MKDEV
42 #include <sys/mkdev.h>
43 #endif
44 #ifdef MAJOR_IN_SYSMACROS
45 #include <sys/sysmacros.h>
46 #endif
47 #include <GL/gl.h>
48 #include <GL/internal/dri_interface.h>
49 #include "loader.h"
50
51 #ifdef HAVE_LIBDRM
52 #include <xf86drm.h>
53 #ifdef USE_DRICONF
54 #include "util/xmlconfig.h"
55 #include "util/xmlpool.h"
56 #endif
57 #endif
58
59 #define __IS_LOADER
60 #include "pci_id_driver_map.h"
61
62 static void default_logger(int level, const char *fmt, ...)
63 {
64 if (level <= _LOADER_WARNING) {
65 va_list args;
66 va_start(args, fmt);
67 vfprintf(stderr, fmt, args);
68 va_end(args);
69 }
70 }
71
72 static loader_logger *log_ = default_logger;
73
74 int
75 loader_open_device(const char *device_name)
76 {
77 int fd;
78 #ifdef O_CLOEXEC
79 fd = open(device_name, O_RDWR | O_CLOEXEC);
80 if (fd == -1 && errno == EINVAL)
81 #endif
82 {
83 fd = open(device_name, O_RDWR);
84 if (fd != -1)
85 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
86 }
87 return fd;
88 }
89
90 static char *loader_get_kernel_driver_name(int fd)
91 {
92 #if HAVE_LIBDRM
93 char *driver;
94 drmVersionPtr version = drmGetVersion(fd);
95
96 if (!version) {
97 log_(_LOADER_WARNING, "failed to get driver name for fd %d\n", fd);
98 return NULL;
99 }
100
101 driver = strndup(version->name, version->name_len);
102
103 drmFreeVersion(version);
104 return driver;
105 #else
106 return NULL;
107 #endif
108 }
109
110 #if defined(HAVE_LIBDRM)
111 int
112 loader_open_render_node(const char *name)
113 {
114 drmDevicePtr *devices, device;
115 int err, render = -ENOENT, fd;
116 unsigned int num, i;
117
118 err = drmGetDevices2(0, NULL, 0);
119 if (err < 0)
120 return err;
121
122 num = err;
123
124 devices = calloc(num, sizeof(*devices));
125 if (!devices)
126 return -ENOMEM;
127
128 err = drmGetDevices2(0, devices, num);
129 if (err < 0) {
130 render = err;
131 goto free;
132 }
133
134 for (i = 0; i < num; i++) {
135 device = devices[i];
136
137 if ((device->available_nodes & (1 << DRM_NODE_RENDER)) &&
138 (device->bustype == DRM_BUS_PLATFORM)) {
139 drmVersionPtr version;
140
141 fd = loader_open_device(device->nodes[DRM_NODE_RENDER]);
142 if (fd < 0)
143 continue;
144
145 version = drmGetVersion(fd);
146 if (!version) {
147 close(fd);
148 continue;
149 }
150
151 if (strcmp(version->name, name) != 0) {
152 drmFreeVersion(version);
153 close(fd);
154 continue;
155 }
156
157 drmFreeVersion(version);
158 render = fd;
159 break;
160 }
161 }
162
163 drmFreeDevices(devices, num);
164
165 free:
166 free(devices);
167 return render;
168 }
169
170 #ifdef USE_DRICONF
171 static const char __driConfigOptionsLoader[] =
172 DRI_CONF_BEGIN
173 DRI_CONF_SECTION_INITIALIZATION
174 DRI_CONF_DEVICE_ID_PATH_TAG()
175 DRI_CONF_DRI_DRIVER()
176 DRI_CONF_SECTION_END
177 DRI_CONF_END;
178
179 static char *loader_get_dri_config_driver(int fd)
180 {
181 driOptionCache defaultInitOptions;
182 driOptionCache userInitOptions;
183 char *dri_driver = NULL;
184 char *kernel_driver = loader_get_kernel_driver_name(fd);
185
186 driParseOptionInfo(&defaultInitOptions, __driConfigOptionsLoader);
187 driParseConfigFiles(&userInitOptions, &defaultInitOptions, 0,
188 "loader", kernel_driver, NULL, 0);
189 if (driCheckOption(&userInitOptions, "dri_driver", DRI_STRING)) {
190 char *opt = driQueryOptionstr(&userInitOptions, "dri_driver");
191 /* not an empty string */
192 if (*opt)
193 dri_driver = strdup(opt);
194 }
195 driDestroyOptionCache(&userInitOptions);
196 driDestroyOptionInfo(&defaultInitOptions);
197
198 free(kernel_driver);
199 return dri_driver;
200 }
201
202 static char *loader_get_dri_config_device_id(void)
203 {
204 driOptionCache defaultInitOptions;
205 driOptionCache userInitOptions;
206 char *prime = NULL;
207
208 driParseOptionInfo(&defaultInitOptions, __driConfigOptionsLoader);
209 driParseConfigFiles(&userInitOptions, &defaultInitOptions, 0,
210 "loader", NULL, NULL, 0);
211 if (driCheckOption(&userInitOptions, "device_id", DRI_STRING))
212 prime = strdup(driQueryOptionstr(&userInitOptions, "device_id"));
213 driDestroyOptionCache(&userInitOptions);
214 driDestroyOptionInfo(&defaultInitOptions);
215
216 return prime;
217 }
218 #endif
219
220 static char *drm_construct_id_path_tag(drmDevicePtr device)
221 {
222 char *tag = NULL;
223
224 if (device->bustype == DRM_BUS_PCI) {
225 if (asprintf(&tag, "pci-%04x_%02x_%02x_%1u",
226 device->businfo.pci->domain,
227 device->businfo.pci->bus,
228 device->businfo.pci->dev,
229 device->businfo.pci->func) < 0) {
230 return NULL;
231 }
232 } else if (device->bustype == DRM_BUS_PLATFORM ||
233 device->bustype == DRM_BUS_HOST1X) {
234 char *fullname, *name, *address;
235
236 if (device->bustype == DRM_BUS_PLATFORM)
237 fullname = device->businfo.platform->fullname;
238 else
239 fullname = device->businfo.host1x->fullname;
240
241 name = strrchr(fullname, '/');
242 if (!name)
243 name = strdup(fullname);
244 else
245 name = strdup(name + 1);
246
247 address = strchr(name, '@');
248 if (address) {
249 *address++ = '\0';
250
251 if (asprintf(&tag, "platform-%s_%s", address, name) < 0)
252 tag = NULL;
253 } else {
254 if (asprintf(&tag, "platform-%s", name) < 0)
255 tag = NULL;
256 }
257
258 free(name);
259 }
260 return tag;
261 }
262
263 static bool drm_device_matches_tag(drmDevicePtr device, const char *prime_tag)
264 {
265 char *tag = drm_construct_id_path_tag(device);
266 int ret;
267
268 if (tag == NULL)
269 return false;
270
271 ret = strcmp(tag, prime_tag);
272
273 free(tag);
274 return ret == 0;
275 }
276
277 static char *drm_get_id_path_tag_for_fd(int fd)
278 {
279 drmDevicePtr device;
280 char *tag;
281
282 if (drmGetDevice2(fd, 0, &device) != 0)
283 return NULL;
284
285 tag = drm_construct_id_path_tag(device);
286 drmFreeDevice(&device);
287 return tag;
288 }
289
290 int loader_get_user_preferred_fd(int default_fd, bool *different_device)
291 {
292 /* Arbitrary "maximum" value of drm devices. */
293 #define MAX_DRM_DEVICES 32
294 const char *dri_prime = getenv("DRI_PRIME");
295 char *default_tag, *prime = NULL;
296 drmDevicePtr devices[MAX_DRM_DEVICES];
297 int i, num_devices, fd;
298 bool found = false;
299
300 if (dri_prime)
301 prime = strdup(dri_prime);
302 #ifdef USE_DRICONF
303 else
304 prime = loader_get_dri_config_device_id();
305 #endif
306
307 if (prime == NULL) {
308 *different_device = false;
309 return default_fd;
310 }
311
312 default_tag = drm_get_id_path_tag_for_fd(default_fd);
313 if (default_tag == NULL)
314 goto err;
315
316 num_devices = drmGetDevices2(0, devices, MAX_DRM_DEVICES);
317 if (num_devices < 0)
318 goto err;
319
320 /* two format are supported:
321 * "1": choose any other card than the card used by default.
322 * id_path_tag: (for example "pci-0000_02_00_0") choose the card
323 * with this id_path_tag.
324 */
325 if (!strcmp(prime,"1")) {
326 /* Hmm... detection for 2-7 seems to be broken. Oh well ...
327 * Pick the first render device that is not our own.
328 */
329 for (i = 0; i < num_devices; i++) {
330 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
331 !drm_device_matches_tag(devices[i], default_tag)) {
332
333 found = true;
334 break;
335 }
336 }
337 } else {
338 for (i = 0; i < num_devices; i++) {
339 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
340 drm_device_matches_tag(devices[i], prime)) {
341
342 found = true;
343 break;
344 }
345 }
346 }
347
348 if (!found) {
349 drmFreeDevices(devices, num_devices);
350 goto err;
351 }
352
353 fd = loader_open_device(devices[i]->nodes[DRM_NODE_RENDER]);
354 drmFreeDevices(devices, num_devices);
355 if (fd < 0)
356 goto err;
357
358 close(default_fd);
359
360 *different_device = !!strcmp(default_tag, prime);
361
362 free(default_tag);
363 free(prime);
364 return fd;
365
366 err:
367 *different_device = false;
368
369 free(default_tag);
370 free(prime);
371 return default_fd;
372 }
373 #else
374 int
375 loader_open_render_node(const char *name)
376 {
377 return -1;
378 }
379
380 int loader_get_user_preferred_fd(int default_fd, bool *different_device)
381 {
382 *different_device = false;
383 return default_fd;
384 }
385 #endif
386
387 #if defined(HAVE_LIBDRM)
388
389 static int
390 drm_get_pci_id_for_fd(int fd, int *vendor_id, int *chip_id)
391 {
392 drmDevicePtr device;
393 int ret;
394
395 if (drmGetDevice2(fd, 0, &device) == 0) {
396 if (device->bustype == DRM_BUS_PCI) {
397 *vendor_id = device->deviceinfo.pci->vendor_id;
398 *chip_id = device->deviceinfo.pci->device_id;
399 ret = 1;
400 }
401 else {
402 log_(_LOADER_DEBUG, "MESA-LOADER: device is not located on the PCI bus\n");
403 ret = 0;
404 }
405 drmFreeDevice(&device);
406 }
407 else {
408 log_(_LOADER_WARNING, "MESA-LOADER: failed to retrieve device information\n");
409 ret = 0;
410 }
411
412 return ret;
413 }
414 #endif
415
416
417 int
418 loader_get_pci_id_for_fd(int fd, int *vendor_id, int *chip_id)
419 {
420 #if HAVE_LIBDRM
421 if (drm_get_pci_id_for_fd(fd, vendor_id, chip_id))
422 return 1;
423 #endif
424 return 0;
425 }
426
427 char *
428 loader_get_device_name_for_fd(int fd)
429 {
430 char *result = NULL;
431
432 #if HAVE_LIBDRM
433 result = drmGetDeviceNameFromFd2(fd);
434 #endif
435
436 return result;
437 }
438
439 char *
440 loader_get_driver_for_fd(int fd)
441 {
442 int vendor_id, chip_id, i, j;
443 char *driver = NULL;
444
445 /* Allow an environment variable to force choosing a different driver
446 * binary. If that driver binary can't survive on this FD, that's the
447 * user's problem, but this allows vc4 simulator to run on an i965 host,
448 * and may be useful for some touch testing of i915 on an i965 host.
449 */
450 if (geteuid() == getuid()) {
451 driver = getenv("MESA_LOADER_DRIVER_OVERRIDE");
452 if (driver)
453 return strdup(driver);
454 }
455
456 #if defined(HAVE_LIBDRM) && defined(USE_DRICONF)
457 driver = loader_get_dri_config_driver(fd);
458 if (driver)
459 return driver;
460 #endif
461
462 if (!loader_get_pci_id_for_fd(fd, &vendor_id, &chip_id)) {
463 driver = loader_get_kernel_driver_name(fd);
464 if (driver)
465 log_(_LOADER_INFO, "using driver %s for %d\n", driver, fd);
466 return driver;
467 }
468
469 for (i = 0; driver_map[i].driver; i++) {
470 if (vendor_id != driver_map[i].vendor_id)
471 continue;
472
473 if (driver_map[i].predicate && !driver_map[i].predicate(fd))
474 continue;
475
476 if (driver_map[i].num_chips_ids == -1) {
477 driver = strdup(driver_map[i].driver);
478 goto out;
479 }
480
481 for (j = 0; j < driver_map[i].num_chips_ids; j++)
482 if (driver_map[i].chip_ids[j] == chip_id) {
483 driver = strdup(driver_map[i].driver);
484 goto out;
485 }
486 }
487
488 driver = loader_get_kernel_driver_name(fd);
489 bool is_amdgpu = driver && strcmp(driver, "amdgpu") == 0;
490 free(driver);
491
492 if (is_amdgpu)
493 driver = strdup("radeonsi");
494 else
495 driver = NULL;
496
497 out:
498 log_(driver ? _LOADER_DEBUG : _LOADER_WARNING,
499 "pci id for fd %d: %04x:%04x, driver %s\n",
500 fd, vendor_id, chip_id, driver);
501 return driver;
502 }
503
504 void
505 loader_set_logger(loader_logger *logger)
506 {
507 log_ = logger;
508 }
509
510 char *
511 loader_get_extensions_name(const char *driver_name)
512 {
513 char *name = NULL;
514
515 if (asprintf(&name, "%s_%s", __DRI_DRIVER_GET_EXTENSIONS, driver_name) < 0)
516 return NULL;
517
518 const size_t len = strlen(name);
519 for (size_t i = 0; i < len; i++) {
520 if (name[i] == '-')
521 name[i] = '_';
522 }
523
524 return name;
525 }
526
527 /**
528 * Opens a DRI driver using its driver name, returning the __DRIextension
529 * entrypoints.
530 *
531 * \param driverName - a name like "i965", "radeon", "nouveau", etc.
532 * \param out_driver - Address where the dlopen() return value will be stored.
533 * \param search_path_vars - NULL-terminated list of env vars that can be used
534 * to override the DEFAULT_DRIVER_DIR search path.
535 */
536 const struct __DRIextensionRec **
537 loader_open_driver(const char *driver_name,
538 void **out_driver_handle,
539 const char **search_path_vars)
540 {
541 char path[PATH_MAX], *search_paths, *next, *end;
542 char *get_extensions_name;
543 const struct __DRIextensionRec **extensions = NULL;
544 const struct __DRIextensionRec **(*get_extensions)(void);
545
546 search_paths = NULL;
547 if (geteuid() == getuid() && search_path_vars) {
548 for (int i = 0; search_path_vars[i] != NULL; i++) {
549 search_paths = getenv(search_path_vars[i]);
550 if (search_paths)
551 break;
552 }
553 }
554 if (search_paths == NULL)
555 search_paths = DEFAULT_DRIVER_DIR;
556
557 void *driver = NULL;
558 end = search_paths + strlen(search_paths);
559 for (char *p = search_paths; p < end; p = next + 1) {
560 int len;
561 next = strchr(p, ':');
562 if (next == NULL)
563 next = end;
564
565 len = next - p;
566 #if USE_ELF_TLS
567 snprintf(path, sizeof(path), "%.*s/tls/%s_dri.so", len, p, driver_name);
568 driver = dlopen(path, RTLD_NOW | RTLD_GLOBAL);
569 #endif
570 if (driver == NULL) {
571 snprintf(path, sizeof(path), "%.*s/%s_dri.so", len, p, driver_name);
572 driver = dlopen(path, RTLD_NOW | RTLD_GLOBAL);
573 if (driver == NULL)
574 log_(_LOADER_DEBUG, "MESA-LOADER: failed to open %s: %s\n",
575 path, dlerror());
576 }
577 /* not need continue to loop all paths once the driver is found */
578 if (driver != NULL)
579 break;
580 }
581
582 if (driver == NULL) {
583 log_(_LOADER_WARNING, "MESA-LOADER: failed to open %s (search paths %s)\n",
584 driver_name, search_paths);
585 *out_driver_handle = NULL;
586 return NULL;
587 }
588
589 log_(_LOADER_DEBUG, "MESA-LOADER: dlopen(%s)\n", path);
590
591 get_extensions_name = loader_get_extensions_name(driver_name);
592 if (get_extensions_name) {
593 get_extensions = dlsym(driver, get_extensions_name);
594 if (get_extensions) {
595 extensions = get_extensions();
596 } else {
597 log_(_LOADER_DEBUG, "MESA-LOADER: driver does not expose %s(): %s\n",
598 get_extensions_name, dlerror());
599 }
600 free(get_extensions_name);
601 }
602
603 if (!extensions)
604 extensions = dlsym(driver, __DRI_DRIVER_EXTENSIONS);
605 if (extensions == NULL) {
606 log_(_LOADER_WARNING,
607 "MESA-LOADER: driver exports no extensions (%s)\n", dlerror());
608 dlclose(driver);
609 }
610
611 *out_driver_handle = driver;
612 return extensions;
613 }