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