be0417ca30ad131f7b20b22b36846aeec2debad3
[platform/upstream/linaro-glibc.git] / sysdeps / mach / hurd / dl-sysdep.c
1 /* Operating system support for run-time dynamic linker.  Hurd version.
2 Copyright (C) 1995, 1996 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 Library General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 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 Library General Public License for more details.
14
15 You should have received a copy of the GNU Library General Public
16 License along with the GNU C Library; see the file COPYING.LIB.  If
17 not, write to the Free Software Foundation, Inc., 675 Mass Ave,
18 Cambridge, MA 02139, USA.  */
19
20 #include <hurd.h>
21 #include <link.h>
22 #include <unistd.h>
23 #include <fcntl.h>
24 #include <stdlib.h>
25 #include <sys/mman.h>
26 #include <sys/wait.h>
27 #include <assert.h>
28 #include <sysdep.h>
29 #include <mach/mig_support.h>
30 #include "hurdstartup.h"
31 #include <mach/host_info.h>
32 #include "../stdio-common/_itoa.h"
33 #include <hurd/auth.h>
34 #include <hurd/term.h>
35 #include <stdarg.h>
36 #include <ctype.h>
37
38 #include "dl-machine.h"
39
40 extern void __mach_init (void);
41
42 extern int _dl_argc;
43 extern char **_dl_argv;
44 extern char **_environ;
45
46 struct hurd_startup_data *_dl_hurd_data;
47
48 unsigned int __hurd_threadvar_max = _HURD_THREADVAR_MAX;
49 static unsigned long int threadvars[_HURD_THREADVAR_MAX];
50 unsigned long int __hurd_threadvar_stack_offset
51   = (unsigned long int) &threadvars;
52 unsigned long int __hurd_sigthread_stack_base;
53 unsigned long int __hurd_sigthread_stack_end;
54 unsigned long int *__hurd_sigthread_variables;
55 unsigned long int __hurd_threadvar_stack_mask;
56
57
58 /* XXX loser kludge for vm_map kernel bug */
59 static vm_address_t fmha;
60 static vm_size_t fmhs;
61 static void unfmh(void){
62 __vm_deallocate(__mach_task_self(),fmha,fmhs);}
63 static void fmh(void) {
64     error_t err;int x;mach_port_t p;
65     vm_address_t a=0x08000000U,max=VM_MAX_ADDRESS;
66     while (!(err=__vm_region(__mach_task_self(),&a,&fmhs,&x,&x,&x,&x,&p,&x))){
67       __mach_port_deallocate(__mach_task_self(),p);
68       if (a+fmhs>=0x80000000U){
69         max=a; break;}
70       fmha=a+=fmhs;}
71     if (err) assert(err==KERN_NO_SPACE);
72     if (!fmha)fmhs=0;else{
73     fmhs=max-fmha;
74     err = __vm_map (__mach_task_self (),
75                     &fmha, fmhs, 0, 0, MACH_PORT_NULL, 0, 1,
76                     VM_PROT_NONE, VM_PROT_NONE, VM_INHERIT_COPY);
77     assert_perror(err);}
78   }
79 /* XXX loser kludge for vm_map kernel bug */
80
81
82
83 Elf32_Addr
84 _dl_sysdep_start (void **start_argptr,
85                   void (*dl_main) (const Elf32_Phdr *phdr, Elf32_Word phent,
86                                    Elf32_Addr *user_entry))
87 {
88   extern void _start ();
89
90   void go (int *argdata)
91     {
92       extern unsigned int _dl_skip_args; /* rtld.c */
93       char **p;
94
95       /* Cache the information in various global variables.  */
96       _dl_argc = *argdata;
97       _dl_argv = 1 + (char **) argdata;
98       _environ = &_dl_argv[_dl_argc + 1];
99       for (p = _environ; *p++;); /* Skip environ pointers and terminator.  */
100
101       if ((void *) p == _dl_argv[0])
102         {
103           static struct hurd_startup_data nodata;
104           _dl_hurd_data = &nodata;
105           nodata.user_entry = (vm_address_t) &_start;
106         }
107       else
108         _dl_hurd_data = (void *) p;
109
110       __libc_enable_secure = _dl_hurd_data->flags & EXEC_SECURE;
111
112       if (_dl_hurd_data->flags & EXEC_STACK_ARGS &&
113           _dl_hurd_data->user_entry == 0)
114         _dl_hurd_data->user_entry = (vm_address_t) &_start;
115
116 unfmh();                        /* XXX */
117
118       if (_dl_hurd_data->user_entry == (vm_address_t) &_start)
119         /* We were invoked as a command, not as the program interpreter.
120            The generic ld.so code supports this: it will parse the args
121            as "ld.so PROGRAM [ARGS...]".  For booting the Hurd, we
122            support an additional special syntax:
123              ld.so [-LIBS...] PROGRAM [ARGS...]
124            Each LIBS word consists of "FILENAME=MEMOBJ";
125            for example "-/lib/libc.so=123" says that the contents of
126            /lib/libc.so are found in a memory object whose port name
127            in our task is 123.  */
128         while (_dl_argc > 2 && _dl_argv[1][0] == '-' && _dl_argv[1][1] != '-')
129           {
130             char *lastslash, *memobjname, *p;
131             struct link_map *l;
132             mach_port_t memobj;
133             error_t err;
134
135             ++_dl_skip_args;
136             --_dl_argc;
137             p = _dl_argv++[1] + 1;
138
139             memobjname = strchr (p, '=');
140             if (! memobjname)
141               _dl_sysdep_fatal ("Bogus library spec: ", p, "\n", NULL);
142             *memobjname++ = '\0';
143             memobj = 0;
144             while (*memobjname != '\0')
145               memobj = (memobj * 10) + (*memobjname++ - '0');
146
147             /* Add a user reference on the memory object port, so we will
148                still have one after _dl_map_object_from_fd calls our
149                `close'.  */
150             err = __mach_port_mod_refs (__mach_task_self (), memobj,
151                                         MACH_PORT_RIGHT_SEND, +1);
152             assert_perror (err);
153
154             lastslash = strrchr (p, '/');
155             l = _dl_map_object_from_fd (lastslash ? lastslash + 1 : p,
156                                         memobj, strdup (p));
157
158             /* Squirrel away the memory object port where it
159                can be retrieved by the program later.  */
160             l->l_info[DT_NULL] = (void *) memobj;
161           }
162
163       /* Call elf/rtld.c's main program.  It will set everything
164          up and leave us to transfer control to USER_ENTRY.  */
165       (*dl_main) ((const Elf32_Phdr *) _dl_hurd_data->phdr,
166                   _dl_hurd_data->phdrsz / sizeof (Elf32_Phdr),
167                   &_dl_hurd_data->user_entry);
168
169       if (_dl_skip_args && _dl_argv[-_dl_skip_args] == (char *) p)
170         {
171           /* We are ignoring the first few arguments, but we have no Hurd
172              startup data.  It is magical convention that ARGV[0] == P in
173              this case.  The startup code in init-first.c will get confused
174              if this is not the case, so we must rearrange things to make
175              it so.  Overwrite the original ARGV[0] at P with
176              ARGV[_dl_skip_args].  */
177           assert ((char *) p < _dl_argv[0]);
178           _dl_argv[0] = strcpy ((char *) p, _dl_argv[0]);
179         }
180
181       {
182         extern void _dl_start_user (void);
183         /* Unwind the stack to ARGDATA and simulate a return from _dl_start
184            to the RTLD_START code which will run the user's entry point.  */
185         RETURN_TO (argdata, &_dl_start_user, _dl_hurd_data->user_entry);
186       }
187     }
188
189   /* Set up so we can do RPCs.  */
190   __mach_init ();
191
192 fmh();                          /* XXX */
193
194   /* See hurd/hurdstartup.c; this deals with getting information
195      from the exec server and slicing up the arguments.
196      Then it will call `go', above.  */
197   _hurd_startup (start_argptr, &go);
198
199   LOSE;
200   abort ();
201 }
202
203 void
204 _dl_sysdep_start_cleanup (void)
205 {
206   /* Deallocate the reply port and task port rights acquired by
207      __mach_init.  We are done with them now, and the user will
208      reacquire them for himself when he wants them.  */
209   __mig_dealloc_reply_port (MACH_PORT_NULL);
210   __mach_port_deallocate (__mach_task_self (), __mach_task_self_);
211 }
212 \f
213 void
214 _dl_sysdep_fatal (const char *msg, ...)
215 {
216   va_list ap;
217
218   va_start (ap, msg);
219   do
220     {
221       size_t len = strlen (msg);
222       mach_msg_type_number_t nwrote;
223       do
224         {
225           if (__io_write (_hurd_init_dtable[2], msg, len, -1, &nwrote))
226             break;
227           len -= nwrote;
228           msg += nwrote;
229         } while (nwrote > 0);
230       msg = va_arg (ap, const char *);
231     } while (msg);
232   va_end (ap);
233
234   _exit (127);
235 }
236
237
238 void
239 _dl_sysdep_message (const char *msg, ...)
240 {
241   va_list ap;
242
243   va_start (ap, msg);
244   do
245     {
246       size_t len = strlen (msg);
247       mach_msg_type_number_t nwrote;
248       do
249         {
250           if (__io_write (_hurd_init_dtable[1], msg, len, -1, &nwrote))
251             break;
252           len -= nwrote;
253           msg += nwrote;
254         } while (nwrote > 0);
255       msg = va_arg (ap, const char *);
256     } while (msg);
257   va_end (ap);
258 }
259 \f
260 /* Minimal open/close/mmap implementation sufficient for initial loading of
261    shared libraries.  These are weak definitions so that when the
262    dynamic linker re-relocates itself to be user-visible (for -ldl),
263    it will get the user's definition (i.e. usually libc's).  */
264
265 int weak_function
266 __open (const char *file_name, int mode, ...)
267 {
268   enum retry_type doretry;
269   char retryname[1024];         /* XXX string_t LOSES! */
270   file_t startdir, newpt, fileport;
271   int dealloc_dir;
272   int nloops;
273   error_t err;
274
275   assert (mode == O_RDONLY);
276
277   startdir = _dl_hurd_data->portarray[file_name[0] == '/' ?
278                                       INIT_PORT_CRDIR : INIT_PORT_CWDIR];
279
280   while (file_name[0] == '/')
281     file_name++;
282
283   if (err = __dir_lookup (startdir, file_name, mode, 0,
284                           &doretry, retryname, &fileport))
285     return __hurd_fail (err);
286
287   dealloc_dir = 0;
288   nloops = 0;
289
290   while (1)
291     {
292       if (dealloc_dir)
293         __mach_port_deallocate (__mach_task_self (), startdir);
294       if (err)
295         return __hurd_fail (err);
296
297       switch (doretry)
298         {
299         case FS_RETRY_REAUTH:
300           {
301             mach_port_t ref = __mach_reply_port ();
302             err = __io_reauthenticate (fileport, ref, MACH_MSG_TYPE_MAKE_SEND);
303             if (! err)
304               err = __auth_user_authenticate
305                 (_dl_hurd_data->portarray[INIT_PORT_AUTH],
306                  ref, MACH_MSG_TYPE_MAKE_SEND,
307                  &newpt);
308             __mach_port_destroy (__mach_task_self (), ref);
309           }
310           __mach_port_deallocate (__mach_task_self (), fileport);
311           if (err)
312             return __hurd_fail (err);
313           fileport = newpt;
314           /* Fall through.  */
315
316         case FS_RETRY_NORMAL:
317 #ifdef SYMLOOP_MAX
318           if (nloops++ >= SYMLOOP_MAX)
319             return __hurd_fail (ELOOP);
320 #endif
321
322           /* An empty RETRYNAME indicates we have the final port.  */
323           if (retryname[0] == '\0')
324             {
325               mach_port_t memobj_rd, memobj_wr;
326
327               dealloc_dir = 1;
328
329             opened:
330               /* We have the file open.  Now map it.  */
331               err = __io_map (fileport, &memobj_rd, &memobj_wr);
332               if (dealloc_dir)
333                 __mach_port_deallocate (__mach_task_self (), fileport);
334               if (err)
335                 return __hurd_fail (err);
336               if (memobj_wr != MACH_PORT_NULL)
337                 __mach_port_deallocate (__mach_task_self (), memobj_wr);
338
339               return (int) memobj_rd;
340             }
341
342           startdir = fileport;
343           dealloc_dir = 1;
344           file_name = retryname;
345           break;
346
347         case FS_RETRY_MAGICAL:
348           switch (retryname[0])
349             {
350             case '/':
351               startdir = _dl_hurd_data->portarray[INIT_PORT_CRDIR];
352               dealloc_dir = 0;
353               if (fileport != MACH_PORT_NULL)
354                 __mach_port_deallocate (__mach_task_self (), fileport);
355               file_name = &retryname[1];
356               break;
357
358             case 'f':
359               if (retryname[1] == 'd' && retryname[2] == '/' &&
360                   isdigit (retryname[3]))
361                 {
362                   /* We can't use strtol for the decoding here
363                      because it brings in hairy locale bloat.  */
364                   char *p;
365                   int fd = 0;
366                   for (p = &retryname[3]; isdigit (*p); ++p)
367                     fd = (fd * 10) + (*p - '0');
368                   /* Check for excess text after the number.  A slash is
369                      valid; it ends the component.  Anything else does not
370                      name a numeric file descriptor.  */
371                   if (*p != '/' && *p != '\0')
372                     return __hurd_fail (ENOENT);
373                   if (fd < 0 || fd >= _dl_hurd_data->dtablesize ||
374                       _dl_hurd_data->dtable[fd] == MACH_PORT_NULL)
375                     /* If the name was a proper number, but the file
376                        descriptor does not exist, we return EBADF instead
377                        of ENOENT.  */
378                     return __hurd_fail (EBADF);
379                   fileport = _dl_hurd_data->dtable[fd];
380                   if (*p == '\0')
381                     {
382                       /* This descriptor is the file port we want.  */
383                       dealloc_dir = 0;
384                       goto opened;
385                     }
386                   else
387                     {
388                       /* Do a normal retry on the remaining components.  */
389                       startdir = fileport;
390                       dealloc_dir = 1;
391                       file_name = p + 1; /* Skip the slash.  */
392                       break;
393                     }
394                 }
395               else
396                 goto bad_magic;
397               break;
398
399             case 'm':
400               if (retryname[1] == 'a' && retryname[2] == 'c' &&
401                   retryname[3] == 'h' && retryname[4] == 't' &&
402                   retryname[5] == 'y' && retryname[6] == 'p' &&
403                   retryname[7] == 'e')
404                 {
405                   error_t err;
406                   struct host_basic_info hostinfo;
407                   mach_msg_type_number_t hostinfocnt = HOST_BASIC_INFO_COUNT;
408                   char *p;
409                   if (err = __host_info (__mach_host_self (), HOST_BASIC_INFO,
410                                          (natural_t *) &hostinfo,
411                                          &hostinfocnt))
412                     return err;
413                   if (hostinfocnt != HOST_BASIC_INFO_COUNT)
414                     return EGRATUITOUS;
415                   p = _itoa (hostinfo.cpu_subtype, &retryname[8], 10, 0);
416                   *--p = '/';
417                   p = _itoa (hostinfo.cpu_type, &retryname[8], 10, 0);
418                   if (p < retryname)
419                     abort ();   /* XXX write this right if this ever happens */
420                   if (p > retryname)
421                     strcpy (retryname, p);
422                   startdir = fileport;
423                   dealloc_dir = 1;
424                 }
425               else
426                 goto bad_magic;
427               break;
428
429             case 't':
430               if (retryname[1] == 't' && retryname[2] == 'y')
431                 switch (retryname[3])
432                   {
433                     error_t opentty (file_t *result)
434                       {
435                         error_t err;
436                         file_t unauth;
437                         err = __termctty_open_terminal
438                           (_dl_hurd_data->portarray[INIT_PORT_CTTYID],
439                            mode, &unauth);
440                         if (! err)
441                           {
442                             mach_port_t ref = __mach_reply_port ();
443                             err = __io_reauthenticate
444                               (unauth, ref, MACH_MSG_TYPE_MAKE_SEND);
445                             if (! err)
446                               err = __auth_user_authenticate
447                                 (_dl_hurd_data->portarray[INIT_PORT_AUTH],
448                                  ref, MACH_MSG_TYPE_MAKE_SEND,
449                                  result);
450                             __mach_port_deallocate (__mach_task_self (),
451                                                     unauth);
452                             __mach_port_destroy (__mach_task_self (), ref);
453                           }
454                         return err;
455                       }
456
457                   case '\0':
458                     if (err = opentty (&fileport))
459                       return __hurd_fail (err);
460                     dealloc_dir = 1;
461                     goto opened;
462                   case '/':
463                     if (err = opentty (&startdir))
464                       return __hurd_fail (err);
465                     dealloc_dir = 1;
466                     strcpy (retryname, &retryname[4]);
467                     break;
468                   default:
469                     goto bad_magic;
470                   }
471               else
472                 goto bad_magic;
473               break;
474
475             default:
476             bad_magic:
477               return __hurd_fail (EGRATUITOUS);
478             }
479           break;
480
481         default:
482           return __hurd_fail (EGRATUITOUS);
483         }
484
485       err = __dir_lookup (startdir, file_name, mode, 0,
486                           &doretry, retryname, &fileport);
487     }
488 }
489
490 int weak_function
491 __close (int fd)
492 {
493   if (fd != (int) MACH_PORT_NULL)
494     __mach_port_deallocate (__mach_task_self (), (mach_port_t) fd);
495   return 0;
496 }
497
498 caddr_t weak_function
499 __mmap (caddr_t addr, size_t len, int prot, int flags, int fd, off_t offset)
500 {
501   error_t err;
502   vm_prot_t vmprot;
503   vm_address_t mapaddr;
504
505   vmprot = VM_PROT_NONE;
506   if (prot & PROT_READ)
507     vmprot |= VM_PROT_READ;
508   if (prot & PROT_WRITE)
509     vmprot |= VM_PROT_WRITE;
510   if (prot & PROT_EXEC)
511     vmprot |= VM_PROT_EXECUTE;
512
513   mapaddr = (vm_address_t) addr;
514   err = __vm_map (__mach_task_self (),
515                   &mapaddr, (vm_size_t) len, 0 /*ELF_MACHINE_USER_ADDRESS_MASK*/,
516                   !(flags & MAP_FIXED),
517                   (flags & MAP_ANON) ? MACH_PORT_NULL : (mach_port_t) fd,
518                   (vm_offset_t) offset,
519                   flags & (MAP_COPY|MAP_PRIVATE),
520                   vmprot, VM_PROT_ALL,
521                   (flags & MAP_SHARED) ? VM_INHERIT_SHARE : VM_INHERIT_COPY);
522   if (err == KERN_NO_SPACE && (flags & MAP_FIXED))
523     {
524       /* XXX this is not atomic as it is in unix! */
525       /* The region is already allocated; deallocate it first.  */
526       err = __vm_deallocate (__mach_task_self (), mapaddr, len);
527       if (! err)
528         err = __vm_map (__mach_task_self (),
529                         &mapaddr, (vm_size_t) len, 0 /*ELF_MACHINE_USER_ADDRESS_MASK*/,
530                         !(flags & MAP_FIXED),
531                         (mach_port_t) fd, (vm_offset_t) offset,
532                         flags & (MAP_COPY|MAP_PRIVATE),
533                         vmprot, VM_PROT_ALL,
534                         (flags & MAP_SHARED)
535                         ? VM_INHERIT_SHARE : VM_INHERIT_COPY);
536     }
537
538   return err ? (caddr_t) __hurd_fail (err) : (caddr_t) mapaddr;
539 }
540
541 void weak_function
542 _exit (int status)
543 {
544   __proc_mark_exit (_dl_hurd_data->portarray[INIT_PORT_PROC],
545                     W_EXITCODE (status, 0), 0);
546   while (__task_terminate (__mach_task_self ()))
547     __mach_task_self_ = (__mach_task_self) ();
548 }
549 \f
550
551 /* This function is called by interruptible RPC stubs.  For initial
552    dynamic linking, just use the normal mach_msg.  Since this defn is
553    weak, the real defn in libc.so will override it if we are linked into
554    the user program (-ldl).  */
555
556 error_t weak_function
557 _hurd_intr_rpc_mach_msg (mach_msg_header_t *msg,
558                          mach_msg_option_t option,
559                          mach_msg_size_t send_size,
560                          mach_msg_size_t rcv_size,
561                          mach_port_t rcv_name,
562                          mach_msg_timeout_t timeout,
563                          mach_port_t notify)
564 {
565   return __mach_msg (msg, option, send_size, rcv_size, rcv_name,
566                      timeout, notify);
567 }