os_dep.c 171 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
 * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
 * Copyright (c) 1991-1995 by Xerox Corporation.  All rights reserved.
 * Copyright (c) 1996-1999 by Silicon Graphics.  All rights reserved.
 * Copyright (c) 1999 by Hewlett-Packard Company.  All rights reserved.
 *
 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
 * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
 *
 * Permission is hereby granted to use or copy this program
 * for any purpose,  provided the above notices are retained on all copies.
 * Permission to modify the code and to distribute modified code is granted,
 * provided the above notices are retained, and a notice that the code was
 * modified is included with the above copyright notice.
 */

17
18
19
20
21
22
/*
 * Copyright (c) 2014, Jean-Claude Beaudoin.
 *
 * On native Microsoft Windows, function MK_GC_get_stack_base() has been replaced.
 */

23
24
#include "private/gc_priv.h"

25
#if defined(LINUX) && !defined(POWERPC) && !defined(NO_SIGCONTEXT_H)
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# include <linux/version.h>
# if (LINUX_VERSION_CODE <= 0x10400)
    /* Ugly hack to get struct sigcontext_struct definition.  Required  */
    /* for some early 1.3.X releases.  Will hopefully go away soon.     */
    /* in some later Linux releases, asm/sigcontext.h may have to       */
    /* be included instead.                                             */
#   define __KERNEL__
#   include <asm/signal.h>
#   undef __KERNEL__
# else
    /* Kernels prior to 2.1.1 defined struct sigcontext_struct instead of */
    /* struct sigcontext.  libc6 (glibc2) uses "struct sigcontext" in     */
    /* prototypes, so we have to include the top-level sigcontext.h to    */
    /* make sure the former gets defined to be the latter if appropriate. */
#   include <features.h>
#   if 2 <= __GLIBC__
#     if 2 == __GLIBC__ && 0 == __GLIBC_MINOR__
        /* glibc 2.1 no longer has sigcontext.h.  But signal.h          */
        /* has the right declaration for glibc 2.1.                     */
#       include <sigcontext.h>
#     endif /* 0 == __GLIBC_MINOR__ */
47
#   else /* __GLIBC__ < 2 */
48
49
50
      /* libc5 doesn't have <sigcontext.h>: go directly with the kernel   */
      /* one.  Check LINUX_VERSION_CODE to see which we should reference. */
#     include <asm/sigcontext.h>
51
#   endif /* __GLIBC__ < 2 */
52
# endif
53
#endif /* LINUX && !POWERPC */
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

#if !defined(OS2) && !defined(PCR) && !defined(AMIGA) && !defined(MACOS) \
    && !defined(MSWINCE) && !defined(__CC_ARM)
# include <sys/types.h>
# if !defined(MSWIN32)
#   include <unistd.h>
# endif
#endif

#include <stdio.h>
#if defined(MSWINCE) || defined(SN_TARGET_PS3)
# define SIGSEGV 0 /* value is irrelevant */
#else
# include <signal.h>
#endif

70
71
#if defined(UNIX_LIKE) || defined(CYGWIN32) || defined(NACL) \
    || defined(SYMBIAN)
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# include <fcntl.h>
#endif

#if defined(LINUX) || defined(LINUX_STACKBOTTOM)
# include <ctype.h>
#endif

/* Blatantly OS dependent routines, except for those that are related   */
/* to dynamic loading.                                                  */

#ifdef AMIGA
# define MK_GC_AMIGA_DEF
# include "extra/AmigaOS.c"
# undef MK_GC_AMIGA_DEF
#endif

#if defined(MSWIN32) || defined(MSWINCE) || defined(CYGWIN32)
# ifndef WIN32_LEAN_AND_MEAN
#   define WIN32_LEAN_AND_MEAN 1
# endif
# define NOSERVICE
# include <windows.h>
  /* It's not clear this is completely kosher under Cygwin.  But it     */
  /* allows us to get a working MK_GC_get_stack_base.                      */
#endif

#ifdef MACOS
# include <Processes.h>
#endif

#ifdef IRIX5
# include <sys/uio.h>
# include <malloc.h>   /* for locking */
#endif

#if defined(LINUX) || defined(FREEBSD) || defined(SOLARIS) || defined(IRIX5) \
108
    || ((defined(USE_MMAP) || defined(USE_MUNMAP)) && !defined(USE_WINALLOC))
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# define MMAP_SUPPORTED
#endif

#if defined(MMAP_SUPPORTED) || defined(ADD_HEAP_GUARD_PAGES)
# if defined(USE_MUNMAP) && !defined(USE_MMAP)
#   error "invalid config - USE_MUNMAP requires USE_MMAP"
# endif
# include <sys/types.h>
# include <sys/mman.h>
# include <sys/stat.h>
# include <errno.h>
#endif

#ifdef DARWIN
  /* for get_etext and friends */
# include <mach-o/getsect.h>
#endif

#ifdef DJGPP
  /* Apparently necessary for djgpp 2.01.  May cause problems with      */
  /* other versions.                                                    */
  typedef long unsigned int caddr_t;
#endif

#ifdef PCR
# include "il/PCR_IL.h"
# include "th/PCR_ThCtl.h"
# include "mm/PCR_MM.h"
#endif

#if !defined(NO_EXECUTE_PERMISSION)
  STATIC MK_GC_bool MK_GC_pages_executable = TRUE;
#else
  STATIC MK_GC_bool MK_GC_pages_executable = FALSE;
#endif
#define IGNORE_PAGES_EXECUTABLE 1
                        /* Undefined on MK_GC_pages_executable real use.   */

#ifdef NEED_PROC_MAPS
/* We need to parse /proc/self/maps, either to find dynamic libraries,  */
/* and/or to find the register backing store base (IA64).  Do it once   */
/* here.                                                                */

#define READ read

/* Repeatedly perform a read call until the buffer is filled or */
/* we encounter EOF.                                            */
STATIC ssize_t MK_GC_repeat_read(int fd, char *buf, size_t count)
{
    size_t num_read = 0;
    ssize_t result;

    ASSERT_CANCEL_DISABLED();
    while (num_read < count) {
        result = READ(fd, buf + num_read, count - num_read);
        if (result < 0) return result;
        if (result == 0) break;
        num_read += result;
    }
    return num_read;
}

#ifdef THREADS
  /* Determine the length of a file by incrementally reading it into a  */
  /* This would be silly to use on a file supporting lseek, but Linux   */
  /* /proc files usually do not.                                        */
  STATIC size_t MK_GC_get_file_len(int f)
  {
    size_t total = 0;
    ssize_t result;
#   define GET_FILE_LEN_BUF_SZ 500
    char buf[GET_FILE_LEN_BUF_SZ];

    do {
        result = read(f, buf, GET_FILE_LEN_BUF_SZ);
        if (result == -1) return 0;
        total += result;
    } while (result > 0);
    return total;
  }

  STATIC size_t MK_GC_get_maps_len(void)
  {
    int f = open("/proc/self/maps", O_RDONLY);
    size_t result;
    if (f < 0) return 0; /* treat missing file as empty */
    result = MK_GC_get_file_len(f);
    close(f);
    return result;
  }
#endif /* THREADS */

/* Copy the contents of /proc/self/maps to a buffer in our address      */
/* space.  Return the address of the buffer, or zero on failure.        */
/* This code could be simplified if we could determine its size ahead   */
/* of time.                                                             */
MK_GC_INNER char * MK_GC_get_maps(void)
{
    int f;
    ssize_t result;
    static char *maps_buf = NULL;
    static size_t maps_buf_sz = 1;
    size_t maps_size, old_maps_size = 0;

    /* The buffer is essentially static, so there must be a single client. */
    MK_GC_ASSERT(I_HOLD_LOCK());

    /* Note that in the presence of threads, the maps file can  */
    /* essentially shrink asynchronously and unexpectedly as    */
    /* threads that we already think of as dead release their   */
    /* stacks.  And there is no easy way to read the entire     */
    /* file atomically.  This is arguably a misfeature of the   */
    /* /proc/.../maps interface.                                */

    /* Since we don't believe the file can grow                 */
    /* asynchronously, it should suffice to first determine     */
    /* the size (using lseek or read), and then to reread the   */
    /* file.  If the size is inconsistent we have to retry.     */
    /* This only matters with threads enabled, and if we use    */
    /* this to locate roots (not the default).                  */

#   ifdef THREADS
        /* Determine the initial size of /proc/self/maps.       */
        /* Note that lseek doesn't work, at least as of 2.6.15. */
        maps_size = MK_GC_get_maps_len();
        if (0 == maps_size) return 0;
#   else
        maps_size = 4000;       /* Guess */
#   endif

    /* Read /proc/self/maps, growing maps_buf as necessary.     */
    /* Note that we may not allocate conventionally, and        */
    /* thus can't use stdio.                                    */
        do {
            while (maps_size >= maps_buf_sz) {
              /* Grow only by powers of 2, since we leak "too small" buffers.*/
              while (maps_size >= maps_buf_sz) maps_buf_sz *= 2;
              maps_buf = MK_GC_scratch_alloc(maps_buf_sz);
#             ifdef THREADS
                /* Recompute initial length, since we allocated.        */
                /* This can only happen a few times per program         */
                /* execution.                                           */
                maps_size = MK_GC_get_maps_len();
                if (0 == maps_size) return 0;
#             endif
              if (maps_buf == 0) return 0;
            }
            MK_GC_ASSERT(maps_buf_sz >= maps_size + 1);
            f = open("/proc/self/maps", O_RDONLY);
            if (-1 == f) return 0;
#           ifdef THREADS
              old_maps_size = maps_size;
#           endif
            maps_size = 0;
            do {
                result = MK_GC_repeat_read(f, maps_buf, maps_buf_sz-1);
                if (result <= 0)
                  break;
                maps_size += result;
            } while ((size_t)result == maps_buf_sz-1);
            close(f);
            if (result <= 0)
              return 0;
#           ifdef THREADS
              if (maps_size > old_maps_size) {
274
275
276
277
                ABORT_ARG2("Unexpected asynchronous /proc/self/maps growth "
                           "(unregistered thread?)", " from %lu to %lu",
                           (unsigned long)old_maps_size,
                           (unsigned long)maps_size);
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
              }
#           endif
        } while (maps_size >= maps_buf_sz || maps_size < old_maps_size);
                /* In the single-threaded case, the second clause is false. */
        maps_buf[maps_size] = '\0';

        /* Apply fn to result.  */
        return maps_buf;
}

/*
 *  MK_GC_parse_map_entry parses an entry from /proc/self/maps so we can
 *  locate all writable data segments that belong to shared libraries.
 *  The format of one of these entries and the fields we care about
 *  is as follows:
 *  XXXXXXXX-XXXXXXXX r-xp 00000000 30:05 260537     name of mapping...\n
 *  ^^^^^^^^ ^^^^^^^^ ^^^^          ^^
 *  start    end      prot          maj_dev
 *
 *  Note that since about august 2003 kernels, the columns no longer have
 *  fixed offsets on 64-bit kernels.  Hence we no longer rely on fixed offsets
 *  anywhere, which is safer anyway.
 */

