1 /* Initialization code for TLS in statically linked application.
2    Copyright (C) 2002-2022 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 <startup.h>
20 #include <errno.h>
21 #include <ldsodefs.h>
22 #include <tls.h>
23 #include <unistd.h>
24 #include <stdio.h>
25 #include <sys/param.h>
26 #include <array_length.h>
27 #include <pthreadP.h>
28 
29 #ifdef SHARED
30  #error makefile bug, this file is for static only
31 #endif
32 
33 dtv_t _dl_static_dtv[2 + TLS_SLOTINFO_SURPLUS];
34 
35 
36 static struct dtv_slotinfo_list static_slotinfo =
37   {
38    /* Allocate an array of 2 + TLS_SLOTINFO_SURPLUS elements.  */
39    .slotinfo =  { [array_length (_dl_static_dtv) - 1] = { 0 } },
40   };
41 
42 /* Highest dtv index currently needed.  */
43 size_t _dl_tls_max_dtv_idx;
44 /* Flag signalling whether there are gaps in the module ID allocation.  */
45 bool _dl_tls_dtv_gaps;
46 /* Information about the dtv slots.  */
47 struct dtv_slotinfo_list *_dl_tls_dtv_slotinfo_list;
48 /* Number of modules in the static TLS block.  */
49 size_t _dl_tls_static_nelem;
50 /* Size of the static TLS block.  */
51 size_t _dl_tls_static_size;
52 /* Size actually allocated in the static TLS block.  */
53 size_t _dl_tls_static_used;
54 /* Alignment requirement of the static TLS block.  */
55 size_t _dl_tls_static_align;
56 /* Size of surplus space in the static TLS area for dynamically
57    loaded modules with IE-model TLS or for TLSDESC optimization.
58    See comments in elf/dl-tls.c where it is initialized.  */
59 size_t _dl_tls_static_surplus;
60 /* Remaining amount of static TLS that may be used for optimizing
61    dynamic TLS access (e.g. with TLSDESC).  */
62 size_t _dl_tls_static_optional;
63 
64 /* Generation counter for the dtv.  */
65 size_t _dl_tls_generation;
66 
67 
68 /* Additional definitions needed by TLS initialization.  */
69 #ifdef TLS_INIT_HELPER
70 TLS_INIT_HELPER
71 #endif
72 
73 static void
init_slotinfo(void)74 init_slotinfo (void)
75 {
76   /* Create the slotinfo list.  Note that the type of static_slotinfo
77      has effectively a zero-length array, so we cannot use the size of
78      static_slotinfo to determine the array length.  */
79   static_slotinfo.len = array_length (_dl_static_dtv);
80   /* static_slotinfo.next = NULL; -- Already zero.  */
81 
82   /* The slotinfo list.  Will be extended by the code doing dynamic
83      linking.  */
84   GL(dl_tls_max_dtv_idx) = 1;
85   GL(dl_tls_dtv_slotinfo_list) = &static_slotinfo;
86 }
87 
88 static void
init_static_tls(size_t memsz,size_t align)89 init_static_tls (size_t memsz, size_t align)
90 {
91   /* That is the size of the TLS memory for this object.  */
92   GL(dl_tls_static_size) = roundup (memsz + GLRO(dl_tls_static_surplus),
93 				    TCB_ALIGNMENT);
94 #if TLS_TCB_AT_TP
95   GL(dl_tls_static_size) += TLS_TCB_SIZE;
96 #endif
97   GL(dl_tls_static_used) = memsz;
98   /* The alignment requirement for the static TLS block.  */
99   GL(dl_tls_static_align) = align;
100   /* Number of elements in the static TLS block.  */
101   GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
102 }
103 
104 void
__libc_setup_tls(void)105 __libc_setup_tls (void)
106 {
107   void *tlsblock;
108   size_t memsz = 0;
109   size_t filesz = 0;
110   void *initimage = NULL;
111   size_t align = 0;
112   size_t max_align = TCB_ALIGNMENT;
113   size_t tcb_offset;
114   const ElfW(Phdr) *phdr;
115 
116   struct link_map *main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
117 
118   __tls_pre_init_tp ();
119 
120   /* Look through the TLS segment if there is any.  */
121   if (_dl_phdr != NULL)
122     for (phdr = _dl_phdr; phdr < &_dl_phdr[_dl_phnum]; ++phdr)
123       if (phdr->p_type == PT_TLS)
124 	{
125 	  /* Remember the values we need.  */
126 	  memsz = phdr->p_memsz;
127 	  filesz = phdr->p_filesz;
128 	  initimage = (void *) phdr->p_vaddr + main_map->l_addr;
129 	  align = phdr->p_align;
130 	  if (phdr->p_align > max_align)
131 	    max_align = phdr->p_align;
132 	  break;
133 	}
134 
135   /* Calculate the size of the static TLS surplus, with 0 auditors.  */
136   _dl_tls_static_surplus_init (0);
137 
138   /* We have to set up the TCB block which also (possibly) contains
139      'errno'.  Therefore we avoid 'malloc' which might touch 'errno'.
140      Instead we use 'sbrk' which would only uses 'errno' if it fails.
141      In this case we are right away out of memory and the user gets
142      what she/he deserves.  */
143 #if TLS_TCB_AT_TP
144   /* Align the TCB offset to the maximum alignment, as
145      _dl_allocate_tls_storage (in elf/dl-tls.c) does using __libc_memalign
146      and dl_tls_static_align.  */
147   tcb_offset = roundup (memsz + GLRO(dl_tls_static_surplus), max_align);
148   tlsblock = _dl_early_allocate (tcb_offset + TLS_INIT_TCB_SIZE + max_align);
149   if (tlsblock == NULL)
150     _startup_fatal ("Fatal glibc error: Cannot allocate TLS block\n");
151 #elif TLS_DTV_AT_TP
152   tcb_offset = roundup (TLS_INIT_TCB_SIZE, align ?: 1);
153   tlsblock = _dl_early_allocate (tcb_offset + memsz + max_align
154 				 + TLS_PRE_TCB_SIZE
155 				 + GLRO(dl_tls_static_surplus));
156   if (tlsblock == NULL)
157     _startup_fatal ("Fatal glibc error: Cannot allocate TLS block\n");
158   tlsblock += TLS_PRE_TCB_SIZE;
159 #else
160   /* In case a model with a different layout for the TCB and DTV
161      is defined add another #elif here and in the following #ifs.  */
162 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
163 #endif
164 
165   /* Align the TLS block.  */
166   tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
167 		       & ~(max_align - 1));
168 
169   /* Initialize the dtv.  [0] is the length, [1] the generation counter.  */
170   _dl_static_dtv[0].counter = (sizeof (_dl_static_dtv) / sizeof (_dl_static_dtv[0])) - 2;
171   // _dl_static_dtv[1].counter = 0;		would be needed if not already done
172 
173   /* Initialize the TLS block.  */
174 #if TLS_TCB_AT_TP
175   _dl_static_dtv[2].pointer.val = ((char *) tlsblock + tcb_offset
176 			       - roundup (memsz, align ?: 1));
177   main_map->l_tls_offset = roundup (memsz, align ?: 1);
178 #elif TLS_DTV_AT_TP
179   _dl_static_dtv[2].pointer.val = (char *) tlsblock + tcb_offset;
180   main_map->l_tls_offset = tcb_offset;
181 #else
182 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
183 #endif
184   _dl_static_dtv[2].pointer.to_free = NULL;
185   /* sbrk gives us zero'd memory, so we don't need to clear the remainder.  */
186   memcpy (_dl_static_dtv[2].pointer.val, initimage, filesz);
187 
188   /* Install the pointer to the dtv.  */
189 
190   /* Initialize the thread pointer.  */
191 #if TLS_TCB_AT_TP
192   INSTALL_DTV ((char *) tlsblock + tcb_offset, _dl_static_dtv);
193 
194   const char *lossage = TLS_INIT_TP ((char *) tlsblock + tcb_offset);
195 #elif TLS_DTV_AT_TP
196   INSTALL_DTV (tlsblock, _dl_static_dtv);
197   const char *lossage = TLS_INIT_TP (tlsblock);
198 #else
199 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
200 #endif
201   if (__builtin_expect (lossage != NULL, 0))
202     _startup_fatal (lossage);
203   __tls_init_tp ();
204 
205   /* Update the executable's link map with enough information to make
206      the TLS routines happy.  */
207   main_map->l_tls_align = align;
208   main_map->l_tls_blocksize = memsz;
209   main_map->l_tls_initimage = initimage;
210   main_map->l_tls_initimage_size = filesz;
211   main_map->l_tls_modid = 1;
212 
213   init_slotinfo ();
214   /* static_slotinfo.slotinfo[1].gen = 0; -- Already zero.  */
215   static_slotinfo.slotinfo[1].map = main_map;
216 
217   memsz = roundup (memsz, align ?: 1);
218 
219 #if TLS_DTV_AT_TP
220   memsz += tcb_offset;
221 #endif
222 
223   init_static_tls (memsz, MAX (TCB_ALIGNMENT, max_align));
224 }
225