1/* libio vtable validation.
2 Copyright (C) 2016-2023 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
18
19#include <dlfcn.h>
20#include <libioP.h>
21#include <stdio.h>
22#include <ldsodefs.h>
23#include <pointer_guard.h>
24
25#ifdef SHARED
26
27void (*IO_accept_foreign_vtables) (void) attribute_hidden;
28
29#else /* !SHARED */
30
31/* Used to check whether static dlopen support is needed. */
32# pragma weak __dlopen
33
34#endif
35
36void attribute_hidden
37_IO_vtable_check (void)
38{
39#ifdef SHARED
40 /* Honor the compatibility flag. */
41 void (*flag) (void) = atomic_load_relaxed (&IO_accept_foreign_vtables);
42 PTR_DEMANGLE (flag);
43 if (flag == &_IO_vtable_check)
44 return;
45
46 /* In case this libc copy is in a non-default namespace, we always
47 need to accept foreign vtables because there is always a
48 possibility that FILE * objects are passed across the linking
49 boundary. */
50 {
51 Dl_info di;
52 struct link_map *l;
53 if (!rtld_active ()
54 || (_dl_addr (_IO_vtable_check, &di, &l, NULL) != 0
55 && l->l_ns != LM_ID_BASE))
56 return;
57 }
58
59#else /* !SHARED */
60 /* We cannot perform vtable validation in the static dlopen case
61 because FILE * handles might be passed back and forth across the
62 boundary. Therefore, we disable checking in this case. */
63 if (__dlopen != NULL)
64 return;
65#endif
66
67 __libc_fatal ("Fatal error: glibc detected an invalid stdio handle\n");
68}
69
70/* Some variants of libstdc++ interpose _IO_2_1_stdin_ etc. and
71 install their own vtables directly, without calling _IO_init or
72 other functions. Detect this by looking at the vtables values
73 during startup, and disable vtable validation in this case. */
74#ifdef SHARED
75__attribute__ ((constructor))
76static void
77check_stdfiles_vtables (void)
78{
79 if (_IO_2_1_stdin_.vtable != &_IO_file_jumps
80 || _IO_2_1_stdout_.vtable != &_IO_file_jumps
81 || _IO_2_1_stderr_.vtable != &_IO_file_jumps)
82 IO_set_accept_foreign_vtables (&_IO_vtable_check);
83}
84#endif
85