1/* libio vtable validation.
2 Copyright (C) 2016-2017 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 <http://www.gnu.org/licenses/>. */
18
19#include <dlfcn.h>
20#include <libioP.h>
21#include <stdio.h>
22
23#ifdef SHARED
24
25void (*IO_accept_foreign_vtables) (void) attribute_hidden;
26
27/* Used to detected multiple libcs. */
28extern struct dl_open_hook *_dl_open_hook;
29libc_hidden_proto (_dl_open_hook);
30
31#else /* !SHARED */
32
33/* Used to check whether static dlopen support is needed. */
34# pragma weak __dlopen
35
36#endif
37
38void attribute_hidden
39_IO_vtable_check (void)
40{
41#ifdef SHARED
42 /* Honor the compatibility flag. */
43 void (*flag) (void) = atomic_load_relaxed (&IO_accept_foreign_vtables);
44#ifdef PTR_DEMANGLE
45 PTR_DEMANGLE (flag);
46#endif
47 if (flag == &_IO_vtable_check)
48 return;
49
50 /* In case this libc copy is in a non-default namespace, we always
51 need to accept foreign vtables because there is always a
52 possibility that FILE * objects are passed across the linking
53 boundary. */
54 {
55 Dl_info di;
56 struct link_map *l;
57 if (_dl_open_hook != NULL
58 || (_dl_addr (_IO_vtable_check, &di, &l, NULL) != 0
59 && l->l_ns != LM_ID_BASE))
60 return;
61 }
62
63#else /* !SHARED */
64 /* We cannot perform vtable validation in the static dlopen case
65 because FILE * handles might be passed back and forth across the
66 boundary. Therefore, we disable checking in this case. */
67 if (__dlopen != NULL)
68 return;
69#endif
70
71 __libc_fatal ("Fatal error: glibc detected an invalid stdio handle\n");
72}
73
74/* Some variants of libstdc++ interpose _IO_2_1_stdin_ etc. and
75 install their own vtables directly, without calling _IO_init or
76 other functions. Detect this by looking at the vtables values
77 during startup, and disable vtable validation in this case. */
78#ifdef SHARED
79__attribute__ ((constructor))
80static void
81check_stdfiles_vtables (void)
82{
83 if (_IO_2_1_stdin_.vtable != &_IO_file_jumps
84 || _IO_2_1_stdout_.vtable != &_IO_file_jumps
85 || _IO_2_1_stderr_.vtable != &_IO_file_jumps)
86 IO_set_accept_foreign_vtables (&_IO_vtable_check);
87}
88#endif
89