OSDN Git Service

Copyright year update in most files of the GDB Project.
[pf3gnuchains/pf3gnuchains4x.git] / sim / cris / sim-if.c
1 /* Main simulator entry points specific to the CRIS.
2    Copyright (C) 2004-2012 Free Software Foundation, Inc.
3    Contributed by Axis Communications.
4
5 This file is part of the GNU simulators.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 /* Based on the fr30 file, mixing in bits from the i960 and pruning of
21    dead code.  */
22
23 #include "libiberty.h"
24 #include "bfd.h"
25 #include "elf-bfd.h"
26
27 #include "sim-main.h"
28 #ifdef HAVE_STDLIB_H
29 #include <stdlib.h>
30 #endif
31 #include <errno.h>
32 #include "sim-options.h"
33 #include "dis-asm.h"
34
35 /* Apparently the autoconf bits are missing (though HAVE_ENVIRON is used
36    in other dirs; also lacking there).  Patch around it for major systems.  */
37 #if defined (HAVE_ENVIRON) || defined (__GLIBC__)
38 extern char **environ;
39 #define GET_ENVIRON() environ
40 #else
41 char *missing_environ[] = { "SHELL=/bin/sh", "PATH=/bin:/usr/bin", NULL };
42 #define GET_ENVIRON() missing_environ
43 #endif
44
45 /* Used with get_progbounds to find out how much memory is needed for the
46    program.  We don't want to allocate more, since that could mask
47    invalid memory accesses program bugs.  */
48 struct progbounds {
49   USI startmem;
50   USI endmem;
51   USI end_loadmem;
52   USI start_nonloadmem;
53 };
54
55 static void free_state (SIM_DESC);
56 static void get_progbounds_iterator (bfd *, asection *, void *);
57 static SIM_RC cris_option_handler (SIM_DESC, sim_cpu *, int, char *, int);
58
59 /* Since we don't build the cgen-opcode table, we use the old
60    disassembler.  */
61 static CGEN_DISASSEMBLER cris_disassemble_insn;
62
63 /* By default, we set up stack and environment variables like the Linux
64    kernel.  */
65 static char cris_bare_iron = 0;
66
67 /* Whether 0x9000000xx have simulator-specific meanings.  */
68 char cris_have_900000xxif = 0;
69
70 /* Used to optionally override the default start address of the
71    simulation.  */
72 static USI cris_start_address = 0xffffffffu;
73
74 /* Used to optionally add offsets to the loaded image and its start
75    address.  (Not used for the interpreter of dynamically loaded
76    programs or the DSO:s.)  */
77 static int cris_program_offset = 0;
78
79 /* What to do when we face a more or less unknown syscall.  */
80 enum cris_unknown_syscall_action_type cris_unknown_syscall_action
81   = CRIS_USYSC_MSG_STOP;
82
83 /* Records simulator descriptor so utilities like cris_dump_regs can be
84    called from gdb.  */
85 SIM_DESC current_state;
86
87 /* CRIS-specific options.  */
88 typedef enum {
89   OPTION_CRIS_STATS = OPTION_START,
90   OPTION_CRIS_TRACE,
91   OPTION_CRIS_NAKED,
92   OPTION_CRIS_PROGRAM_OFFSET,
93   OPTION_CRIS_STARTADDR,
94   OPTION_CRIS_900000XXIF,
95   OPTION_CRIS_UNKNOWN_SYSCALL
96 } CRIS_OPTIONS;
97
98 static const OPTION cris_options[] =
99 {
100   { {"cris-cycles", required_argument, NULL, OPTION_CRIS_STATS},
101       '\0', "basic|unaligned|schedulable|all",
102     "Dump execution statistics",
103       cris_option_handler, NULL },
104   { {"cris-trace", required_argument, NULL, OPTION_CRIS_TRACE},
105       '\0', "basic",
106     "Emit trace information while running",
107       cris_option_handler, NULL },
108   { {"cris-naked", no_argument, NULL, OPTION_CRIS_NAKED},
109      '\0', NULL, "Don't set up stack and environment",
110      cris_option_handler, NULL },
111   { {"cris-900000xx", no_argument, NULL, OPTION_CRIS_900000XXIF},
112      '\0', NULL, "Define addresses at 0x900000xx with simulator semantics",
113      cris_option_handler, NULL },
114   { {"cris-unknown-syscall", required_argument, NULL,
115      OPTION_CRIS_UNKNOWN_SYSCALL},
116      '\0', "stop|enosys|enosys-quiet", "Action at an unknown system call",
117      cris_option_handler, NULL },
118   { {"cris-program-offset", required_argument, NULL,
119      OPTION_CRIS_PROGRAM_OFFSET},
120       '\0', "OFFSET",
121     "Offset image addresses and default start address of a program",
122       cris_option_handler },
123   { {"cris-start-address", required_argument, NULL, OPTION_CRIS_STARTADDR},
124       '\0', "ADDRESS", "Set start address",
125       cris_option_handler },
126   { {NULL, no_argument, NULL, 0}, '\0', NULL, NULL, NULL, NULL }
127 };
128 \f
129 /* Add the CRIS-specific option list to the simulator.  */
130
131 SIM_RC
132 cris_option_install (SIM_DESC sd)
133 {
134   SIM_ASSERT (STATE_MAGIC (sd) == SIM_MAGIC_NUMBER);
135   if (sim_add_option_table (sd, NULL, cris_options) != SIM_RC_OK)
136     return SIM_RC_FAIL;
137   return SIM_RC_OK;
138 }
139
140 /* Handle CRIS-specific options.  */
141
142 static SIM_RC
143 cris_option_handler (SIM_DESC sd, sim_cpu *cpu ATTRIBUTE_UNUSED, int opt,
144                      char *arg, int is_command ATTRIBUTE_UNUSED)
145 {
146   /* The options are CRIS-specific, but cpu-specific option-handling is
147      broken; required to being with "--cpu0-".  We store the flags in an
148      unused field in the global state structure and move the flags over
149      to the module-specific CPU data when we store things in the
150      cpu-specific structure.  */
151   char *tracefp = STATE_TRACE_FLAGS (sd);
152   char *chp = arg;
153
154   switch ((CRIS_OPTIONS) opt)
155     {
156       case OPTION_CRIS_STATS:
157         if (strcmp (arg, "basic") == 0)
158           *tracefp = FLAG_CRIS_MISC_PROFILE_SIMPLE;
159         else if (strcmp (arg, "unaligned") == 0)
160           *tracefp
161             = (FLAG_CRIS_MISC_PROFILE_UNALIGNED
162                | FLAG_CRIS_MISC_PROFILE_SIMPLE);
163         else if (strcmp (arg, "schedulable") == 0)
164           *tracefp
165             = (FLAG_CRIS_MISC_PROFILE_SCHEDULABLE
166                | FLAG_CRIS_MISC_PROFILE_SIMPLE);
167         else if (strcmp (arg, "all") == 0)
168           *tracefp = FLAG_CRIS_MISC_PROFILE_ALL;
169         else
170           {
171             /* Beware; the framework does not handle the error case;
172                we have to do it ourselves.  */
173             sim_io_eprintf (sd, "Unknown option `--cris-cycles=%s'\n", arg);
174             return SIM_RC_FAIL;
175           }
176         break;
177
178       case OPTION_CRIS_TRACE:
179         if (strcmp (arg, "basic") == 0)
180           *tracefp |= FLAG_CRIS_MISC_PROFILE_XSIM_TRACE;
181         else
182           {
183             sim_io_eprintf (sd, "Unknown option `--cris-trace=%s'\n", arg);
184             return SIM_RC_FAIL;
185           }
186         break;
187
188       case OPTION_CRIS_NAKED:
189         cris_bare_iron = 1;
190         break;
191
192       case OPTION_CRIS_900000XXIF:
193         cris_have_900000xxif = 1;
194         break;
195
196       case OPTION_CRIS_STARTADDR:
197         errno = 0;
198         cris_start_address = (USI) strtoul (chp, &chp, 0);
199
200         if (errno != 0 || *chp != 0)
201           {
202             sim_io_eprintf (sd, "Invalid option `--cris-start-address=%s'\n",
203                             arg);
204             return SIM_RC_FAIL;
205           }
206         break;
207
208       case OPTION_CRIS_PROGRAM_OFFSET:
209         errno = 0;
210         cris_program_offset = (int) strtol (chp, &chp, 0);
211
212         if (errno != 0 || *chp != 0)
213           {
214             sim_io_eprintf (sd, "Invalid option `--cris-program-offset=%s'\n",
215                             arg);
216             return SIM_RC_FAIL;
217           }
218         break;
219
220       case OPTION_CRIS_UNKNOWN_SYSCALL:
221         if (strcmp (arg, "enosys") == 0)
222           cris_unknown_syscall_action = CRIS_USYSC_MSG_ENOSYS;
223         else if (strcmp (arg, "enosys-quiet") == 0)
224           cris_unknown_syscall_action = CRIS_USYSC_QUIET_ENOSYS;
225         else if (strcmp (arg, "stop") == 0)
226           cris_unknown_syscall_action = CRIS_USYSC_MSG_STOP;
227         else
228           {
229             sim_io_eprintf (sd, "Unknown option `--cris-unknown-syscall=%s'\n",
230                             arg);
231             return SIM_RC_FAIL;
232           }
233         break;
234
235       default:
236         /* We'll actually never get here; the caller handles the error
237            case.  */
238         sim_io_eprintf (sd, "Unknown option `%s'\n", arg);
239         return SIM_RC_FAIL;
240     }
241
242   /* Imply --profile-model=on.  */
243   return sim_profile_set_option (sd, "-model", PROFILE_MODEL_IDX, "on");
244 }
245
246 /* FIXME: Remove these, globalize those in sim-load.c, move elsewhere.  */
247
248 static void
249 xprintf  (host_callback *callback, const char *fmt, ...)
250 {
251   va_list ap;
252
253   va_start (ap, fmt);
254
255   (*callback->vprintf_filtered) (callback, fmt, ap);
256
257   va_end (ap);
258 }
259
260 static void
261 eprintf (host_callback *callback, const char *fmt, ...)
262 {
263   va_list ap;
264
265   va_start (ap, fmt);
266
267   (*callback->evprintf_filtered) (callback, fmt, ap);
268
269   va_end (ap);
270 }
271
272 /* An ELF-specific simplified ../common/sim-load.c:sim_load_file,
273    using the program headers, not sections, in order to make sure that
274    the program headers themeselves are also loaded.  The caller is
275    responsible for asserting that ABFD is an ELF file.  */
276
277 static bfd_boolean
278 cris_load_elf_file (SIM_DESC sd, struct bfd *abfd, sim_write_fn do_write)
279 {
280   Elf_Internal_Phdr *phdr;
281   int n_hdrs;
282   int i;
283   bfd_boolean verbose = STATE_OPEN_KIND (sd) == SIM_OPEN_DEBUG;
284   host_callback *callback = STATE_CALLBACK (sd);
285
286   phdr = elf_tdata (abfd)->phdr;
287   n_hdrs = elf_elfheader (abfd)->e_phnum;
288
289   /* We're only interested in PT_LOAD; all necessary information
290      should be covered by that.  */
291   for (i = 0; i < n_hdrs; i++)
292     {
293       bfd_byte *buf;
294       bfd_vma lma = STATE_LOAD_AT_LMA_P (sd)
295         ? phdr[i].p_paddr : phdr[i].p_vaddr;
296
297       if (phdr[i].p_type != PT_LOAD)
298         continue;
299
300       buf = xmalloc (phdr[i].p_filesz);
301
302       if (verbose)
303         xprintf (callback, "Loading segment at 0x%lx, size 0x%lx\n",
304                  lma, phdr[i].p_filesz);
305
306       if (bfd_seek (abfd, phdr[i].p_offset, SEEK_SET) != 0
307           || (bfd_bread (buf, phdr[i].p_filesz, abfd) != phdr[i].p_filesz))
308         {
309           eprintf (callback,
310                    "%s: could not read segment at 0x%lx, size 0x%lx\n",
311                    STATE_MY_NAME (sd), lma, phdr[i].p_filesz);
312           free (buf);
313           return FALSE;
314         }
315
316       if (do_write (sd, lma, buf, phdr[i].p_filesz) != phdr[i].p_filesz)
317         {
318           eprintf (callback,
319                    "%s: could not load segment at 0x%lx, size 0x%lx\n",
320                    STATE_MY_NAME (sd), lma, phdr[i].p_filesz);
321           free (buf);
322           return FALSE;
323         }
324
325       free (buf);
326     }
327
328   return TRUE;
329 }
330
331 /* Helper for sim_load (needed just for ELF files): like sim_write,
332    but offset load at cris_program_offset offset.  */
333
334 static int
335 cris_program_offset_write (SIM_DESC sd, SIM_ADDR mem, unsigned char *buf,
336                            int length)
337 {
338   return sim_write (sd, mem + cris_program_offset, buf, length);
339 }
340
341 /* Replacement for ../common/sim-hload.c:sim_load, so we can treat ELF
342    files differently.  */
343
344 SIM_RC
345 sim_load (SIM_DESC sd, char *prog_name, struct bfd *prog_bfd,
346           int from_tty ATTRIBUTE_UNUSED)
347 {
348   bfd *result_bfd;
349
350   if (bfd_get_flavour (prog_bfd) != bfd_target_elf_flavour)
351     {
352       SIM_ASSERT (STATE_MAGIC (sd) == SIM_MAGIC_NUMBER);
353       if (sim_analyze_program (sd, prog_name, prog_bfd) != SIM_RC_OK)
354         return SIM_RC_FAIL;
355       SIM_ASSERT (STATE_PROG_BFD (sd) != NULL);
356
357       result_bfd = sim_load_file (sd, STATE_MY_NAME (sd),
358                                   STATE_CALLBACK (sd),
359                                   prog_name,
360                                   STATE_PROG_BFD (sd),
361                                   STATE_OPEN_KIND (sd) == SIM_OPEN_DEBUG,
362                                   STATE_LOAD_AT_LMA_P (sd),
363                                   sim_write);
364       if (result_bfd == NULL)
365         {
366           bfd_close (STATE_PROG_BFD (sd));
367           STATE_PROG_BFD (sd) = NULL;
368           return SIM_RC_FAIL;
369         }
370       return SIM_RC_OK;
371     }
372
373   return cris_load_elf_file (sd, prog_bfd, cris_program_offset_write)
374     ? SIM_RC_OK : SIM_RC_FAIL;
375 }
376
377 /* Cover function of sim_state_free to free the cpu buffers as well.  */
378
379 static void
380 free_state (SIM_DESC sd)
381 {
382   if (STATE_MODULES (sd) != NULL)
383     sim_module_uninstall (sd);
384   sim_cpu_free_all (sd);
385   sim_state_free (sd);
386 }
387
388 /* Helper struct for cris_set_section_offset_iterator.  */
389
390 struct offsetinfo
391 {
392   SIM_DESC sd;
393   int offset;
394 };
395
396 /* BFD section iterator to offset the LMA and VMA.  */
397
398 static void
399 cris_set_section_offset_iterator (bfd *abfd, asection *s, void *vp)
400 {
401   struct offsetinfo *p = (struct offsetinfo *) vp;
402   SIM_DESC sd = p->sd;
403   int offset = p->offset;
404
405   if ((bfd_get_section_flags (abfd, s) & SEC_ALLOC))
406     {
407       bfd_vma vma = bfd_get_section_vma (abfd, s);
408       
409       bfd_set_section_vma (abfd, s, vma + offset);
410     }
411
412   /* This seems clumsy and inaccurate, but let's stick to doing it the
413      same way as sim_analyze_program for consistency.  */
414   if (strcmp (bfd_get_section_name (abfd, s), ".text") == 0)
415     STATE_TEXT_START (sd) = bfd_get_section_vma (abfd, s);
416 }
417
418 /* Adjust the start-address, LMA and VMA of a SD.  Must be called
419    after sim_analyze_program.  */
420
421 static void
422 cris_offset_sections (SIM_DESC sd, int offset)
423 {
424   bfd_boolean ret;
425   struct bfd *abfd = STATE_PROG_BFD (sd);
426   asection *text;
427   struct offsetinfo oi;
428
429   /* Only happens for usage error.  */
430   if (abfd == NULL)
431     return;
432
433   oi.sd = sd;
434   oi.offset = offset;
435
436   bfd_map_over_sections (abfd, cris_set_section_offset_iterator, &oi);
437   ret = bfd_set_start_address (abfd, bfd_get_start_address (abfd) + offset);
438
439   STATE_START_ADDR (sd) = bfd_get_start_address (abfd);
440 }
441
442 /* BFD section iterator to find the highest and lowest allocated and
443    non-allocated section addresses (plus one).  */
444
445 static void
446 get_progbounds_iterator (bfd *abfd ATTRIBUTE_UNUSED, asection *s, void *vp)
447 {
448   struct progbounds *pbp = (struct progbounds *) vp;
449
450   if ((bfd_get_section_flags (abfd, s) & SEC_ALLOC))
451     {
452       bfd_size_type sec_size = bfd_get_section_size (s);
453       bfd_size_type sec_start = bfd_get_section_vma (abfd, s);
454       bfd_size_type sec_end = sec_start + sec_size;
455
456       if (sec_end > pbp->endmem)
457         pbp->endmem = sec_end;
458
459       if (sec_start < pbp->startmem)
460         pbp->startmem = sec_start;
461
462       if ((bfd_get_section_flags (abfd, s) & SEC_LOAD))
463         {
464           if (sec_end > pbp->end_loadmem)
465             pbp->end_loadmem = sec_end;
466         }
467       else if (sec_start < pbp->start_nonloadmem)
468         pbp->start_nonloadmem = sec_start;
469     }
470 }
471
472 /* Get the program boundaries.  Because not everything is covered by
473    sections in ELF, notably the program headers, we use the program
474    headers instead.  */
475
476 static void
477 cris_get_progbounds (struct bfd *abfd, struct progbounds *pbp)
478 {
479   Elf_Internal_Phdr *phdr;
480   int n_hdrs;
481   int i;
482
483   pbp->startmem = 0xffffffff;
484   pbp->endmem = 0;
485   pbp->end_loadmem = 0;
486   pbp->start_nonloadmem = 0xffffffff;
487
488   /* In case we're ever used for something other than ELF, use the
489      generic method.  */
490   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
491     {
492       bfd_map_over_sections (abfd, get_progbounds_iterator, pbp);
493       return;
494     }
495
496   phdr = elf_tdata (abfd)->phdr;
497   n_hdrs = elf_elfheader (abfd)->e_phnum;
498
499   /* We're only interested in PT_LOAD; all necessary information
500      should be covered by that.  */
501   for (i = 0; i < n_hdrs; i++)
502     {
503       if (phdr[i].p_type != PT_LOAD)
504         continue;
505
506       if (phdr[i].p_paddr < pbp->startmem)
507         pbp->startmem = phdr[i].p_paddr;
508
509       if (phdr[i].p_paddr + phdr[i].p_memsz > pbp->endmem)
510         pbp->endmem = phdr[i].p_paddr + phdr[i].p_memsz;
511
512       if (phdr[i].p_paddr + phdr[i].p_filesz > pbp->end_loadmem)
513         pbp->end_loadmem = phdr[i].p_paddr + phdr[i].p_filesz;
514
515       if (phdr[i].p_memsz > phdr[i].p_filesz
516           && phdr[i].p_paddr + phdr[i].p_filesz < pbp->start_nonloadmem)
517         pbp->start_nonloadmem = phdr[i].p_paddr + phdr[i].p_filesz;
518     }  
519 }
520
521 /* Parameter communication by static variables, hmm...  Oh well, for
522    simplicity.  */
523 static bfd_vma exec_load_addr;
524 static bfd_vma interp_load_addr;
525 static bfd_vma interp_start_addr;
526
527 /* Supposed to mimic Linux' "NEW_AUX_ENT (AT_PHDR, load_addr + exec->e_phoff)".  */
528
529 static USI
530 aux_ent_phdr (struct bfd *ebfd)
531 {
532   return elf_elfheader (ebfd)->e_phoff + exec_load_addr;
533 }
534
535 /* We just pass on the header info; we don't have our own idea of the
536    program header entry size.  */
537
538 static USI
539 aux_ent_phent (struct bfd *ebfd)
540 {
541   return elf_elfheader (ebfd)->e_phentsize;
542 }
543
544 /* Like "NEW_AUX_ENT(AT_PHNUM, exec->e_phnum)".  */
545
546 static USI
547 aux_ent_phnum (struct bfd *ebfd)
548 {
549   return elf_elfheader (ebfd)->e_phnum;
550 }
551
552 /* Like "NEW_AUX_ENT(AT_BASE, interp_load_addr)".  */
553
554 static USI
555 aux_ent_base (struct bfd *ebfd)
556 {
557   return interp_load_addr;
558 }
559
560 /* Like "NEW_AUX_ENT(AT_ENTRY, exec->e_entry)".  */
561
562 static USI
563 aux_ent_entry (struct bfd *ebfd)
564 {
565   ASSERT (elf_elfheader (ebfd)->e_entry == bfd_get_start_address (ebfd));
566   return elf_elfheader (ebfd)->e_entry;
567 }
568
569 /* Helper for cris_handle_interpreter: like sim_write, but load at
570    interp_load_addr offset.  */
571
572 static int
573 cris_write_interp (SIM_DESC sd, SIM_ADDR mem, unsigned char *buf, int length)
574 {
575   return sim_write (sd, mem + interp_load_addr, buf, length);
576 }
577
578 /* Cater to the presence of an interpreter: load it and set
579    interp_start_addr.  Return FALSE if there was an error, TRUE if
580    everything went fine, including an interpreter being absent and
581    the program being in a non-ELF format.  */
582
583 static bfd_boolean
584 cris_handle_interpreter (SIM_DESC sd, struct bfd *abfd)
585 {
586   int i, n_hdrs;
587   bfd_vma phaddr;
588   bfd_byte buf[4];
589   char *interp = NULL;
590   struct bfd *ibfd;
591   bfd_boolean ok = FALSE;
592   Elf_Internal_Phdr *phdr;
593
594   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
595     return TRUE;
596
597   phdr = elf_tdata (abfd)->phdr;
598   n_hdrs = aux_ent_phnum (abfd);
599
600   /* Check the program headers for presence of an interpreter.  */
601   for (i = 0; i < n_hdrs; i++)
602     {
603       int interplen;
604       bfd_size_type interpsiz, interp_filesiz;
605       struct progbounds interp_bounds;
606
607       if (phdr[i].p_type != PT_INTERP)
608         continue;
609
610       /* Get the name of the interpreter, prepended with the sysroot
611          (empty if absent).  */
612       interplen = phdr[i].p_filesz;
613       interp = xmalloc (interplen + strlen (simulator_sysroot));
614       strcpy (interp, simulator_sysroot);
615
616       /* Read in the name.  */
617       if (bfd_seek (abfd, phdr[i].p_offset, SEEK_SET) != 0
618           || (bfd_bread (interp + strlen (simulator_sysroot), interplen, abfd)
619               != interplen))
620         goto interpname_failed;
621
622       /* Like Linux, require the string to be 0-terminated.  */
623       if (interp[interplen + strlen (simulator_sysroot) - 1] != 0)
624         goto interpname_failed;
625
626       /* Inspect the interpreter.  */
627       ibfd = bfd_openr (interp, STATE_TARGET (sd));
628       if (ibfd == NULL)
629         goto interpname_failed;
630
631       /* The interpreter is at least something readable to BFD; make
632          sure it's an ELF non-archive file.  */
633       if (!bfd_check_format (ibfd, bfd_object)
634           || bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
635         goto interp_failed;
636
637       /* Check the layout of the interpreter.  */
638       cris_get_progbounds (ibfd, &interp_bounds);
639
640       /* Round down to pagesize the start page and up the endpage.
641          Don't round the *load and *nonload members.  */
642       interp_bounds.startmem &= ~8191;
643       interp_bounds.endmem = (interp_bounds.endmem + 8191) & ~8191;
644
645       /* Until we need a more dynamic solution, assume we can put the
646          interpreter at this fixed location.  NB: this is not what
647          happens for Linux 2008-12-28, but it could and might and
648          perhaps should.  */
649       interp_load_addr = 0x40000;
650       interpsiz = interp_bounds.endmem - interp_bounds.startmem;
651       interp_filesiz = interp_bounds.end_loadmem - interp_bounds.startmem;
652
653       /* If we have a non-DSO or interpreter starting at the wrong
654          address, bail.  */
655       if (interp_bounds.startmem != 0
656           || interpsiz + interp_load_addr >= exec_load_addr)
657         goto interp_failed;
658
659       /* We don't have the API to get the address of a simulator
660          memory area, so we go via a temporary area.  Luckily, the
661          interpreter is supposed to be small, less than 0x40000
662          bytes.  */
663       sim_do_commandf (sd, "memory region 0x%lx,0x%lx",
664                        interp_load_addr, interpsiz);
665
666       /* Now that memory for the interpreter is defined, load it.  */
667       if (!cris_load_elf_file (sd, ibfd, cris_write_interp))
668         goto interp_failed;
669
670       /* It's no use setting STATE_START_ADDR, because it gets
671          overwritten by a sim_analyze_program call in sim_load.  Let's
672          just store it locally.  */
673       interp_start_addr
674         = (bfd_get_start_address (ibfd)
675            - interp_bounds.startmem + interp_load_addr);
676
677       /* Linux cares only about the first PT_INTERP, so let's ignore
678          the rest.  */
679       goto all_done;
680     }
681
682   /* Register R10 should hold 0 at static start (no finifunc), but
683      that's the default, so don't bother.  */
684   return TRUE;
685
686  all_done:
687   ok = TRUE;
688
689  interp_failed:
690   bfd_close (ibfd);
691
692  interpname_failed:
693   if (!ok)
694     sim_io_eprintf (sd,
695                     "%s: could not load ELF interpreter `%s' for program `%s'\n",
696                     STATE_MY_NAME (sd),
697                     interp == NULL ? "(what's-its-name)" : interp,
698                     bfd_get_filename (abfd));
699   free (interp);
700   return ok;
701 }
702
703 /* Create an instance of the simulator.  */
704
705 SIM_DESC
706 sim_open (SIM_OPEN_KIND kind, host_callback *callback, struct bfd *abfd,
707           char **argv)
708 {
709   char c;
710   int i;
711   USI startmem = 0;
712   USI endmem = CRIS_DEFAULT_MEM_SIZE;
713   USI endbrk = endmem;
714   USI stack_low = 0;
715   SIM_DESC sd = sim_state_alloc (kind, callback);
716
717   static const struct auxv_entries_s
718   {
719     bfd_byte id;
720     USI (*efn) (struct bfd *ebfd);
721     USI val;
722   } auxv_entries[] =
723     {
724 #define AUX_ENT(a, b) {a, NULL, b}
725 #define AUX_ENTF(a, f) {a, f, 0}
726       AUX_ENT (AT_HWCAP, 0),
727       AUX_ENT (AT_PAGESZ, 8192),
728       AUX_ENT (AT_CLKTCK, 100),
729       AUX_ENTF (AT_PHDR, aux_ent_phdr),
730       AUX_ENTF (AT_PHENT, aux_ent_phent),
731       AUX_ENTF (AT_PHNUM, aux_ent_phnum),
732       AUX_ENTF (AT_BASE, aux_ent_base),
733       AUX_ENT (AT_FLAGS, 0),
734       AUX_ENTF (AT_ENTRY, aux_ent_entry),
735
736       /* Or is root better?  Maybe have it settable?  */
737       AUX_ENT (AT_UID, 500),
738       AUX_ENT (AT_EUID, 500),
739       AUX_ENT (AT_GID, 500),
740       AUX_ENT (AT_EGID, 500),
741       AUX_ENT (AT_SECURE, 0),
742       AUX_ENT (AT_NULL, 0)
743     };
744
745   /* Can't initialize to "" below.  It's either a GCC bug in old
746      releases (up to and including 2.95.3 (.4 in debian) or a bug in the
747      standard ;-) that the rest of the elements won't be initialized.  */
748   bfd_byte sp_init[4] = {0, 0, 0, 0};
749
750   /* The cpu data is kept in a separately allocated chunk of memory.  */
751   if (sim_cpu_alloc_all (sd, 1, cgen_cpu_max_extra_bytes ()) != SIM_RC_OK)
752     {
753       free_state (sd);
754       return 0;
755     }
756
757   if (sim_pre_argv_init (sd, argv[0]) != SIM_RC_OK)
758     {
759       free_state (sd);
760       return 0;
761     }
762
763   /* getopt will print the error message so we just have to exit if this fails.
764      FIXME: Hmmm...  in the case of gdb we need getopt to call
765      print_filtered.  */
766   if (sim_parse_args (sd, argv) != SIM_RC_OK)
767     {
768       free_state (sd);
769       return 0;
770     }
771
772   /* If we have a binary program, endianness-setting would not be taken
773      from elsewhere unfortunately, so set it here.  At the time of this
774      writing, it isn't used until sim_config, but that might change so
775      set it here before memory is defined or touched.  */
776   current_target_byte_order = LITTLE_ENDIAN;
777
778   /* check for/establish the reference program image */
779   if (sim_analyze_program (sd,
780                            (STATE_PROG_ARGV (sd) != NULL
781                             ? *STATE_PROG_ARGV (sd)
782                             : NULL),
783                            abfd) != SIM_RC_OK)
784     {
785       /* When there's an error, sim_analyze_program has already output
786          a message.  Let's just clarify it, as "not an object file"
787          perhaps doesn't ring a bell.  */
788       sim_io_eprintf (sd, "(not a CRIS program)\n");
789       free_state (sd);
790       return 0;
791     }
792
793   /* We might get called with the caller expecting us to get hold of
794      the bfd for ourselves, which would happen at the
795      sim_analyze_program call above.  */
796   if (abfd == NULL)
797     abfd = STATE_PROG_BFD (sd);
798
799   /* Adjust the addresses of the program at this point.  Unfortunately
800      this does not affect ELF program headers, so we have to handle
801      that separately.  */
802   cris_offset_sections (sd, cris_program_offset);
803
804   if (abfd != NULL && bfd_get_arch (abfd) == bfd_arch_unknown)
805     {
806       if (STATE_PROG_ARGV (sd) != NULL)
807         sim_io_eprintf (sd, "%s: `%s' is not a CRIS program\n",
808                         STATE_MY_NAME (sd), *STATE_PROG_ARGV (sd));
809       else
810         sim_io_eprintf (sd, "%s: program to be run is not a CRIS program\n",
811                         STATE_MY_NAME (sd));
812       free_state (sd);
813       return 0;
814     }
815
816   /* For CRIS simulator-specific use, we need to find out the bounds of
817      the program as well, which is not done by sim_analyze_program
818      above.  */
819   if (abfd != NULL)
820     {
821       struct progbounds pb;
822
823       /* The sections should now be accessible using bfd functions.  */
824       cris_get_progbounds (abfd, &pb);
825
826       /* We align the area that the program uses to page boundaries.  */
827       startmem = pb.startmem & ~8191;
828       endbrk = pb.endmem;
829       endmem = (endbrk + 8191) & ~8191;
830     }
831
832   /* Find out how much room is needed for the environment and argv, create
833      that memory and fill it.  Only do this when there's a program
834      specified.  */
835   if (abfd != NULL && !cris_bare_iron)
836     {
837       char *name = bfd_get_filename (abfd);
838       char **my_environ = GET_ENVIRON ();
839       /* We use these maps to give the same behavior as the old xsim
840          simulator.  */
841       USI envtop = 0x40000000;
842       USI stacktop = 0x3e000000;
843       USI envstart;
844       int envc;
845       int len = strlen (name) + 1;
846       USI epp, epp0;
847       USI stacklen;
848       int i;
849       char **prog_argv = STATE_PROG_ARGV (sd);
850       int my_argc = 0;
851       /* All CPU:s have the same memory map, apparently.  */
852       SIM_CPU *cpu = STATE_CPU (sd, 0);
853       USI csp;
854       bfd_byte buf[4];
855
856       /* Count in the environment as well. */
857       for (envc = 0; my_environ[envc] != NULL; envc++)
858         len += strlen (my_environ[envc]) + 1;
859
860       for (i = 0; prog_argv[i] != NULL; my_argc++, i++)
861         len += strlen (prog_argv[i]) + 1;
862
863       envstart = (envtop - len) & ~8191;
864
865       /* Create read-only block for the environment strings.  */
866       sim_core_attach (sd, NULL, 0, access_read, 0,
867                        envstart, (len + 8191) & ~8191,
868                        0, NULL, NULL);
869
870       /* This shouldn't happen.  */
871       if (envstart < stacktop)
872         stacktop = envstart - 64 * 8192;
873
874       csp = stacktop;
875
876       /* Note that the linux kernel does not correctly compute the storage
877          needs for the static-exe AUX vector.  */
878
879       csp -= sizeof (auxv_entries) / sizeof (auxv_entries[0]) * 4 * 2;
880
881       csp -= (envc + 1) * 4;
882       csp -= (my_argc + 1) * 4;
883       csp -= 4;
884
885       /* Write the target representation of the start-up-value for the
886          stack-pointer suitable for register initialization below.  */
887       bfd_putl32 (csp, sp_init);
888
889       /* If we make this 1M higher; say 8192*1024, we have to take
890          special precautions for pthreads, because pthreads assumes that
891          the memory that low isn't mmapped, and that it can mmap it
892          without fallback in case of failure (and we fail ungracefully
893          long before *that*: the memory isn't accounted for in our mmap
894          list).  */
895       stack_low = (csp - (7168*1024)) & ~8191;
896
897       stacklen = stacktop - stack_low;
898
899       /* Tee hee, we have an executable stack.  Well, it's necessary to
900          test GCC trampolines...  */
901       sim_core_attach (sd, NULL, 0, access_read_write_exec, 0,
902                        stack_low, stacklen,
903                        0, NULL, NULL);
904
905       epp = epp0 = envstart;
906
907       /* Can't use sim_core_write_unaligned_4 without everything
908          initialized when tracing, and then these writes would get into
909          the trace.  */
910 #define write_dword(addr, data)                                         \
911  do                                                                     \
912    {                                                                    \
913      USI data_ = data;                                                  \
914      USI addr_ = addr;                                                  \
915      bfd_putl32 (data_, buf);                                           \
916      if (sim_core_write_buffer (sd, cpu, 0, buf, addr_, 4) != 4)        \
917         goto abandon_chip;                                              \
918    }                                                                    \
919  while (0)
920
921       write_dword (csp, my_argc);
922       csp += 4;
923
924       for (i = 0; i < my_argc; i++, csp += 4)
925         {
926           size_t strln = strlen (prog_argv[i]) + 1;
927
928           if (sim_core_write_buffer (sd, cpu, 0, prog_argv[i], epp, strln)
929               != strln)
930           goto abandon_chip;
931
932           write_dword (csp, envstart + epp - epp0);
933           epp += strln;
934         }
935
936       write_dword (csp, 0);
937       csp += 4;
938
939       for (i = 0; i < envc; i++, csp += 4)
940         {
941           unsigned int strln = strlen (my_environ[i]) + 1;
942
943           if (sim_core_write_buffer (sd, cpu, 0, my_environ[i], epp, strln)
944               != strln)
945             goto abandon_chip;
946
947           write_dword (csp, envstart + epp - epp0);
948           epp += strln;
949         }
950
951       write_dword (csp, 0);
952       csp += 4;
953
954       /* The load address of the executable could presumably be
955          different than the lowest used memory address, but let's
956          stick to simplicity until needed.  And
957          cris_handle_interpreter might change startmem and endmem, so
958          let's set it now.  */
959       exec_load_addr = startmem;
960
961       if (!cris_handle_interpreter (sd, abfd))
962         goto abandon_chip;
963
964       if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
965         for (i = 0; i < sizeof (auxv_entries) / sizeof (auxv_entries[0]); i++)
966           {
967             write_dword (csp, auxv_entries[i].id);
968             write_dword (csp + 4,
969                          auxv_entries[i].efn != NULL
970                          ? (*auxv_entries[i].efn) (abfd)
971                          : auxv_entries[i].val);
972             csp += 4 + 4;
973           }
974     }
975
976   /* Allocate core managed memory if none specified by user.  */
977   if (sim_core_read_buffer (sd, NULL, read_map, &c, startmem, 1) == 0)
978     sim_do_commandf (sd, "memory region 0x%lx,0x%lx", startmem,
979                      endmem - startmem);
980
981   /* Allocate simulator I/O managed memory if none specified by user.  */
982   if (cris_have_900000xxif)
983     {
984       if (sim_core_read_buffer (sd, NULL, read_map, &c, 0x90000000, 1) == 0)
985         sim_core_attach (sd, NULL, 0, access_write, 0, 0x90000000, 0x100,
986                          0, &cris_devices, NULL);
987       else
988         {
989           (*callback->
990            printf_filtered) (callback,
991                              "Seeing --cris-900000xx with memory defined there\n");
992           goto abandon_chip;
993         }
994     }
995
996   /* Establish any remaining configuration options.  */
997   if (sim_config (sd) != SIM_RC_OK)
998     {
999     abandon_chip:
1000       free_state (sd);
1001       return 0;
1002     }
1003
1004   if (sim_post_argv_init (sd) != SIM_RC_OK)
1005     {
1006       free_state (sd);
1007       return 0;
1008     }
1009
1010   /* Open a copy of the cpu descriptor table.  */
1011   {
1012     CGEN_CPU_DESC cd = cris_cgen_cpu_open_1 (STATE_ARCHITECTURE (sd)->printable_name,
1013                                              CGEN_ENDIAN_LITTLE);
1014     for (i = 0; i < MAX_NR_PROCESSORS; ++i)
1015       {
1016         SIM_CPU *cpu = STATE_CPU (sd, i);
1017         CPU_CPU_DESC (cpu) = cd;
1018         CPU_DISASSEMBLER (cpu) = cris_disassemble_insn;
1019
1020         /* See cris_option_handler for the reason why this is needed.  */
1021         CPU_CRIS_MISC_PROFILE (cpu)->flags = STATE_TRACE_FLAGS (sd)[0];
1022
1023         /* Set SP to the stack we allocated above.  */
1024         (* CPU_REG_STORE (cpu)) (cpu, H_GR_SP, (char *) sp_init, 4);
1025
1026         /* Set the simulator environment data.  */
1027         cpu->highest_mmapped_page = NULL;
1028         cpu->endmem = endmem;
1029         cpu->endbrk = endbrk;
1030         cpu->stack_low = stack_low;
1031         cpu->syscalls = 0;
1032         cpu->m1threads = 0;
1033         cpu->threadno = 0;
1034         cpu->max_threadid = 0;
1035         cpu->thread_data = NULL;
1036         memset (cpu->sighandler, 0, sizeof (cpu->sighandler));
1037         cpu->make_thread_cpu_data = NULL;
1038         cpu->thread_cpu_data_size = 0;
1039 #if WITH_HW
1040         cpu->deliver_interrupt = NULL;
1041 #endif
1042       }
1043 #if WITH_HW
1044     /* Always be cycle-accurate and call before/after functions if
1045        with-hardware.  */
1046     sim_profile_set_option (sd, "-model", PROFILE_MODEL_IDX, "on");
1047 #endif
1048   }
1049
1050   /* Initialize various cgen things not done by common framework.
1051      Must be done after cris_cgen_cpu_open.  */
1052   cgen_init (sd);
1053
1054   /* Store in a global so things like cris_dump_regs can be invoked
1055      from the gdb command line.  */
1056   current_state = sd;
1057
1058   cris_set_callbacks (callback);
1059
1060   return sd;
1061 }
1062
1063 void
1064 sim_close (SIM_DESC sd, int quitting ATTRIBUTE_UNUSED)
1065 {
1066   cris_cgen_cpu_close (CPU_CPU_DESC (STATE_CPU (sd, 0)));
1067   sim_module_uninstall (sd);
1068 }
1069 \f
1070 SIM_RC
1071 sim_create_inferior (SIM_DESC sd, struct bfd *abfd,
1072                      char **argv ATTRIBUTE_UNUSED,
1073                      char **envp ATTRIBUTE_UNUSED)
1074 {
1075   SIM_CPU *current_cpu = STATE_CPU (sd, 0);
1076   SIM_ADDR addr;
1077
1078   if (sd != NULL)
1079     addr = cris_start_address != (SIM_ADDR) -1
1080       ? cris_start_address
1081       : (interp_start_addr != 0
1082          ? interp_start_addr
1083          : bfd_get_start_address (abfd));
1084   else
1085     addr = 0;
1086   sim_pc_set (current_cpu, addr);
1087
1088   /* Other simulators have #if 0:d code that says
1089       STATE_ARGV (sd) = sim_copy_argv (argv);
1090       STATE_ENVP (sd) = sim_copy_argv (envp);
1091      Enabling that gives you not-found link-errors for sim_copy_argv.
1092      FIXME: Do archaeology to find out more.  */
1093
1094   return SIM_RC_OK;
1095 }
1096 \f
1097 /* Disassemble an instruction.  */
1098
1099 static void
1100 cris_disassemble_insn (SIM_CPU *cpu,
1101                        const CGEN_INSN *insn ATTRIBUTE_UNUSED,
1102                        const ARGBUF *abuf ATTRIBUTE_UNUSED,
1103                        IADDR pc, char *buf)
1104 {
1105   disassembler_ftype pinsn;
1106   struct disassemble_info disasm_info;
1107   SFILE sfile;
1108   SIM_DESC sd = CPU_STATE (cpu);
1109
1110   sfile.buffer = sfile.current = buf;
1111   INIT_DISASSEMBLE_INFO (disasm_info, (FILE *) &sfile,
1112                          (fprintf_ftype) sim_disasm_sprintf);
1113   disasm_info.endian = BFD_ENDIAN_LITTLE;
1114   disasm_info.read_memory_func = sim_disasm_read_memory;
1115   disasm_info.memory_error_func = sim_disasm_perror_memory;
1116   disasm_info.application_data = (PTR) cpu;
1117   pinsn = cris_get_disassembler (STATE_PROG_BFD (sd));
1118   (*pinsn) (pc, &disasm_info);
1119 }