/* Assign various fields of the first line in buf_ptr to (*start),      */
/* (*end), (*prot), (*maj_dev) and (*mapping_name).  mapping_name may   */
/* be NULL. (*prot) and (*mapping_name) are assigned pointers into the  */
/* original buffer.                                                     */
306
307
308
309
310
311
312
#if (defined(DYNAMIC_LOADING) && defined(USE_PROC_FOR_LIBRARIES)) \
    || defined(IA64) || defined(INCLUDE_LINUX_THREAD_DESCR) \
    || defined(REDIRECT_MALLOC)
  MK_GC_INNER char *MK_GC_parse_map_entry(char *buf_ptr, ptr_t *start, ptr_t *end,
                                    char **prot, unsigned int *maj_dev,
                                    char **mapping_name)
  {
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
    char *start_start, *end_start, *maj_dev_start;
    char *p;
    char *endp;

    if (buf_ptr == NULL || *buf_ptr == '\0') {
        return NULL;
    }

    p = buf_ptr;
    while (isspace(*p)) ++p;
    start_start = p;
    MK_GC_ASSERT(isxdigit(*start_start));
    *start = (ptr_t)strtoul(start_start, &endp, 16); p = endp;
    MK_GC_ASSERT(*p=='-');

    ++p;
    end_start = p;
    MK_GC_ASSERT(isxdigit(*end_start));
    *end = (ptr_t)strtoul(end_start, &endp, 16); p = endp;
    MK_GC_ASSERT(isspace(*p));

    while (isspace(*p)) ++p;
    MK_GC_ASSERT(*p == 'r' || *p == '-');
    *prot = p;
    /* Skip past protection field to offset field */
       while (!isspace(*p)) ++p; while (isspace(*p)) ++p;
    MK_GC_ASSERT(isxdigit(*p));
    /* Skip past offset field, which we ignore */
          while (!isspace(*p)) ++p; while (isspace(*p)) ++p;
    maj_dev_start = p;
    MK_GC_ASSERT(isxdigit(*maj_dev_start));
    *maj_dev = strtoul(maj_dev_start, NULL, 16);

    if (mapping_name == 0) {
      while (*p && *p++ != '\n');
    } else {
      while (*p && *p != '\n' && *p != '/' && *p != '[') p++;
      *mapping_name = p;
      while (*p && *p++ != '\n');
    }
    return p;
354
355
  }
#endif /* REDIRECT_MALLOC || DYNAMIC_LOADING || IA64 || ... */
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377

#if defined(IA64) || defined(INCLUDE_LINUX_THREAD_DESCR)
  /* Try to read the backing store base from /proc/self/maps.           */
  /* Return the bounds of the writable mapping with a 0 major device,   */
  /* which includes the address passed as data.                         */
  /* Return FALSE if there is no such mapping.                          */
  MK_GC_INNER MK_GC_bool MK_GC_enclosing_mapping(ptr_t addr, ptr_t *startp,
                                        ptr_t *endp)
  {
    char *prot;
    ptr_t my_start, my_end;
    unsigned int maj_dev;
    char *maps = MK_GC_get_maps();
    char *buf_ptr = maps;

    if (0 == maps) return(FALSE);
    for (;;) {
      buf_ptr = MK_GC_parse_map_entry(buf_ptr, &my_start, &my_end,
                                   &prot, &maj_dev, 0);

      if (buf_ptr == NULL) return FALSE;
      if (prot[1] == 'w' && maj_dev == 0) {
378
          if ((word)my_end > (word)addr && (word)my_start <= (word)addr) {
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
            *startp = my_start;
            *endp = my_end;
            return TRUE;
          }
      }
    }
    return FALSE;
  }
#endif /* IA64 || INCLUDE_LINUX_THREAD_DESCR */

#if defined(REDIRECT_MALLOC)
  /* Find the text(code) mapping for the library whose name, after      */
  /* stripping the directory part, starts with nm.                      */
  MK_GC_INNER MK_GC_bool MK_GC_text_mapping(char *nm, ptr_t *startp, ptr_t *endp)
  {
    size_t nm_len = strlen(nm);
    char *prot;
    char *map_path;
    ptr_t my_start, my_end;
    unsigned int maj_dev;
    char *maps = MK_GC_get_maps();
    char *buf_ptr = maps;

    if (0 == maps) return(FALSE);
    for (;;) {
      buf_ptr = MK_GC_parse_map_entry(buf_ptr, &my_start, &my_end,
                                   &prot, &maj_dev, &map_path);

      if (buf_ptr == NULL) return FALSE;
      if (prot[0] == 'r' && prot[1] == '-' && prot[2] == 'x') {
          char *p = map_path;
          /* Set p to point just past last slash, if any. */
            while (*p != '\0' && *p != '\n' && *p != ' ' && *p != '\t') ++p;
412
            while (*p != '/' && (word)p >= (word)map_path) --p;
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
            ++p;
          if (strncmp(nm, p, nm_len) == 0) {
            *startp = my_start;
            *endp = my_end;
            return TRUE;
          }
      }
    }
    return FALSE;
  }
#endif /* REDIRECT_MALLOC */

#ifdef IA64
  static ptr_t backing_store_base_from_proc(void)
  {
    ptr_t my_start, my_end;
    if (!MK_GC_enclosing_mapping(MK_GC_save_regs_in_stack(), &my_start, &my_end)) {
430
        MK_GC_COND_LOG_PRINTF("Failed to find backing store base from /proc\n");
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
        return 0;
    }
    return my_start;
  }
#endif

#endif /* NEED_PROC_MAPS */

#if defined(SEARCH_FOR_DATA_START)
  /* The I386 case can be handled without a search.  The Alpha case     */
  /* used to be handled differently as well, but the rules changed      */
  /* for recent Linux versions.  This seems to be the easiest way to    */
  /* cover all versions.                                                */

# if defined(LINUX) || defined(HURD)
    /* Some Linux distributions arrange to define __data_start.  Some   */
    /* define data_start as a weak symbol.  The latter is technically   */
    /* broken, since the user program may define data_start, in which   */
    /* case we lose.  Nonetheless, we try both, preferring __data_start.*/
    /* We assume gcc-compatible pragmas.        */
#   pragma weak __data_start
    extern int __data_start[];
#   pragma weak data_start
    extern int data_start[];
# endif /* LINUX */
  extern int _end[];

  ptr_t MK_GC_data_start = NULL;

  ptr_t MK_GC_find_limit(ptr_t, MK_GC_bool);

  MK_GC_INNER void MK_GC_init_linux_data_start(void)
  {
464
#   if (defined(LINUX) || defined(HURD)) && !defined(IGNORE_PROG_DATA_START)
465
466
467
      /* Try the easy approaches first: */
      if ((ptr_t)__data_start != 0) {
          MK_GC_data_start = (ptr_t)(__data_start);
468
          MK_GC_ASSERT((word)MK_GC_data_start <= (word)_end);
469
470
471
472
          return;
      }
      if ((ptr_t)data_start != 0) {
          MK_GC_data_start = (ptr_t)(data_start);
473
          MK_GC_ASSERT((word)MK_GC_data_start <= (word)_end);
474
475
          return;
      }
476
477
478
#     ifdef DEBUG_ADD_DEL_ROOTS
        MK_GC_log_printf("__data_start not provided\n");
#     endif
479
#   endif /* LINUX */
480
481
482
483
484
485
486
487

    if (MK_GC_no_dls) {
      /* Not needed, avoids the SIGSEGV caused by       */
      /* MK_GC_find_limit which complicates debugging.     */
      MK_GC_data_start = (ptr_t)_end; /* set data root size to 0 */
      return;
    }

488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
    MK_GC_data_start = MK_GC_find_limit((ptr_t)(_end), FALSE);
  }
#endif /* SEARCH_FOR_DATA_START */

#ifdef ECOS

# ifndef ECOS_MK_GC_MEMORY_SIZE
#   define ECOS_MK_GC_MEMORY_SIZE (448 * 1024)
# endif /* ECOS_MK_GC_MEMORY_SIZE */

  /* FIXME: This is a simple way of allocating memory which is          */
  /* compatible with ECOS early releases.  Later releases use a more    */
  /* sophisticated means of allocating memory than this simple static   */
  /* allocator, but this method is at least bound to work.              */
  static char ecos_gc_memory[ECOS_MK_GC_MEMORY_SIZE];
  static char *ecos_gc_brk = ecos_gc_memory;

  static void *tiny_sbrk(ptrdiff_t increment)
  {
    void *p = ecos_gc_brk;
    ecos_gc_brk += increment;
509
    if ((word)ecos_gc_brk > (word)(ecos_gc_memory + sizeof(ecos_gc_memory))) {
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
      ecos_gc_brk -= increment;
      return NULL;
    }
    return p;
  }
# define sbrk tiny_sbrk
#endif /* ECOS */

#if defined(NETBSD) && defined(__ELF__)
  ptr_t MK_GC_data_start = NULL;
  ptr_t MK_GC_find_limit(ptr_t, MK_GC_bool);

  extern char **environ;

  MK_GC_INNER void MK_GC_init_netbsd_elf(void)
  {
        /* This may need to be environ, without the underscore, for     */
        /* some versions.                                               */
    MK_GC_data_start = MK_GC_find_limit((ptr_t)&environ, FALSE);
  }
#endif /* NETBSD */

532
533
534
535
#ifdef JMP_BUF
  JMP_BUF MK_GC_jmp_buf;  /* JCB */
#endif

536
537
538
539
540
541
542
543
544
545
546
547
548
549
#ifdef OPENBSD
  static struct sigaction old_segv_act;
  STATIC sigjmp_buf MK_GC_jmp_buf_openbsd;

# ifdef THREADS
#   include <sys/syscall.h>
    extern sigset_t __syscall(quad_t, ...);
# endif

  /* Don't use MK_GC_find_limit() because siglongjmp() outside of the      */
  /* signal handler by-passes our userland pthreads lib, leaving        */
  /* SIGSEGV and SIGPROF masked.  Instead, use this custom one that     */
  /* works-around the issues.                                           */

550
  STATIC void MK_GC_fault_handler_openbsd(int sig MK_GC_ATTR_UNUSED)
551
552
553
554
  {
     siglongjmp(MK_GC_jmp_buf_openbsd, 1);
  }

555
  /* Return the first non-addressable location > p or bound.    */
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
  /* Requires the allocation lock.                              */
  STATIC ptr_t MK_GC_find_limit_openbsd(ptr_t p, ptr_t bound)
  {
    static volatile ptr_t result;
             /* Safer if static, since otherwise it may not be  */
             /* preserved across the longjmp.  Can safely be    */
             /* static since it's only called with the          */
             /* allocation lock held.                           */

    struct sigaction act;
    size_t pgsz = (size_t)sysconf(_SC_PAGESIZE);
    MK_GC_ASSERT(I_HOLD_LOCK());

    act.sa_handler = MK_GC_fault_handler_openbsd;
    sigemptyset(&act.sa_mask);
    act.sa_flags = SA_NODEFER | SA_RESTART;
572
    /* act.sa_restorer is deprecated and should not be initialized. */
573
574
575
576
577
578
    sigaction(SIGSEGV, &act, &old_segv_act);

    if (sigsetjmp(MK_GC_jmp_buf_openbsd, 1) == 0) {
      result = (ptr_t)((word)p & ~(pgsz-1));
      for (;;) {
        result += pgsz;
579
        if ((word)result >= (word)bound) {
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
          result = bound;
          break;
        }
        MK_GC_noop1((word)(*result));
      }
    }

#   ifdef THREADS
      /* Due to the siglongjump we need to manually unmask SIGPROF.     */
      __syscall(SYS_sigprocmask, SIG_UNBLOCK, sigmask(SIGPROF));
#   endif

    sigaction(SIGSEGV, &old_segv_act, 0);
    return(result);
  }

  /* Return first addressable location > p or bound.    */
  /* Requires the allocation lock.                      */
  STATIC ptr_t MK_GC_skip_hole_openbsd(ptr_t p, ptr_t bound)
  {
    static volatile ptr_t result;
    static volatile int firstpass;

    struct sigaction act;
    size_t pgsz = (size_t)sysconf(_SC_PAGESIZE);
    MK_GC_ASSERT(I_HOLD_LOCK());

    act.sa_handler = MK_GC_fault_handler_openbsd;
    sigemptyset(&act.sa_mask);
    act.sa_flags = SA_NODEFER | SA_RESTART;
610
    /* act.sa_restorer is deprecated and should not be initialized. */
611
612
613
614
615
616
617
    sigaction(SIGSEGV, &act, &old_segv_act);

    firstpass = 1;
    result = (ptr_t)((word)p & ~(pgsz-1));
    if (sigsetjmp(MK_GC_jmp_buf_openbsd, 1) != 0 || firstpass) {
      firstpass = 0;
      result += pgsz;
618
      if ((word)result >= (word)bound) {
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
        result = bound;
      } else {
        MK_GC_noop1((word)(*result));
      }
    }

    sigaction(SIGSEGV, &old_segv_act, 0);
    return(result);
  }
#endif /* OPENBSD */

# ifdef OS2

# include <stddef.h>

# if !defined(__IBMC__) && !defined(__WATCOMC__) /* e.g. EMX */

struct exe_hdr {
    unsigned short      magic_number;
    unsigned short      padding[29];
    long                new_exe_offset;
};

#define E_MAGIC(x)      (x).magic_number
#define EMAGIC          0x5A4D
#define E_LFANEW(x)     (x).new_exe_offset

struct e32_exe {
    unsigned char       magic_number[2];
    unsigned char       byte_order;
    unsigned char       word_order;
    unsigned long       exe_format_level;
    unsigned short      cpu;
    unsigned short      os;
    unsigned long       padding1[13];
    unsigned long       object_table_offset;
    unsigned long       object_count;
    unsigned long       padding2[31];
};

#define E32_MAGIC1(x)   (x).magic_number[0]
#define E32MAGIC1       'L'
#define E32_MAGIC2(x)   (x).magic_number[1]
#define E32MAGIC2       'X'
#define E32_BORDER(x)   (x).byte_order
#define E32LEBO         0
#define E32_WORDER(x)   (x).word_order
#define E32LEWO         0
#define E32_CPU(x)      (x).cpu
#define E32CPU286       1
#define E32_OBJTAB(x)   (x).object_table_offset
#define E32_OBJCNT(x)   (x).object_count

struct o32_obj {
    unsigned long       size;
    unsigned long       base;
    unsigned long       flags;
    unsigned long       pagemap;
    unsigned long       mapsize;
    unsigned long       reserved;
};

#define O32_FLAGS(x)    (x).flags
#define OBJREAD         0x0001L
#define OBJWRITE        0x0002L
#define OBJINVALID      0x0080L
#define O32_SIZE(x)     (x).size
#define O32_BASE(x)     (x).base

# else  /* IBM's compiler */

/* A kludge to get around what appears to be a header file bug */
# ifndef WORD
#   define WORD unsigned short
# endif
# ifndef DWORD
#   define DWORD unsigned long
# endif

# define EXE386 1
# include <newexe.h>
# include <exe386.h>

# endif  /* __IBMC__ */

# define INCL_DOSEXCEPTIONS
# define INCL_DOSPROCESS
# define INCL_DOSERRORS
# define INCL_DOSMODULEMGR
# define INCL_DOSMEMMGR
# include <os2.h>

# endif /* OS/2 */

/* Find the page size */
MK_GC_INNER word MK_GC_page_size = 0;

#if defined(MSWIN32) || defined(MSWINCE) || defined(CYGWIN32)
# ifndef VER_PLATFORM_WIN32_CE
#   define VER_PLATFORM_WIN32_CE 3
# endif

# if defined(MSWINCE) && defined(THREADS)
    MK_GC_INNER MK_GC_bool MK_GC_dont_query_stack_min = FALSE;
# endif

725
726
  MK_GC_INNER SYSTEM_INFO MK_GC_sysinfo;

727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
  MK_GC_INNER void MK_GC_setpagesize(void)
  {
    GetSystemInfo(&MK_GC_sysinfo);
    MK_GC_page_size = MK_GC_sysinfo.dwPageSize;
#   if defined(MSWINCE) && !defined(_WIN32_WCE_EMULATION)
      {
        OSVERSIONINFO verInfo;
        /* Check the current WinCE version.     */
        verInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
        if (!GetVersionEx(&verInfo))
          ABORT("GetVersionEx failed");
        if (verInfo.dwPlatformId == VER_PLATFORM_WIN32_CE &&
            verInfo.dwMajorVersion < 6) {
          /* Only the first 32 MB of address space belongs to the       */
          /* current process (unless WinCE 6.0+ or emulation).          */
          MK_GC_sysinfo.lpMaximumApplicationAddress = (LPVOID)((word)32 << 20);
#         ifdef THREADS
            /* On some old WinCE versions, it's observed that           */
            /* VirtualQuery calls don't work properly when used to      */
            /* get thread current stack committed minimum.              */
            if (verInfo.dwMajorVersion < 5)
              MK_GC_dont_query_stack_min = TRUE;
#         endif
        }
      }
#   endif
  }

# ifndef CYGWIN32
#   define is_writable(prot) ((prot) == PAGE_READWRITE \
                            || (prot) == PAGE_WRITECOPY \
                            || (prot) == PAGE_EXECUTE_READWRITE \
                            || (prot) == PAGE_EXECUTE_WRITECOPY)
760
#  if 0  /* "#if 0" for MKCL 1.1.3 and later, "#if 1" before. JCB */
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
    /* Return the number of bytes that are writable starting at p.      */
    /* The pointer p is assumed to be page aligned.                     */
    /* If base is not 0, *base becomes the beginning of the             */
    /* allocation region containing p.                                  */
    STATIC word MK_GC_get_writable_length(ptr_t p, ptr_t *base)
    {
      MEMORY_BASIC_INFORMATION buf;
      word result;
      word protect;

      result = VirtualQuery(p, &buf, sizeof(buf));
      if (result != sizeof(buf)) ABORT("Weird VirtualQuery result");
      if (base != 0) *base = (ptr_t)(buf.AllocationBase);
      protect = (buf.Protect & ~(PAGE_GUARD | PAGE_NOCACHE));
      if (!is_writable(protect)) {
        return(0);
      }
      if (buf.State != MEM_COMMIT) return(0);
      return(buf.RegionSize);
    }

    MK_GC_API int MK_GC_CALL MK_GC_get_stack_base(struct MK_GC_stack_base *sb)
    {
      ptr_t trunc_sp = (ptr_t)((word)MK_GC_approx_sp() & ~(MK_GC_page_size - 1));
      /* FIXME: This won't work if called from a deeply recursive       */
      /* client code (and the committed stack space has grown).         */
      word size = MK_GC_get_writable_length(trunc_sp, 0);
      MK_GC_ASSERT(size != 0);
      sb -> mem_base = trunc_sp + size;
      return MK_GC_SUCCESS;
    }
792
793
794
795
796
797
798
799
#  else
    MK_GC_API int MK_GC_CALL MK_GC_get_stack_base(struct MK_GC_stack_base *sb)
    { /* JCB */
      word a_var = 0;
      MEMORY_BASIC_INFORMATION mbi;

      SIZE_T mbi_size = VirtualQuery(&a_var, &mbi, sizeof(mbi));

800
801
      if (mbi_size != sizeof(mbi)) ABORT("Weird VirtualQuery result");

802
803
804
805
      ptr_t stack_top = mbi.BaseAddress + mbi.RegionSize;
      ptr_t stack_base = mbi.AllocationBase;
      word stack_size = stack_top - stack_base;

806
      if (stack_size == 0) ABORT("VirtualQuery reported a stack of size 0");
807
808
809
810
811

      sb -> mem_base = stack_top;
      return MK_GC_SUCCESS;
    }
#  endif
812
813
814
815
816
# else /* CYGWIN32 */
    /* An alternate version for Cygwin (adapted from Dave Korn's        */
    /* gcc version of boehm-gc).                                        */
    MK_GC_API int MK_GC_CALL MK_GC_get_stack_base(struct MK_GC_stack_base *sb)
    {
817
818
819
820
      void * _tlsbase;

      __asm__ ("movl %%fs:4, %0"
               : "=r" (_tlsbase));
821
822
823
824
825
826
827
828
829
830
831
      sb -> mem_base = _tlsbase;
      return MK_GC_SUCCESS;
    }
# endif /* CYGWIN32 */
# define HAVE_GET_STACK_BASE

#else /* !MSWIN32 */
  MK_GC_INNER void MK_GC_setpagesize(void)
  {
#   if defined(MPROTECT_VDB) || defined(PROC_VDB) || defined(USE_MMAP)
      MK_GC_page_size = GETPAGESIZE();
832
      if (!MK_GC_page_size) ABORT("getpagesize failed");
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
#   else
      /* It's acceptable to fake it.    */
      MK_GC_page_size = HBLKSIZE;
#   endif
  }
#endif /* !MSWIN32 */

#ifdef BEOS
# include <kernel/OS.h>

  MK_GC_API int MK_GC_CALL MK_GC_get_stack_base(struct MK_GC_stack_base *sb)
  {
    thread_info th;
    get_thread_info(find_thread(NULL),&th);
    sb->mem_base = th.stack_end;
    return MK_GC_SUCCESS;
  }
# define HAVE_GET_STACK_BASE
#endif /* BEOS */

#ifdef OS2
  MK_GC_API int MK_GC_CALL MK_GC_get_stack_base(struct MK_GC_stack_base *sb)
  {
    PTIB ptib; /* thread information block */
    PPIB ppib;
    if (DosGetInfoBlocks(&ptib, &ppib) != NO_ERROR) {
      ABORT("DosGetInfoBlocks failed");
    }
    sb->mem_base = ptib->tib_pstacklimit;
    return MK_GC_SUCCESS;
  }
# define HAVE_GET_STACK_BASE
#endif /* OS2 */

# ifdef AMIGA
#   define MK_GC_AMIGA_SB
#   include "extra/AmigaOS.c"
#   undef MK_GC_AMIGA_SB
# endif /* AMIGA */

# if defined(NEED_FIND_LIMIT) || defined(UNIX_LIKE)

    typedef void (*MK_GC_fault_handler_t)(int);

#   if defined(SUNOS5SIGS) || defined(IRIX5) || defined(OSF1) \
878
       || defined(HURD) || defined(FREEBSD) || defined(NETBSD)
879
        static struct sigaction old_segv_act;
880
#       if defined(_sigargs) /* !Irix6.x */ \
881
882
883
884
           || defined(HURD) || defined(NETBSD) || defined(FREEBSD)
            static struct sigaction old_bus_act;
#       endif
#   else
885
886
887
888
      static MK_GC_fault_handler_t old_segv_handler;
#     ifdef SIGBUS
        static MK_GC_fault_handler_t old_bus_handler;
#     endif
889
890
891
892
#   endif

    MK_GC_INNER void MK_GC_set_and_save_fault_handler(MK_GC_fault_handler_t h)
    {
893
894
#       if defined(SUNOS5SIGS) || defined(IRIX5) || defined(OSF1) \
            || defined(HURD) || defined(FREEBSD) || defined(NETBSD)
895
896
897
898
899
900
901
902
903
904
905
906
          struct sigaction act;

          act.sa_handler = h;
#         ifdef SIGACTION_FLAGS_NODEFER_HACK
            /* Was necessary for Solaris 2.3 and very temporary */
            /* NetBSD bugs.                                     */
            act.sa_flags = SA_RESTART | SA_NODEFER;
#         else
            act.sa_flags = SA_RESTART;
#         endif

          (void) sigemptyset(&act.sa_mask);
907
          /* act.sa_restorer is deprecated and should not be initialized. */
908
909
910
911
912
913
914
915
#         ifdef MK_GC_IRIX_THREADS
            /* Older versions have a bug related to retrieving and      */
            /* and setting a handler at the same time.                  */
            (void) sigaction(SIGSEGV, 0, &old_segv_act);
            (void) sigaction(SIGSEGV, &act, 0);
#         else
            (void) sigaction(SIGSEGV, &act, &old_segv_act);
#           if defined(IRIX5) && defined(_sigargs) /* Irix 5.x, not 6.x */ \
916
               || defined(HURD) || defined(NETBSD) || defined(FREEBSD)
917
918
919
920
921
              /* Under Irix 5.x or HP/UX, we may get SIGBUS.    */
              /* Pthreads doesn't exist under Irix 5.x, so we   */
              /* don't have to worry in the threads case.       */
              (void) sigaction(SIGBUS, &act, &old_bus_act);
#           endif
922
#         endif /* !MK_GC_IRIX_THREADS */
923
924
925
926
927
928
929
930
931
932
933
934
935
936
#       else
          old_segv_handler = signal(SIGSEGV, h);
#         ifdef SIGBUS
            old_bus_handler = signal(SIGBUS, h);
#         endif
#       endif
    }
# endif /* NEED_FIND_LIMIT || UNIX_LIKE */

# if defined(NEED_FIND_LIMIT) \
     || (defined(USE_PROC_FOR_LIBRARIES) && defined(THREADS))
  /* Some tools to implement HEURISTIC2 */
#   define MIN_PAGE_SIZE 256    /* Smallest conceivable page size, bytes */

937
    STATIC void MK_GC_fault_handler(int sig MK_GC_ATTR_UNUSED)
938
939
940
941
942
943
944
945
946
947
948
949
950
951
    {
        LONGJMP(MK_GC_jmp_buf, 1);
    }

    MK_GC_INNER void MK_GC_setup_temporary_fault_handler(void)
    {
        /* Handler is process-wide, so this should only happen in       */
        /* one thread at a time.                                        */
        MK_GC_ASSERT(I_HOLD_LOCK());
        MK_GC_set_and_save_fault_handler(MK_GC_fault_handler);
    }

    MK_GC_INNER void MK_GC_reset_fault_handler(void)
    {
952
953
#       if defined(SUNOS5SIGS) || defined(IRIX5) || defined(OSF1) \
           || defined(HURD) || defined(FREEBSD) || defined(NETBSD)
954
955
          (void) sigaction(SIGSEGV, &old_segv_act, 0);
#         if defined(IRIX5) && defined(_sigargs) /* Irix 5.x, not 6.x */ \
956
             || defined(HURD) || defined(NETBSD)
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
              (void) sigaction(SIGBUS, &old_bus_act, 0);
#         endif
#       else
          (void) signal(SIGSEGV, old_segv_handler);
#         ifdef SIGBUS
            (void) signal(SIGBUS, old_bus_handler);
#         endif
#       endif
    }

    /* Return the first non-addressable location > p (up) or    */
    /* the smallest location q s.t. [q,p) is addressable (!up). */
    /* We assume that p (up) or p-1 (!up) is addressable.       */
    /* Requires allocation lock.                                */
    STATIC ptr_t MK_GC_find_limit_with_bound(ptr_t p, MK_GC_bool up, ptr_t bound)
    {
        static volatile ptr_t result;
                /* Safer if static, since otherwise it may not be       */
                /* preserved across the longjmp.  Can safely be         */
                /* static since it's only called with the               */
                /* allocation lock held.                                */

        MK_GC_ASSERT(I_HOLD_LOCK());
        MK_GC_setup_temporary_fault_handler();
        if (SETJMP(MK_GC_jmp_buf) == 0) {
            result = (ptr_t)(((word)(p))
                              & ~(MIN_PAGE_SIZE-1));
            for (;;) {
                if (up) {
                    result += MIN_PAGE_SIZE;
987
                    if ((word)result >= (word)bound) {
988
989
990
991
992
                      result = bound;
                      break;
                    }
                } else {
                    result -= MIN_PAGE_SIZE;
993
                    if ((word)result <= (word)bound) {
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
                      result = bound - MIN_PAGE_SIZE;
                                        /* This is to compensate        */
                                        /* further result increment (we */
                                        /* do not modify "up" variable  */
                                        /* since it might be clobbered  */
                                        /* by setjmp otherwise).        */
                      break;
                    }
                }
                MK_GC_noop1((word)(*result));
            }
        }
        MK_GC_reset_fault_handler();
        if (!up) {
            result += MIN_PAGE_SIZE;
        }
        return(result);
    }

    ptr_t MK_GC_find_limit(ptr_t p, MK_GC_bool up)
    {
        return MK_GC_find_limit_with_bound(p, up, up ? (ptr_t)(word)(-1) : 0);
    }
# endif /* NEED_FIND_LIMIT || USE_PROC_FOR_LIBRARIES */

#ifdef HPUX_STACKBOTTOM

#include <sys/param.h>
#include <sys/pstat.h>

  MK_GC_INNER ptr_t MK_GC_get_register_stack_base(void)
  {
    struct pst_vm_status vm_status;

    int i = 0;
    while (pstat_getprocvm(&vm_status, sizeof(vm_status), 0, i++) == 1) {
      if (vm_status.pst_type == PS_RSESTACK) {
        return (ptr_t) vm_status.pst_vaddr;
      }
    }

    /* old way to get the register stackbottom */
    return (ptr_t)(((word)MK_GC_stackbottom - BACKING_STORE_DISPLACEMENT - 1)
                   & ~(BACKING_STORE_ALIGNMENT - 1));
  }

#endif /* HPUX_STACK_BOTTOM */

#ifdef LINUX_STACKBOTTOM

# include <sys/types.h>
# include <sys/stat.h>

# define STAT_SKIP 27   /* Number of fields preceding startstack        */
                        /* field in /proc/self/stat                     */

# ifdef USE_LIBC_PRIVATES
#   pragma weak __libc_stack_end
    extern ptr_t __libc_stack_end;
# endif

# ifdef IA64
#   ifdef USE_LIBC_PRIVATES
#     pragma weak __libc_ia64_register_backing_store_base
      extern ptr_t __libc_ia64_register_backing_store_base;
#   endif

    MK_GC_INNER ptr_t MK_GC_get_register_stack_base(void)
    {
      ptr_t result;

#     ifdef USE_LIBC_PRIVATES
        if (0 != &__libc_ia64_register_backing_store_base
            && 0 != __libc_ia64_register_backing_store_base) {
          /* Glibc 2.2.4 has a bug such that for dynamically linked     */
          /* executables __libc_ia64_register_backing_store_base is     */
          /* defined but uninitialized during constructor calls.        */
          /* Hence we check for both nonzero address and value.         */
          return __libc_ia64_register_backing_store_base;
        }
#     endif
      result = backing_store_base_from_proc();
      if (0 == result) {
          result = MK_GC_find_limit(MK_GC_save_regs_in_stack(), FALSE);
          /* Now seems to work better than constant displacement        */
          /* heuristic used in 6.X versions.  The latter seems to       */
          /* fail for 2.6 kernels.                                      */
      }
      return result;
    }
# endif /* IA64 */

  STATIC ptr_t MK_GC_linux_main_stack_base(void)
  {
    /* We read the stack base value from /proc/self/stat.  We do this   */
    /* using direct I/O system calls in order to avoid calling malloc   */
    /* in case REDIRECT_MALLOC is defined.                              */
#   ifndef STAT_READ
      /* Also defined in pthread_support.c. */
#     define STAT_BUF_SIZE 4096
#     define STAT_READ read
#   endif
          /* Should probably call the real read, if read is wrapped.    */
    char stat_buf[STAT_BUF_SIZE];
    int f;
    word result;
    int i, buf_offset = 0, len;

    /* First try the easy way.  This should work for glibc 2.2  */
    /* This fails in a prelinked ("prelink" command) executable */
    /* since the correct value of __libc_stack_end never        */
    /* becomes visible to us.  The second test works around     */
    /* this.                                                    */
#   ifdef USE_LIBC_PRIVATES
      if (0 != &__libc_stack_end && 0 != __libc_stack_end ) {
#       if defined(IA64)
          /* Some versions of glibc set the address 16 bytes too        */
          /* low while the initialization code is running.              */
          if (((word)__libc_stack_end & 0xfff) + 0x10 < 0x1000) {
            return __libc_stack_end + 0x10;
          } /* Otherwise it's not safe to add 16 bytes and we fall      */
            /* back to using /proc.                                     */
#       elif defined(SPARC)
1117
1118
          /* Older versions of glibc for 64-bit SPARC do not set this   */
          /* variable correctly, it gets set to either zero or one.     */
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
          if (__libc_stack_end != (ptr_t) (unsigned long)0x1)
            return __libc_stack_end;
#       else
          return __libc_stack_end;
#       endif
      }
#   endif
    f = open("/proc/self/stat", O_RDONLY);
    if (f < 0)
      ABORT("Couldn't read /proc/self/stat");
    len = STAT_READ(f, stat_buf, STAT_BUF_SIZE);
    close(f);

    /* Skip the required number of fields.  This number is hopefully    */
    /* constant across all Linux implementations.                       */
    for (i = 0; i < STAT_SKIP; ++i) {
      while (buf_offset < len && isspace(stat_buf[buf_offset++])) {
        /* empty */
      }
      while (buf_offset < len && !isspace(stat_buf[buf_offset++])) {
        /* empty */
      }
    }
    /* Skip spaces.     */
    while (buf_offset < len && isspace(stat_buf[buf_offset])) {
      buf_offset++;
    }
    /* Find the end of the number and cut the buffer there.     */
    for (i = 0; buf_offset + i < len; i++) {
      if (!isdigit(stat_buf[buf_offset + i])) break;
    }
    if (buf_offset + i >= len) ABORT("Could not parse /proc/self/stat");
    stat_buf[buf_offset + i] = '\0';

    result = (word)STRTOULL(&stat_buf[buf_offset], NULL, 10);
    if (result < 0x100000 || (result & (sizeof(word) - 1)) != 0)
      ABORT("Absurd stack bottom value");
    return (ptr_t)result;
  }
#endif /* LINUX_STACKBOTTOM */

#ifdef FREEBSD_STACKBOTTOM
  /* This uses an undocumented sysctl call, but at least one expert     */
  /* believes it will stay.                                             */

# include <unistd.h>
# include <sys/types.h>
# include <sys/sysctl.h>

  STATIC ptr_t MK_GC_freebsd_main_stack_base(void)
  {
    int nm[2] = {CTL_KERN, KERN_USRSTACK};
    ptr_t base;
    size_t len = sizeof(ptr_t);
    int r = sysctl(nm, 2, &base, &len, NULL, 0);
    if (r) ABORT("Error getting main stack base");
    return base;
  }
#endif /* FREEBSD_STACKBOTTOM */

#if defined(ECOS) || defined(NOSYS)
  ptr_t MK_GC_get_main_stack_base(void)
  {
    return STACKBOTTOM;
  }
# define GET_MAIN_STACKBASE_SPECIAL
1185
1186
1187
1188
1189
1190
1191
#elif defined(SYMBIAN)
  extern int MK_GC_get_main_symbian_stack_base(void);
  ptr_t MK_GC_get_main_stack_base(void)
  {
    return (ptr_t)MK_GC_get_main_symbian_stack_base();
  }
# define GET_MAIN_STACKBASE_SPECIAL
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
#elif !defined(BEOS) && !defined(AMIGA) && !defined(OS2) \
      && !defined(MSWIN32) && !defined(MSWINCE) && !defined(CYGWIN32) \
      && !defined(MK_GC_OPENBSD_THREADS) \
      && (!defined(MK_GC_SOLARIS_THREADS) || defined(_STRICT_STDC))

# if defined(LINUX) && defined(USE_GET_STACKBASE_FOR_MAIN)
#   include <pthread.h>
# elif defined(DARWIN) && !defined(NO_PTHREAD_GET_STACKADDR_NP)
    /* We could use pthread_get_stackaddr_np even in case of a  */
    /* single-threaded gclib (there is no -lpthread on Darwin). */
#   include <pthread.h>
#   undef STACKBOTTOM
#   define STACKBOTTOM (ptr_t)pthread_get_stackaddr_np(pthread_self())
# endif

  ptr_t MK_GC_get_main_stack_base(void)
  {
    ptr_t result;
1210
#   if defined(LINUX) && !defined(NO_PTHREAD_GETATTR_NP) \
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
       && (defined(USE_GET_STACKBASE_FOR_MAIN) \
           || (defined(THREADS) && !defined(REDIRECT_MALLOC)))
      pthread_attr_t attr;
      void *stackaddr;
      size_t size;

      if (pthread_getattr_np(pthread_self(), &attr) == 0) {
        if (pthread_attr_getstack(&attr, &stackaddr, &size) == 0
            && stackaddr != NULL) {
          pthread_attr_destroy(&attr);
#         ifdef STACK_GROWS_DOWN
            stackaddr = (char *)stackaddr + size;
#         endif
          return (ptr_t)stackaddr;
        }
        pthread_attr_destroy(&attr);
      }
      WARN("pthread_getattr_np or pthread_attr_getstack failed"
           " for main thread\n", 0);
#   endif
#   ifdef STACKBOTTOM
      result = STACKBOTTOM;
#   else
#     define STACKBOTTOM_ALIGNMENT_M1 ((word)STACK_GRAN - 1)
#     ifdef HEURISTIC1
#       ifdef STACK_GROWS_DOWN
          result = (ptr_t)(((word)MK_GC_approx_sp() + STACKBOTTOM_ALIGNMENT_M1)
                           & ~STACKBOTTOM_ALIGNMENT_M1);
#       else
          result = (ptr_t)((word)MK_GC_approx_sp() & ~STACKBOTTOM_ALIGNMENT_M1);
#       endif
#     endif /* HEURISTIC1 */
#     ifdef LINUX_STACKBOTTOM
         result = MK_GC_linux_main_stack_base();
#     endif
#     ifdef FREEBSD_STACKBOTTOM
         result = MK_GC_freebsd_main_stack_base();
#     endif
#     ifdef HEURISTIC2
        {
          ptr_t sp = MK_GC_approx_sp();
#         ifdef STACK_GROWS_DOWN
            result = MK_GC_find_limit(sp, TRUE);
#           ifdef HEURISTIC2_LIMIT
1255
1256
              if ((word)result > (word)HEURISTIC2_LIMIT
                  && (word)sp < (word)HEURISTIC2_LIMIT) {
1257
1258
1259
1260
1261
1262
                result = HEURISTIC2_LIMIT;
              }
#           endif
#         else
            result = MK_GC_find_limit(sp, FALSE);
#           ifdef HEURISTIC2_LIMIT
1263
1264
              if ((word)result < (word)HEURISTIC2_LIMIT
                  && (word)sp > (word)HEURISTIC2_LIMIT) {
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
                result = HEURISTIC2_LIMIT;
              }
#           endif
#         endif
        }
#     endif /* HEURISTIC2 */
#     ifdef STACK_GROWS_DOWN
        if (result == 0)
          result = (ptr_t)(signed_word)(-sizeof(ptr_t));
#     endif
#   endif
1276
    MK_GC_ASSERT((word)MK_GC_approx_sp() HOTTER_THAN (word)result);
1277
1278
1279
1280
1281
    return(result);
  }
# define GET_MAIN_STACKBASE_SPECIAL
#endif /* !AMIGA, !BEOS, !OPENBSD, !OS2, !Windows */

1282
1283
#if (defined(MK_GC_LINUX_THREADS) || defined(PLATFORM_ANDROID)) \
    && !defined(NO_PTHREAD_GETATTR_NP)
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344

# include <pthread.h>
  /* extern int pthread_getattr_np(pthread_t, pthread_attr_t *); */

  MK_GC_API int MK_GC_CALL MK_GC_get_stack_base(struct MK_GC_stack_base *b)
  {
    pthread_attr_t attr;
    size_t size;
#   ifdef IA64
      DCL_LOCK_STATE;
#   endif

    if (pthread_getattr_np(pthread_self(), &attr) != 0) {
        WARN("pthread_getattr_np failed\n", 0);
        return MK_GC_UNIMPLEMENTED;
    }
    if (pthread_attr_getstack(&attr, &(b -> mem_base), &size) != 0) {
        ABORT("pthread_attr_getstack failed");
    }
    pthread_attr_destroy(&attr);
#   ifdef STACK_GROWS_DOWN
        b -> mem_base = (char *)(b -> mem_base) + size;
#   endif
#   ifdef IA64
      /* We could try backing_store_base_from_proc, but that's safe     */
      /* only if no mappings are being asynchronously created.          */
      /* Subtracting the size from the stack base doesn't work for at   */
      /* least the main thread.                                         */
      LOCK();
      {
        IF_CANCEL(int cancel_state;)
        ptr_t bsp;
        ptr_t next_stack;

        DISABLE_CANCEL(cancel_state);
        bsp = MK_GC_save_regs_in_stack();
        next_stack = MK_GC_greatest_stack_base_below(bsp);
        if (0 == next_stack) {
          b -> reg_base = MK_GC_find_limit(bsp, FALSE);
        } else {
          /* Avoid walking backwards into preceding memory stack and    */
          /* growing it.                                                */
          b -> reg_base = MK_GC_find_limit_with_bound(bsp, FALSE, next_stack);
        }
        RESTORE_CANCEL(cancel_state);
      }
      UNLOCK();
#   endif
    return MK_GC_SUCCESS;
  }
# define HAVE_GET_STACK_BASE
#endif /* MK_GC_LINUX_THREADS */

#if defined(MK_GC_DARWIN_THREADS) && !defined(NO_PTHREAD_GET_STACKADDR_NP)
# include <pthread.h>

  MK_GC_API int MK_GC_CALL MK_GC_get_stack_base(struct MK_GC_stack_base *b)
  {
    /* pthread_get_stackaddr_np() should return stack bottom (highest   */
    /* stack address plus 1).                                           */
    b->mem_base = pthread_get_stackaddr_np(pthread_self());
1345
    MK_GC_ASSERT((word)MK_GC_approx_sp() HOTTER_THAN (word)b->mem_base);
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
    return MK_GC_SUCCESS;
  }
# define HAVE_GET_STACK_BASE
#endif /* MK_GC_DARWIN_THREADS */

#ifdef MK_GC_OPENBSD_THREADS
# include <sys/signal.h>
# include <pthread.h>
# include <pthread_np.h>

  /* Find the stack using pthread_stackseg_np(). */
  MK_GC_API int MK_GC_CALL MK_GC_get_stack_base(struct MK_GC_stack_base *sb)
  {
    stack_t stack;
    if (pthread_stackseg_np(pthread_self(), &stack))
      ABORT("pthread_stackseg_np(self) failed");
    sb->mem_base = stack.ss_sp;
    return MK_GC_SUCCESS;
  }
# define HAVE_GET_STACK_BASE
#endif /* MK_GC_OPENBSD_THREADS */

#if defined(MK_GC_SOLARIS_THREADS) && !defined(_STRICT_STDC)

# include <thread.h>
# include <signal.h>
# include <pthread.h>

  /* These variables are used to cache ss_sp value for the primordial   */
  /* thread (it's better not to call thr_stksegment() twice for this    */
  /* thread - see JDK bug #4352906).                                    */
  static pthread_t stackbase_main_self = 0;
                        /* 0 means stackbase_main_ss_sp value is unset. */
  static void *stackbase_main_ss_sp = NULL;

  MK_GC_API int MK_GC_CALL MK_GC_get_stack_base(struct MK_GC_stack_base *b)
  {
    stack_t s;
    pthread_t self = pthread_self();

    if (self == stackbase_main_self)
      {
        /* If the client calls MK_GC_get_stack_base() from the main thread */
        /* then just return the cached value.                           */
        b -> mem_base = stackbase_main_ss_sp;
        MK_GC_ASSERT(b -> mem_base != NULL);
        return MK_GC_SUCCESS;
      }

    if (thr_stksegment(&s)) {
      /* According to the manual, the only failure error code returned  */
      /* is EAGAIN meaning "the information is not available due to the */
      /* thread is not yet completely initialized or it is an internal  */
      /* thread" - this shouldn't happen here.                          */
      ABORT("thr_stksegment failed");
    }
    /* s.ss_sp holds the pointer to the stack bottom. */
1403
    MK_GC_ASSERT((word)MK_GC_approx_sp() HOTTER_THAN (word)s.ss_sp);
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428

    if (!stackbase_main_self && thr_main() != 0)
      {
        /* Cache the stack base value for the primordial thread (this   */
        /* is done during MK_GC_init, so there is no race).                */
        stackbase_main_ss_sp = s.ss_sp;
        stackbase_main_self = self;
      }

    b -> mem_base = s.ss_sp;
    return MK_GC_SUCCESS;
  }
# define HAVE_GET_STACK_BASE
#endif /* MK_GC_SOLARIS_THREADS */

#ifdef MK_GC_RTEMS_PTHREADS
  MK_GC_API int MK_GC_CALL MK_GC_get_stack_base(struct MK_GC_stack_base *sb)
  {
    sb->mem_base = rtems_get_stack_bottom();
    return MK_GC_SUCCESS;
  }
# define HAVE_GET_STACK_BASE
#endif /* MK_GC_RTEMS_PTHREADS */

#ifndef HAVE_GET_STACK_BASE
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
# ifdef NEED_FIND_LIMIT
    /* Retrieve stack base.                                             */
    /* Using the MK_GC_find_limit version is risky.                        */
    /* On IA64, for example, there is no guard page between the         */
    /* stack of one thread and the register backing store of the        */
    /* next.  Thus this is likely to identify way too large a           */
    /* "stack" and thus at least result in disastrous performance.      */
    /* FIXME - Implement better strategies here.                        */
    MK_GC_API int MK_GC_CALL MK_GC_get_stack_base(struct MK_GC_stack_base *b)
    {
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
      IF_CANCEL(int cancel_state;)
      DCL_LOCK_STATE;

      LOCK();
      DISABLE_CANCEL(cancel_state);  /* May be unnecessary? */
#     ifdef STACK_GROWS_DOWN
        b -> mem_base = MK_GC_find_limit(MK_GC_approx_sp(), TRUE);
#       ifdef IA64
          b -> reg_base = MK_GC_find_limit(MK_GC_save_regs_in_stack(), FALSE);
#       endif
#     else
        b -> mem_base = MK_GC_find_limit(MK_GC_approx_sp(), FALSE);
#     endif
      RESTORE_CANCEL(cancel_state);
      UNLOCK();
      return MK_GC_SUCCESS;
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
    }
# else
    MK_GC_API int MK_GC_CALL MK_GC_get_stack_base(
                                struct MK_GC_stack_base *b MK_GC_ATTR_UNUSED)
    {
#     if defined(GET_MAIN_STACKBASE_SPECIAL) && !defined(THREADS) \
         && !defined(IA64)
        b->mem_base = MK_GC_get_main_stack_base();
        return MK_GC_SUCCESS;
#     else
        return MK_GC_UNIMPLEMENTED;
#     endif
    }
# endif /* !NEED_FIND_LIMIT */
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
#endif /* !HAVE_GET_STACK_BASE */

#ifndef GET_MAIN_STACKBASE_SPECIAL
  /* This is always called from the main thread.  Default implementation. */
  ptr_t MK_GC_get_main_stack_base(void)
  {
    struct MK_GC_stack_base sb;

    if (MK_GC_get_stack_base(&sb) != MK_GC_SUCCESS)
      ABORT("MK_GC_get_stack_base failed");
1479
    MK_GC_ASSERT((word)MK_GC_approx_sp() HOTTER_THAN (word)sb.mem_base);
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
    return (ptr_t)sb.mem_base;
  }
#endif /* !GET_MAIN_STACKBASE_SPECIAL */

/* Register static data segment(s) as roots.  If more data segments are */
/* added later then they need to be registered at that point (as we do  */
/* with SunOS dynamic loading), or MK_GC_mark_roots needs to check for     */
/* them (as we do with PCR).  Called with allocator lock held.          */
# ifdef OS2

void MK_GC_register_data_segments(void)
{
    PTIB ptib;
    PPIB ppib;
    HMODULE module_handle;
#   define PBUFSIZ 512
    UCHAR path[PBUFSIZ];
    FILE * myexefile;
    struct exe_hdr hdrdos;      /* MSDOS header.        */
    struct e32_exe hdr386;      /* Real header for my executable */
1500
    struct o32_obj seg;         /* Current segment */
1501
1502
1503
1504
1505
1506
1507
    int nsegs;

    if (DosGetInfoBlocks(&ptib, &ppib) != NO_ERROR) {
        ABORT("DosGetInfoBlocks failed");
    }
    module_handle = ppib -> pib_hmte;
    if (DosQueryModuleName(module_handle, PBUFSIZ, path) != NO_ERROR) {
1508
        ABORT("DosQueryModuleName failed");
1509
1510
1511
    }
    myexefile = fopen(path, "rb");
    if (myexefile == 0) {
1512
        ABORT_ARG1("Failed to open executable", ": %s", path);
1513
1514
1515
    }
    if (fread((char *)(&hdrdos), 1, sizeof(hdrdos), myexefile)
          < sizeof(hdrdos)) {
1516
        ABORT_ARG1("Could not read MSDOS header", " from: %s", path);
1517
1518
    }
    if (E_MAGIC(hdrdos) != EMAGIC) {
1519
        ABORT_ARG1("Bad DOS magic number", " in file: %s", path);
1520
1521
    }
    if (fseek(myexefile, E_LFANEW(hdrdos), SEEK_SET) != 0) {
1522
        ABORT_ARG1("Bad DOS magic number", " in file: %s", path);
1523
1524
1525
    }
    if (fread((char *)(&hdr386), 1, sizeof(hdr386), myexefile)
          < sizeof(hdr386)) {
1526
        ABORT_ARG1("Could not read OS/2 header", " from: %s", path);
1527
1528
    }
    if (E32_MAGIC1(hdr386) != E32MAGIC1 || E32_MAGIC2(hdr386) != E32MAGIC2) {
1529
        ABORT_ARG1("Bad OS/2 magic number", " in file: %s", path);
1530
1531
    }
    if (E32_BORDER(hdr386) != E32LEBO || E32_WORDER(hdr386) != E32LEWO) {
1532
        ABORT_ARG1("Bad byte order in executable", " file: %s", path);
1533
1534
    }
    if (E32_CPU(hdr386) == E32CPU286) {
1535
        ABORT_ARG1("GC cannot handle 80286 executables", ": %s", path);
1536
1537
1538
    }
    if (fseek(myexefile, E_LFANEW(hdrdos) + E32_OBJTAB(hdr386),
              SEEK_SET) != 0) {
1539
        ABORT_ARG1("Seek to object table failed", " in file: %s", path);
1540
1541
1542
1543
    }
    for (nsegs = E32_OBJCNT(hdr386); nsegs > 0; nsegs--) {
      int flags;
      if (fread((char *)(&seg), 1, sizeof(seg), myexefile) < sizeof(seg)) {
1544
        ABORT_ARG1("Could not read obj table entry", " from file: %s", path);
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
      }
      flags = O32_FLAGS(seg);
      if (!(flags & OBJWRITE)) continue;
      if (!(flags & OBJREAD)) continue;
      if (flags & OBJINVALID) {
          MK_GC_err_printf("Object with invalid pages?\n");
          continue;
      }
      MK_GC_add_roots_inner((ptr_t)O32_BASE(seg),
                         (ptr_t)(O32_BASE(seg)+O32_SIZE(seg)), FALSE);
    }
}

# else /* !OS2 */

# if defined(GWW_VDB)
#   ifndef MEM_WRITE_WATCH
#     define MEM_WRITE_WATCH 0x200000
#   endif
#   ifndef WRITE_WATCH_FLAG_RESET
#     define WRITE_WATCH_FLAG_RESET 1
#   endif

    /* Since we can't easily check whether ULONG_PTR and SIZE_T are     */
    /* defined in Win32 basetsd.h, we define own ULONG_PTR.             */
#   define MK_GC_ULONG_PTR word

    typedef UINT (WINAPI * GetWriteWatch_type)(
                                DWORD, PVOID, MK_GC_ULONG_PTR /* SIZE_T */,
                                PVOID *, MK_GC_ULONG_PTR *, PULONG);
    static GetWriteWatch_type GetWriteWatch_func;
    static DWORD GetWriteWatch_alloc_flag;

#   define MK_GC_GWW_AVAILABLE() (GetWriteWatch_func != NULL)

    static void detect_GetWriteWatch(void)
    {
      static MK_GC_bool done;
      HMODULE hK32;
      if (done)
        return;

#     if defined(MPROTECT_VDB)
        {
          char * str = GETENV("MK_GC_USE_GETWRITEWATCH");
#         if defined(MK_GC_PREFER_MPROTECT_VDB)
            if (str == NULL || (*str == '0' && *(str + 1) == '\0')) {
              /* MK_GC_USE_GETWRITEWATCH is unset or set to "0".           */
              done = TRUE; /* falling back to MPROTECT_VDB strategy.    */
              /* This should work as if GWW_VDB is undefined. */
              return;
            }
#         else
            if (str != NULL && *str == '0' && *(str + 1) == '\0') {
              /* MK_GC_USE_GETWRITEWATCH is set "0".                       */
              done = TRUE; /* falling back to MPROTECT_VDB strategy.    */
              return;
            }
#         endif
        }
#     endif

      hK32 = GetModuleHandle(TEXT("kernel32.dll"));
      if (hK32 != (HMODULE)0 &&
1609
          (GetWriteWatch_func = (GetWriteWatch_type)(void *)GetProcAddress(hK32, "GetWriteWatch")) != NULL) {
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
        /* Also check whether VirtualAlloc accepts MEM_WRITE_WATCH,   */
        /* as some versions of kernel32.dll have one but not the      */
        /* other, making the feature completely broken.               */
        void * page = VirtualAlloc(NULL, MK_GC_page_size,
                                    MEM_WRITE_WATCH | MEM_RESERVE,
                                    PAGE_READWRITE);
        if (page != NULL) {
          PVOID pages[16];
          MK_GC_ULONG_PTR count = 16;
          DWORD page_size;
          /* Check that it actually works.  In spite of some            */
          /* documentation it actually seems to exist on W2K.           */
          /* This test may be unnecessary, but ...                      */
          if (GetWriteWatch_func(WRITE_WATCH_FLAG_RESET,
                                 page, MK_GC_page_size,
                                 pages,
                                 &count,
                                 &page_size) != 0) {
            /* GetWriteWatch always fails. */
            GetWriteWatch_func = NULL;
          } else {
            GetWriteWatch_alloc_flag = MEM_WRITE_WATCH;
          }
1633
          VirtualFree(page, 0 /* dwSize */, MEM_RELEASE);
1634
1635
1636
1637
1638
        } else {
          /* GetWriteWatch will be useless. */
          GetWriteWatch_func = NULL;
        }
      }
1639
#     ifndef SMALL_CONFIG
1640
        if (GetWriteWatch_func == NULL) {
1641
          MK_GC_COND_LOG_PRINTF("Did not find a usable GetWriteWatch()\n");
1642
        } else {
1643
          MK_GC_COND_LOG_PRINTF("Using GetWriteWatch()\n");
1644
        }
1645
#     endif
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
      done = TRUE;
    }

# else
#   define GetWriteWatch_alloc_flag 0
# endif /* !GWW_VDB */

# if defined(MSWIN32) || defined(MSWINCE) || defined(CYGWIN32)

# ifdef MSWIN32
  /* Unfortunately, we have to handle win32s very differently from NT,  */
  /* Since VirtualQuery has very different semantics.  In particular,   */
  /* under win32s a VirtualQuery call on an unmapped page returns an    */
  /* invalid result.  Under NT, MK_GC_register_data_segments is a no-op    */
  /* and all real work is done by MK_GC_register_dynamic_libraries.  Under */
  /* win32s, we cannot find the data segments associated with dll's.    */
  /* We register the main data segment here.                            */
  MK_GC_INNER MK_GC_bool MK_GC_no_win32_dlls = FALSE;
        /* This used to be set for gcc, to avoid dealing with           */
        /* the structured exception handling issues.  But we now have   */
        /* assembly code to do that right.                              */

  MK_GC_INNER MK_GC_bool MK_GC_wnt = FALSE;
         /* This is a Windows NT derivative, i.e. NT, W2K, XP or later. */

  MK_GC_INNER void MK_GC_init_win32(void)
  {
    /* Set MK_GC_wnt.  If we're running under win32s, assume that no DLLs  */
    /* will be loaded.  I doubt anyone still runs win32s, but...        */
    DWORD v = GetVersion();
    MK_GC_wnt = !(v & 0x80000000);
    MK_GC_no_win32_dlls |= ((!MK_GC_wnt) && (v & 0xff) <= 3);
#   ifdef USE_MUNMAP
      if (MK_GC_no_win32_dlls) {
        /* Turn off unmapping for safety (since may not work well with  */
        /* GlobalAlloc).                                                */
        MK_GC_unmap_threshold = 0;
      }
#   endif
  }

  /* Return the smallest address a such that VirtualQuery               */
  /* returns correct results for all addresses between a and start.     */
  /* Assumes VirtualQuery returns correct information for start.        */
  STATIC ptr_t MK_GC_least_described_address(ptr_t start)
  {
    MEMORY_BASIC_INFORMATION buf;
    size_t result;
    LPVOID limit;
    ptr_t p;
    LPVOID q;

    limit = MK_GC_sysinfo.lpMinimumApplicationAddress;
    p = (ptr_t)((word)start & ~(MK_GC_page_size - 1));
    for (;;) {
        q = (LPVOID)(p - MK_GC_page_size);
1702
        if ((word)q > (word)p /* underflow */ || (word)q < (word)limit) break;
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
        result = VirtualQuery(q, &buf, sizeof(buf));
        if (result != sizeof(buf) || buf.AllocationBase == 0) break;
        p = (ptr_t)(buf.AllocationBase);
    }
    return p;
  }
# endif /* MSWIN32 */

# ifndef REDIRECT_MALLOC
  /* We maintain a linked list of AllocationBase values that we know    */
  /* correspond to malloc heap sections.  Currently this is only called */
  /* during a GC.  But there is some hope that for long running         */
  /* programs we will eventually see most heap sections.                */

  /* In the long run, it would be more reliable to occasionally walk    */
  /* the malloc heap with HeapWalk on the default heap.  But that       */
  /* apparently works only for NT-based Windows.                        */

  STATIC size_t MK_GC_max_root_size = 100000; /* Appr. largest root size.  */

1723
# ifdef USE_WINALLOC
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
  /* In the long run, a better data structure would also be nice ...    */
  STATIC struct MK_GC_malloc_heap_list {
    void * allocation_base;
    struct MK_GC_malloc_heap_list *next;
  } *MK_GC_malloc_heap_l = 0;

  /* Is p the base of one of the malloc heap sections we already know   */
  /* about?                                                             */
  STATIC MK_GC_bool MK_GC_is_malloc_heap_base(ptr_t p)
  {
    struct MK_GC_malloc_heap_list *q = MK_GC_malloc_heap_l;

    while (0 != q) {
      if (q -> allocation_base == p) return TRUE;
      q = q -> next;
    }
    return FALSE;
  }

  STATIC void *MK_GC_get_allocation_base(void *p)
  {
    MEMORY_BASIC_INFORMATION buf;
    size_t result = VirtualQuery(p, &buf, sizeof(buf));
    if (result != sizeof(buf)) {
      ABORT("Weird VirtualQuery result");
    }
    return buf.AllocationBase;
  }

  MK_GC_INNER void MK_GC_add_current_malloc_heap(void)
  {
    struct MK_GC_malloc_heap_list *new_l =
                 malloc(sizeof(struct MK_GC_malloc_heap_list));
    void * candidate = MK_GC_get_allocation_base(new_l);

    if (new_l == 0) return;
    if (MK_GC_is_malloc_heap_base(candidate)) {
      /* Try a little harder to find malloc heap.                       */
        size_t req_size = 10000;
        do {
          void *p = malloc(req_size);
          if (0 == p) {
            free(new_l);
            return;
          }
          candidate = MK_GC_get_allocation_base(p);
          free(p);
          req_size *= 2;
        } while (MK_GC_is_malloc_heap_base(candidate)
                 && req_size < MK_GC_max_root_size/10 && req_size < 500000);
        if (MK_GC_is_malloc_heap_base(candidate)) {
          free(new_l);
          return;
        }
    }
1779
1780
    MK_GC_COND_LOG_PRINTF("Found new system malloc AllocationBase at %p\n",
                       candidate);
1781
1782
1783
1784
    new_l -> allocation_base = candidate;
    new_l -> next = MK_GC_malloc_heap_l;
    MK_GC_malloc_heap_l = new_l;
  }
1785
# endif /* USE_WINALLOC */
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797

# endif /* !REDIRECT_MALLOC */

  STATIC word MK_GC_n_heap_bases = 0;      /* See MK_GC_heap_bases.   */

  /* Is p the start of either the malloc heap, or of one of our */
  /* heap sections?                                             */
  MK_GC_INNER MK_GC_bool MK_GC_is_heap_base(ptr_t p)
  {
     unsigned i;
#    ifndef REDIRECT_MALLOC
       if (MK_GC_root_size > MK_GC_max_root_size) MK_GC_max_root_size = MK_GC_root_size;
1798
#      ifdef USE_WINALLOC
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
         if (MK_GC_is_malloc_heap_base(p)) return TRUE;
#      endif
#    endif
     for (i = 0; i < MK_GC_n_heap_bases; i++) {
         if (MK_GC_heap_bases[i] == p) return TRUE;
     }
     return FALSE;
  }

#ifdef MSWIN32
  STATIC void MK_GC_register_root_section(ptr_t static_root)
  {
      MEMORY_BASIC_INFORMATION buf;
      size_t result;
      DWORD protect;
      LPVOID p;
      char * base;
      char * limit, * new_limit;

      if (!MK_GC_no_win32_dlls) return;
      p = base = limit = MK_GC_least_described_address(static_root);
1820
      while ((word)p < (word)MK_GC_sysinfo.lpMaximumApplicationAddress) {
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
        result = VirtualQuery(p, &buf, sizeof(buf));
        if (result != sizeof(buf) || buf.AllocationBase == 0
            || MK_GC_is_heap_base(buf.AllocationBase)) break;
        new_limit = (char *)p + buf.RegionSize;
        protect = buf.Protect;
        if (buf.State == MEM_COMMIT
            && is_writable(protect)) {
            if ((char *)p == limit) {
                limit = new_limit;
            } else {
                if (base != limit) MK_GC_add_roots_inner(base, limit, FALSE);
                base = p;
                limit = new_limit;
            }
        }
1836
        if ((word)p > (word)new_limit /* overflow */) break;
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
        p = (LPVOID)new_limit;
      }
      if (base != limit) MK_GC_add_roots_inner(base, limit, FALSE);
  }
#endif /* MSWIN32 */

  void MK_GC_register_data_segments(void)
  {
#   ifdef MSWIN32
      MK_GC_register_root_section((ptr_t)&MK_GC_pages_executable);
                            /* any other GC global variable would fit too. */
#   endif
  }

# else /* !OS2 && !Windows */

# if (defined(SVR4) || defined(AUX) || defined(DGUX) \
      || (defined(LINUX) && defined(SPARC))) && !defined(PCR)
  ptr_t MK_GC_SysVGetDataStart(size_t max_page_size, ptr_t etext_addr)
  {
    word text_end = ((word)(etext_addr) + sizeof(word) - 1)
                    & ~(sizeof(word) - 1);
        /* etext rounded to word boundary       */
    word next_page = ((text_end + (word)max_page_size - 1)
                      & ~((word)max_page_size - 1));
    word page_offset = (text_end & ((word)max_page_size - 1));
    char * volatile result = (char *)(next_page + page_offset);
    /* Note that this isn't equivalent to just adding           */
    /* max_page_size to &etext if &etext is at a page boundary  */

    MK_GC_setup_temporary_fault_handler();
    if (SETJMP(MK_GC_jmp_buf) == 0) {
        /* Try writing to the address.  */
        *result = *result;
        MK_GC_reset_fault_handler();
    } else {
        MK_GC_reset_fault_handler();
        /* We got here via a longjmp.  The address is not readable.     */
        /* This is known to happen under Solaris 2.4 + gcc, which place */
        /* string constants in the text segment, but after etext.       */
        /* Use plan B.  Note that we now know there is a gap between    */
        /* text and data segments, so plan A bought us something.       */
        result = (char *)MK_GC_find_limit((ptr_t)(DATAEND), FALSE);
    }
    return((ptr_t)result);
  }
# endif

# if defined(FREEBSD) && !defined(PCR) && (defined(I386) || defined(X86_64) \
                                || defined(powerpc) || defined(__powerpc__))

/* Its unclear whether this should be identical to the above, or        */
/* whether it should apply to non-X86 architectures.                    */
/* For now we don't assume that there is always an empty page after     */
/* etext.  But in some cases there actually seems to be slightly more.  */
/* This also deals with holes between read-only data and writable data. */
ptr_t MK_GC_FreeBSDGetDataStart(size_t max_page_size, ptr_t etext_addr)
{
    word text_end = ((word)(etext_addr) + sizeof(word) - 1)
                     & ~(sizeof(word) - 1);
        /* etext rounded to word boundary       */
    volatile word next_page = (text_end + (word)max_page_size - 1)
                              & ~((word)max_page_size - 1);
    volatile ptr_t result = (ptr_t)text_end;
    MK_GC_setup_temporary_fault_handler();
    if (SETJMP(MK_GC_jmp_buf) == 0) {
        /* Try reading at the address.                          */
        /* This should happen before there is another thread.   */
        for (; next_page < (word)(DATAEND); next_page += (word)max_page_size)
            *(volatile char *)next_page;
        MK_GC_reset_fault_handler();
    } else {
        MK_GC_reset_fault_handler();
        /* As above, we go to plan B    */
        result = MK_GC_find_limit((ptr_t)(DATAEND), FALSE);
    }
    return(result);
}

# endif /* FREEBSD */


#ifdef AMIGA

#  define MK_GC_AMIGA_DS
#  include "extra/AmigaOS.c"
#  undef MK_GC_AMIGA_DS

#elif defined(OPENBSD)

/* Depending on arch alignment, there can be multiple holes     */
/* between DATASTART and DATAEND.  Scan in DATASTART .. DATAEND */
/* and register each region.                                    */
void MK_GC_register_data_segments(void)
{
  ptr_t region_start = DATASTART;
  ptr_t region_end;

  for (;;) {
    region_end = MK_GC_find_limit_openbsd(region_start, DATAEND);
    MK_GC_add_roots_inner(region_start, region_end, FALSE);
1938
    if ((word)region_end >= (word)(DATAEND))
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
      break;
    region_start = MK_GC_skip_hole_openbsd(region_end, DATAEND);
  }
}

# else /* !OS2 && !Windows && !AMIGA && !OPENBSD */

void MK_GC_register_data_segments(void)
{
#   if !defined(PCR) && !defined(MACOS)
#     if defined(REDIRECT_MALLOC) && defined(MK_GC_SOLARIS_THREADS)
        /* As of Solaris 2.3, the Solaris threads implementation        */
        /* allocates the data structure for the initial thread with     */
        /* sbrk at process startup.  It needs to be scanned, so that    */
        /* we don't lose some malloc allocated data structures          */
        /* hanging from it.  We're on thin ice here ...                 */
        extern caddr_t sbrk(int);

1957
1958
1959
1960
1961
1962
        MK_GC_ASSERT(DATASTART);
        {
          ptr_t p = (ptr_t)sbrk(0);
          if ((word)(DATASTART) < (word)p)
            MK_GC_add_roots_inner(DATASTART, p, FALSE);
        }
1963
#     else
1964
        MK_GC_ASSERT(DATASTART);
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
        MK_GC_add_roots_inner(DATASTART, (ptr_t)(DATAEND), FALSE);
#       if defined(DATASTART2)
          MK_GC_add_roots_inner(DATASTART2, (ptr_t)(DATAEND2), FALSE);
#       endif
#     endif
#   endif
#   if defined(MACOS)
    {
#   if defined(THINK_C)
        extern void* MK_GC_MacGetDataStart(void);
        /* globals begin above stack and end at a5. */
        MK_GC_add_roots_inner((ptr_t)MK_GC_MacGetDataStart(),
                           (ptr_t)LMGetCurrentA5(), FALSE);
#   else
#     if defined(__MWERKS__)
#       if !__POWERPC__
          extern void* MK_GC_MacGetDataStart(void);
          /* MATTHEW: Function to handle Far Globals (CW Pro 3) */
#         if __option(far_data)
          extern void* MK_GC_MacGetDataEnd(void);
#         endif
          /* globals begin above stack and end at a5. */
          MK_GC_add_roots_inner((ptr_t)MK_GC_MacGetDataStart(),
                             (ptr_t)LMGetCurrentA5(), FALSE);
          /* MATTHEW: Handle Far Globals */
#         if __option(far_data)
      /* Far globals follow he QD globals: */
          MK_GC_add_roots_inner((ptr_t)LMGetCurrentA5(),
                             (ptr_t)MK_GC_MacGetDataEnd(), FALSE);
#         endif
#       else
          extern char __data_start__[], __data_end__[];
          MK_GC_add_roots_inner((ptr_t)&__data_start__,
                             (ptr_t)&__data_end__, FALSE);
#       endif /* __POWERPC__ */
#     endif /* __MWERKS__ */
#   endif /* !THINK_C */
    }
#   endif /* MACOS */

    /* Dynamic libraries are added at every collection, since they may  */
    /* change.                                                          */
}

2009
2010
2011
# endif /* !AMIGA */
# endif /* !MSWIN32 && !MSWINCE */
# endif /* !OS2 */
2012
2013
2014
2015
2016

/*
 * Auxiliary routines for obtaining memory from OS.
 */

2017
2018
# if !defined(OS2) && !defined(PCR) && !defined(AMIGA) \
     && !defined(USE_WINALLOC) && !defined(MACOS) && !defined(DOS4GW) \
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
     && !defined(NONSTOP) && !defined(SN_TARGET_PS3) && !defined(RTEMS) \
     && !defined(__CC_ARM)

# define SBRK_ARG_T ptrdiff_t

#if defined(MMAP_SUPPORTED)

#ifdef USE_MMAP_FIXED
#   define MK_GC_MMAP_FLAGS MAP_FIXED | MAP_PRIVATE
        /* Seems to yield better performance on Solaris 2, but can      */
        /* be unreliable if something is already mapped at the address. */
#else
#   define MK_GC_MMAP_FLAGS MAP_PRIVATE
#endif

#ifdef USE_MMAP_ANON
# define zero_fd -1
# if defined(MAP_ANONYMOUS)
#   define OPT_MAP_ANON MAP_ANONYMOUS
# else
#   define OPT_MAP_ANON MAP_ANON
# endif
#else
  static int zero_fd;
# define OPT_MAP_ANON 0
#endif

#ifndef HEAP_START
#   define HEAP_START ((ptr_t)0)
#endif

2050
2051
2052
2053
#ifdef SYMBIAN
  extern char* MK_GC_get_private_path_and_zero_file(void);
#endif

2054
2055
2056
2057
2058
2059
2060
2061
STATIC ptr_t MK_GC_unix_mmap_get_mem(word bytes)
{
    void *result;
    static ptr_t last_addr = HEAP_START;

#   ifndef USE_MMAP_ANON
      static MK_GC_bool initialized = FALSE;

2062
2063
2064
2065
2066
2067
      if (!EXPECT(initialized, TRUE)) {
#       ifdef SYMBIAN
          char* path = MK_GC_get_private_path_and_zero_file();
          zero_fd = open(path, O_RDWR | O_CREAT, 0666);
          free(path);
#       else
2068
          zero_fd = open("/dev/zero", O_RDONLY);
2069
2070
2071
2072
#       endif
          if (zero_fd == -1)
            ABORT("Could not open /dev/zero");

2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
          fcntl(zero_fd, F_SETFD, FD_CLOEXEC);
          initialized = TRUE;
      }
#   endif

    if (bytes & (MK_GC_page_size - 1)) ABORT("Bad GET_MEM arg");
    result = mmap(last_addr, bytes, (PROT_READ | PROT_WRITE)
                                    | (MK_GC_pages_executable ? PROT_EXEC : 0),
                  MK_GC_MMAP_FLAGS | OPT_MAP_ANON, zero_fd, 0/* offset */);
#   undef IGNORE_PAGES_EXECUTABLE

    if (result == MAP_FAILED) return(0);
    last_addr = (ptr_t)result + bytes + MK_GC_page_size - 1;
    last_addr = (ptr_t)((word)last_addr & ~(MK_GC_page_size - 1));
#   if !defined(LINUX)
      if (last_addr == 0) {
        /* Oops.  We got the end of the address space.  This isn't      */
        /* usable by arbitrary C code, since one-past-end pointers      */
        /* don't work, so we discard it and try again.                  */
        munmap(result, (size_t)(-MK_GC_page_size) - (size_t)result);
                        /* Leave last page mapped, so we can't repeat.  */
        return MK_GC_unix_mmap_get_mem(bytes);
      }
#   else
      MK_GC_ASSERT(last_addr != 0);
#   endif
2099
2100
2101
    if (((word)result % HBLKSIZE) != 0)
      ABORT(
       "MK_GC_unix_get_mem: Memory returned by mmap is not aligned to HBLKSIZE.");
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
    return((ptr_t)result);
}

# endif  /* MMAP_SUPPORTED */

#if defined(USE_MMAP)
  ptr_t MK_GC_unix_get_mem(word bytes)
  {
    return MK_GC_unix_mmap_get_mem(bytes);
  }
#else /* !USE_MMAP */

STATIC ptr_t MK_GC_unix_sbrk_get_mem(word bytes)
{
  ptr_t result;
# ifdef IRIX5
    /* Bare sbrk isn't thread safe.  Play by malloc rules.      */
    /* The equivalent may be needed on other systems as well.   */
    __LOCK_MALLOC();
# endif
  {
    ptr_t cur_brk = (ptr_t)sbrk(0);
    SBRK_ARG_T lsbs = (word)cur_brk & (MK_GC_page_size-1);

    if ((SBRK_ARG_T)bytes < 0) {
        result = 0; /* too big */
        goto out;
    }
    if (lsbs != 0) {
        if((ptr_t)sbrk(MK_GC_page_size - lsbs) == (ptr_t)(-1)) {
            result = 0;
            goto out;
        }
    }
#   ifdef ADD_HEAP_GUARD_PAGES
      /* This is useful for catching severe memory overwrite problems that */
      /* span heap sections.  It shouldn't otherwise be turned on.         */
      {
        ptr_t guard = (ptr_t)sbrk((SBRK_ARG_T)MK_GC_page_size);
        if (mprotect(guard, MK_GC_page_size, PROT_NONE) != 0)
            ABORT("ADD_HEAP_GUARD_PAGES: mprotect failed");
      }
#   endif /* ADD_HEAP_GUARD_PAGES */
    result = (ptr_t)sbrk((SBRK_ARG_T)bytes);
    if (result == (ptr_t)(-1)) result = 0;
  }
 out:
# ifdef IRIX5
    __UNLOCK_MALLOC();
# endif
  return(result);
}

ptr_t MK_GC_unix_get_mem(word bytes)
{
2157
2158
2159
2160
#if __linux && defined(THREADS)
#error "BDWGC will use sbrk() on Linux which is almost surely wrong since it is NOT thread-safe " \
       "and most likely to clash with malloc() et al!"
#endif
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
# if defined(MMAP_SUPPORTED)
    /* By default, we try both sbrk and mmap, in that order.    */
    static MK_GC_bool sbrk_failed = FALSE;
    ptr_t result = 0;

    if (!sbrk_failed) result = MK_GC_unix_sbrk_get_mem(bytes);
    if (0 == result) {
        sbrk_failed = TRUE;
        result = MK_GC_unix_mmap_get_mem(bytes);
    }
    if (0 == result) {
        /* Try sbrk again, in case sbrk memory became available.        */
        result = MK_GC_unix_sbrk_get_mem(bytes);
    }
    return result;
# else /* !MMAP_SUPPORTED */
    return MK_GC_unix_sbrk_get_mem(bytes);
# endif
}

#endif /* !USE_MMAP */

# endif /* UN*X */

# ifdef OS2

void * os2_alloc(size_t bytes)
{
    void * result;

    if (DosAllocMem(&result, bytes, (PAG_READ | PAG_WRITE | PAG_COMMIT)
                                    | (MK_GC_pages_executable ? PAG_EXECUTE : 0))
                    != NO_ERROR) {
        return(0);
    }
    /* FIXME: What's the purpose of this recursion?  (Probably, if      */
    /* DosAllocMem returns memory at 0 address then just retry once.)   */
    if (result == 0) return(os2_alloc(bytes));
    return(result);
}

# endif /* OS2 */

2204
2205
2206
2207
2208
#ifdef MSWINCE
  ptr_t MK_GC_wince_get_mem(word bytes)
  {
    ptr_t result = 0; /* initialized to prevent warning. */
    word i;
2209

2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
    /* Round up allocation size to multiple of page size */
    bytes = (bytes + MK_GC_page_size-1) & ~(MK_GC_page_size-1);

    /* Try to find reserved, uncommitted pages */
    for (i = 0; i < MK_GC_n_heap_bases; i++) {
        if (((word)(-(signed_word)MK_GC_heap_lengths[i])
             & (MK_GC_sysinfo.dwAllocationGranularity-1))
            >= bytes) {
            result = MK_GC_heap_bases[i] + MK_GC_heap_lengths[i];
            break;
        }
    }

    if (i == MK_GC_n_heap_bases) {
        /* Reserve more pages */
        word res_bytes = (bytes + MK_GC_sysinfo.dwAllocationGranularity-1)
                         & ~(MK_GC_sysinfo.dwAllocationGranularity-1);
        /* If we ever support MPROTECT_VDB here, we will probably need to    */
        /* ensure that res_bytes is strictly > bytes, so that VirtualProtect */
        /* never spans regions.  It seems to be OK for a VirtualFree         */
        /* argument to span regions, so we should be OK for now.             */
        result = (ptr_t) VirtualAlloc(NULL, res_bytes,
                                MEM_RESERVE | MEM_TOP_DOWN,
                                MK_GC_pages_executable ? PAGE_EXECUTE_READWRITE :
                                                      PAGE_READWRITE);
        if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result");
            /* If I read the documentation correctly, this can  */
            /* only happen if HBLKSIZE > 64k or not a power of 2.       */
        if (MK_GC_n_heap_bases >= MAX_HEAP_SECTS) ABORT("Too many heap sections");
        if (result == NULL) return NULL;
        MK_GC_heap_bases[MK_GC_n_heap_bases] = result;
        MK_GC_heap_lengths[MK_GC_n_heap_bases] = 0;
        MK_GC_n_heap_bases++;
    }

    /* Commit pages */
    result = (ptr_t) VirtualAlloc(result, bytes, MEM_COMMIT,
                              MK_GC_pages_executable ? PAGE_EXECUTE_READWRITE :
                                                    PAGE_READWRITE);
#   undef IGNORE_PAGES_EXECUTABLE

    if (result != NULL) {
        if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result");
        MK_GC_heap_lengths[i] += bytes