It's now possible to build SDL without any C runtime at all on Windows,
authorSam Lantinga <slouken@libsdl.org>
Mon, 06 Feb 2006 08:28:51 +0000
changeset 1330450721ad5436
parent 1329 bc67bbf87818
child 1331 1cbaeee565b1
It's now possible to build SDL without any C runtime at all on Windows,
using Visual C++ 2005
VisualC.zip
configure.in
include/Makefile.am
include/SDL_audio.h
include/SDL_config.h
include/SDL_ctype.h
include/SDL_endian.h
include/SDL_events.h
include/SDL_getenv.h
include/SDL_mouse.h
include/SDL_rwops.h
include/SDL_stdarg.h
include/SDL_stdlib.h
include/SDL_string.h
include/SDL_syswm.h
include/SDL_thread.h
include/SDL_types.h
include/SDL_video.h
include/SDL_windows.h
src/Makefile.am
src/SDL.c
src/SDL_error.c
src/SDL_fatal.c
src/SDL_getenv.c
src/audio/SDL_audio.c
src/audio/SDL_audiocvt.c
src/audio/SDL_audiomem.c
src/audio/SDL_mixer.c
src/audio/SDL_mixer_MMX_VC.c
src/audio/SDL_mixer_MMX_VC.h
src/audio/SDL_wave.c
src/audio/windib/SDL_dibaudio.c
src/audio/windx5/SDL_dx5audio.c
src/audio/windx5/directx.h
src/cdrom/SDL_cdrom.c
src/cdrom/win32/SDL_syscdrom.c
src/events/SDL_active.c
src/events/SDL_events.c
src/events/SDL_keyboard.c
src/events/SDL_mouse.c
src/events/SDL_quit.c
src/file/SDL_rwops.c
src/joystick/SDL_joystick.c
src/joystick/win32/SDL_mmjoystick.c
src/loadso/windows/SDL_loadso.c
src/stdlib/.cvsignore
src/stdlib/Makefile.am
src/stdlib/SDL_getenv.c
src/stdlib/SDL_malloc.c
src/stdlib/SDL_qsort.c
src/stdlib/SDL_stdlib.c
src/stdlib/SDL_string.c
src/thread/SDL_systhread.h
src/thread/SDL_thread.c
src/thread/generic/SDL_syscond.c
src/thread/generic/SDL_sysmutex.c
src/thread/generic/SDL_syssem.c
src/thread/os2/SDL_systhread.c
src/thread/win32/SDL_sysmutex.c
src/thread/win32/SDL_syssem.c
src/thread/win32/SDL_systhread.c
src/thread/win32/SDL_systhread_c.h
src/thread/win32/win_ce_semaphore.c
src/timer/SDL_timer.c
src/timer/win32/SDL_systimer.c
src/timer/wince/SDL_systimer.c
src/video/Makefile.am
src/video/SDL_RLEaccel.c
src/video/SDL_blit.c
src/video/SDL_blit_0.c
src/video/SDL_blit_1.c
src/video/SDL_blit_A.c
src/video/SDL_blit_N.c
src/video/SDL_bmp.c
src/video/SDL_cursor.c
src/video/SDL_gamma.c
src/video/SDL_memops.h
src/video/SDL_pixels.c
src/video/SDL_surface.c
src/video/SDL_sysvideo.h
src/video/SDL_video.c
src/video/SDL_yuv.c
src/video/SDL_yuv_sw.c
src/video/e_log.h
src/video/e_pow.h
src/video/e_sqrt.h
src/video/fbcon/SDL_fbelo.h
src/video/math_private.h
src/video/mmx.h
src/video/qtopia/SDL_QWin.h
src/video/wincommon/SDL_lowvideo.h
src/video/wincommon/SDL_sysevents.c
src/video/wincommon/SDL_sysmouse.c
src/video/wincommon/SDL_syswm.c
src/video/wincommon/SDL_wingl.c
src/video/windib/SDL_dibevents.c
src/video/windib/SDL_dibvideo.c
src/video/windib/SDL_dibvideo.h
src/video/windx5/SDL_dx5events.c
src/video/windx5/SDL_dx5video.c
src/video/windx5/SDL_dx5yuv.c
src/video/windx5/directx.h
     1.1 Binary file VisualC.zip has changed
     2.1 --- a/configure.in	Sat Feb 04 22:01:44 2006 +0000
     2.2 +++ b/configure.in	Mon Feb 06 08:28:51 2006 +0000
     2.3 @@ -3008,6 +3008,7 @@
     2.4  src/main/macos/Makefile
     2.5  src/main/macosx/Makefile
     2.6  src/main/macosx/Info.plist
     2.7 +src/stdlib/Makefile
     2.8  src/audio/Makefile
     2.9  src/audio/alsa/Makefile
    2.10  src/audio/arts/Makefile
     3.1 --- a/include/Makefile.am	Sat Feb 04 22:01:44 2006 +0000
     3.2 +++ b/include/Makefile.am	Mon Feb 06 08:28:51 2006 +0000
     3.3 @@ -10,8 +10,10 @@
     3.4  	SDL_audio.h		\
     3.5  	SDL_byteorder.h		\
     3.6  	SDL_cdrom.h		\
     3.7 +	SDL_config.h		\
     3.8  	SDL_copying.h		\
     3.9  	SDL_cpuinfo.h		\
    3.10 +	SDL_ctype.h		\
    3.11  	SDL_endian.h		\
    3.12  	SDL_error.h		\
    3.13  	SDL_events.h		\
    3.14 @@ -27,11 +29,15 @@
    3.15  	SDL_opengl.h		\
    3.16  	SDL_quit.h		\
    3.17  	SDL_rwops.h		\
    3.18 +	SDL_stdarg.h		\
    3.19 +	SDL_stdlib.h		\
    3.20 +	SDL_string.h		\
    3.21  	SDL_syswm.h		\
    3.22  	SDL_thread.h		\
    3.23  	SDL_timer.h		\
    3.24  	SDL_types.h		\
    3.25  	SDL_version.h		\
    3.26  	SDL_video.h		\
    3.27 +	SDL_windows.h		\
    3.28  	begin_code.h		\
    3.29  	close_code.h
     4.1 --- a/include/SDL_audio.h	Sat Feb 04 22:01:44 2006 +0000
     4.2 +++ b/include/SDL_audio.h	Mon Feb 06 08:28:51 2006 +0000
     4.3 @@ -25,8 +25,6 @@
     4.4  #ifndef _SDL_audio_h
     4.5  #define _SDL_audio_h
     4.6  
     4.7 -#include <stdio.h>
     4.8 -
     4.9  #include "SDL_main.h"
    4.10  #include "SDL_types.h"
    4.11  #include "SDL_error.h"
     5.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     5.2 +++ b/include/SDL_config.h	Mon Feb 06 08:28:51 2006 +0000
     5.3 @@ -0,0 +1,87 @@
     5.4 +/*
     5.5 +    SDL - Simple DirectMedia Layer
     5.6 +    Copyright (C) 1997-2006 Sam Lantinga
     5.7 +
     5.8 +    This library is free software; you can redistribute it and/or
     5.9 +    modify it under the terms of the GNU Lesser General Public
    5.10 +    License as published by the Free Software Foundation; either
    5.11 +    version 2.1 of the License, or (at your option) any later version.
    5.12 +
    5.13 +    This library is distributed in the hope that it will be useful,
    5.14 +    but WITHOUT ANY WARRANTY; without even the implied warranty of
    5.15 +    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    5.16 +    Lesser General Public License for more details.
    5.17 +
    5.18 +    You should have received a copy of the GNU Lesser General Public
    5.19 +    License along with this library; if not, write to the Free Software
    5.20 +    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    5.21 +
    5.22 +    Sam Lantinga
    5.23 +    slouken@libsdl.org
    5.24 +*/
    5.25 +
    5.26 +#ifndef _SDL_config_h
    5.27 +#define _SDL_config_h
    5.28 +
    5.29 +/* This is a set of defines to configure the SDL features */
    5.30 +
    5.31 +#define HAVE_STDARG_H
    5.32 +
    5.33 +/* Comment this if you want to build without any libc requirements */
    5.34 +#define HAVE_LIBC
    5.35 +#ifdef HAVE_LIBC
    5.36 +
    5.37 +/* Various C library headers */
    5.38 +#define HAVE_CTYPE_H
    5.39 +#define HAVE_STDIO_H
    5.40 +#define HAVE_STDLIB_H
    5.41 +#define HAVE_MALLOC_H
    5.42 +#define HAVE_STRING_H
    5.43 +#if !defined(_WIN32_WCE)
    5.44 +#define HAVE_SIGNAL_H
    5.45 +#endif
    5.46 +
    5.47 +/* Features provided by SDL_stdlib.h */
    5.48 +#if !defined(_WIN32) /* Don't use C runtime versions of these on Windows */
    5.49 +#define HAVE_GETENV
    5.50 +#define HAVE_PUTENV
    5.51 +#endif
    5.52 +#define HAVE_MALLOC
    5.53 +#define HAVE_REALLOC
    5.54 +#define HAVE_FREE
    5.55 +#define HAVE_ALLOCA
    5.56 +/*#define HAVE_QSORT*/
    5.57 +
    5.58 +/* Features provided by SDL_string.h */
    5.59 +#define HAVE_MEMSET
    5.60 +#define HAVE_MEMCPY
    5.61 +#define HAVE_MEMMOVE
    5.62 +#define HAVE_MEMCMP
    5.63 +#define HAVE_STRLEN
    5.64 +#define HAVE_STRCPY
    5.65 +#define HAVE_STRNCPY
    5.66 +/*#define HAVE__STRREV*/
    5.67 +/*#define HAVE__STRUPR*/
    5.68 +/*#define HAVE__STRLWR*/
    5.69 +#define HAVE_STRCHR
    5.70 +#define HAVE_STRRCHR
    5.71 +#define HAVE_STRSTR
    5.72 +/*#define HAVE_ITOA*/
    5.73 +/*#define HAVE__LTOA*/
    5.74 +/*#define HAVE__UITOA*/
    5.75 +/*#define HAVE__ULTOA*/
    5.76 +/*#define HAVE_STRTOL*/
    5.77 +/*#define HAVE__I64TOA*/
    5.78 +/*#define HAVE__UI64TOA*/
    5.79 +/*#define HAVE_STRTOLL*/
    5.80 +#define HAVE_STRCMP
    5.81 +#define HAVE_STRNCMP
    5.82 +/*#define HAVE_STRICMP*/
    5.83 +/*#define HAVE_STRCASECMP*/
    5.84 +#define HAVE_SSCANF
    5.85 +/*#define HAVE_SNPRINTF*/
    5.86 +#define HAVE_VSNPRINTF
    5.87 +
    5.88 +#endif /* HAVE_LIBC */
    5.89 +
    5.90 +#endif /* _SDL_config_h */
     6.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     6.2 +++ b/include/SDL_ctype.h	Mon Feb 06 08:28:51 2006 +0000
     6.3 @@ -0,0 +1,39 @@
     6.4 +/*
     6.5 +    SDL - Simple DirectMedia Layer
     6.6 +    Copyright (C) 1997-2006 Sam Lantinga
     6.7 +
     6.8 +    This library is free software; you can redistribute it and/or
     6.9 +    modify it under the terms of the GNU Lesser General Public
    6.10 +    License as published by the Free Software Foundation; either
    6.11 +    version 2.1 of the License, or (at your option) any later version.
    6.12 +
    6.13 +    This library is distributed in the hope that it will be useful,
    6.14 +    but WITHOUT ANY WARRANTY; without even the implied warranty of
    6.15 +    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    6.16 +    Lesser General Public License for more details.
    6.17 +
    6.18 +    You should have received a copy of the GNU Lesser General Public
    6.19 +    License along with this library; if not, write to the Free Software
    6.20 +    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    6.21 +
    6.22 +    Sam Lantinga
    6.23 +    slouken@libsdl.org
    6.24 +*/
    6.25 +
    6.26 +/* This file contains portable character manipulation functions for SDL */
    6.27 +
    6.28 +#ifndef _SDL_CTYPE_H_
    6.29 +#define _SDL_CTYPE_H_
    6.30 +
    6.31 +#include "SDL_config.h"
    6.32 +
    6.33 +#ifdef HAVE_CTYPE_H
    6.34 +#include <ctype.h>
    6.35 +#else
    6.36 +#define isdigit(X)  (((X) >= '0') && ((X) <= '9'))
    6.37 +#define isspace(X)  (((X) == ' ') || ((X) == '\t') || ((X) == '\r') || ((X) == '\n'))
    6.38 +#define toupper(X)  (((X) >= 'a') && ((X) <= 'z') ? ('A'+((X)-'a')) : (X))
    6.39 +#define tolower(X)  (((X) >= 'A') && ((X) <= 'Z') ? ('a'+((X)-'A')) : (X))
    6.40 +#endif
    6.41 +
    6.42 +#endif /* _SDL_CTYPE_H_ */
     7.1 --- a/include/SDL_endian.h	Sat Feb 04 22:01:44 2006 +0000
     7.2 +++ b/include/SDL_endian.h	Mon Feb 06 08:28:51 2006 +0000
     7.3 @@ -37,8 +37,6 @@
     7.4           and other data sources.
     7.5  */
     7.6  
     7.7 -#include <stdio.h>
     7.8 -
     7.9  #include "SDL_types.h"
    7.10  #include "SDL_rwops.h"
    7.11  #include "SDL_byteorder.h"
     8.1 --- a/include/SDL_events.h	Sat Feb 04 22:01:44 2006 +0000
     8.2 +++ b/include/SDL_events.h	Mon Feb 06 08:28:51 2006 +0000
     8.3 @@ -38,6 +38,10 @@
     8.4  extern "C" {
     8.5  #endif
     8.6  
     8.7 +/* General keyboard/mouse state definitions */
     8.8 +#define SDL_RELEASED	0
     8.9 +#define SDL_PRESSED	1
    8.10 +
    8.11  /* Event enumerations */
    8.12  typedef enum {
    8.13         SDL_NOEVENT = 0,			/* Unused (do not remove) */
     9.1 --- a/include/SDL_getenv.h	Sat Feb 04 22:01:44 2006 +0000
     9.2 +++ b/include/SDL_getenv.h	Mon Feb 06 08:28:51 2006 +0000
     9.3 @@ -23,29 +23,31 @@
     9.4  #ifndef _SDL_getenv_h
     9.5  #define _SDL_getenv_h
     9.6  
     9.7 +#include "SDL_config.h"
     9.8 +
     9.9 +#ifdef HAVE_STDLIB_H
    9.10 +#include <stdlib.h>
    9.11 +#endif
    9.12 +
    9.13  #include "begin_code.h"
    9.14  /* Set up for C function definitions, even when using C++ */
    9.15  #ifdef __cplusplus
    9.16  extern "C" {
    9.17  #endif
    9.18  
    9.19 -/* Not all environments have a working getenv()/putenv() */
    9.20 -
    9.21 -#if defined(macintosh) || defined(WIN32) || defined(_WIN32_WCE)
    9.22 -#define NEED_SDL_GETENV
    9.23 +#ifdef HAVE_GETENV
    9.24 +#define SDL_getenv	getenv
    9.25 +#else
    9.26 +#define getenv		SDL_getenv
    9.27 +extern DECLSPEC char * SDLCALL SDL_getenv(const char *name);
    9.28  #endif
    9.29  
    9.30 -#ifdef NEED_SDL_GETENV
    9.31 -
    9.32 -/* Put a variable of the form "name=value" into the environment */
    9.33 +#ifdef HAVE_PUTENV
    9.34 +#define SDL_putenv	putenv
    9.35 +#else
    9.36 +#define putenv		SDL_putenv
    9.37  extern DECLSPEC int SDLCALL SDL_putenv(const char *variable);
    9.38 -#define putenv(X)   SDL_putenv(X)
    9.39 -
    9.40 -/* Retrieve a variable named "name" from the environment */
    9.41 -extern DECLSPEC char * SDLCALL SDL_getenv(const char *name);
    9.42 -#define getenv(X)     SDL_getenv(X)
    9.43 -
    9.44 -#endif /* NEED_GETENV */
    9.45 +#endif
    9.46  
    9.47  /* Ends C function definitions when using C++ */
    9.48  #ifdef __cplusplus
    10.1 --- a/include/SDL_mouse.h	Sat Feb 04 22:01:44 2006 +0000
    10.2 +++ b/include/SDL_mouse.h	Mon Feb 06 08:28:51 2006 +0000
    10.3 @@ -115,7 +115,7 @@
    10.4     Button 4:	Mouse wheel up	 (may also be a real button)
    10.5     Button 5:	Mouse wheel down (may also be a real button)
    10.6   */
    10.7 -#define SDL_BUTTON(X)		(SDL_PRESSED << ((X)-1))
    10.8 +#define SDL_BUTTON(X)		(1 << ((X)-1))
    10.9  #define SDL_BUTTON_LEFT		1
   10.10  #define SDL_BUTTON_MIDDLE	2
   10.11  #define SDL_BUTTON_RIGHT	3
    11.1 --- a/include/SDL_rwops.h	Sat Feb 04 22:01:44 2006 +0000
    11.2 +++ b/include/SDL_rwops.h	Mon Feb 06 08:28:51 2006 +0000
    11.3 @@ -27,7 +27,11 @@
    11.4  #ifndef _SDL_RWops_h
    11.5  #define _SDL_RWops_h
    11.6  
    11.7 +#include "SDL_config.h"
    11.8 +
    11.9 +#ifdef HAVE_STDIO_H
   11.10  #include <stdio.h>
   11.11 +#endif
   11.12  
   11.13  #include "SDL_types.h"
   11.14  
   11.15 @@ -63,10 +67,12 @@
   11.16  
   11.17  	Uint32 type;
   11.18  	union {
   11.19 +#ifdef HAVE_STDIO_H
   11.20  	    struct {
   11.21  		int autoclose;
   11.22  	 	FILE *fp;
   11.23  	    } stdio;
   11.24 +#endif
   11.25  	    struct {
   11.26  		Uint8 *base;
   11.27  	 	Uint8 *here;
   11.28 @@ -84,7 +90,9 @@
   11.29  
   11.30  extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromFile(const char *file, const char *mode);
   11.31  
   11.32 +#ifdef HAVE_STDIO_H
   11.33  extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromFP(FILE *fp, int autoclose);
   11.34 +#endif
   11.35  
   11.36  extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromMem(void *mem, int size);
   11.37  extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromConstMem(const void *mem, int size);
   11.38 @@ -92,9 +100,13 @@
   11.39  extern DECLSPEC SDL_RWops * SDLCALL SDL_AllocRW(void);
   11.40  extern DECLSPEC void SDLCALL SDL_FreeRW(SDL_RWops *area);
   11.41  
   11.42 +#define RW_SEEK_SET	0	/* Seek from the beginning of data */
   11.43 +#define RW_SEEK_CUR	1	/* Seek relative to current read point */
   11.44 +#define RW_SEEK_END	2	/* Seek relative to the end of data */
   11.45 +
   11.46  /* Macros to easily read and write from an SDL_RWops structure */
   11.47  #define SDL_RWseek(ctx, offset, whence)	(ctx)->seek(ctx, offset, whence)
   11.48 -#define SDL_RWtell(ctx)			(ctx)->seek(ctx, 0, SEEK_CUR)
   11.49 +#define SDL_RWtell(ctx)			(ctx)->seek(ctx, 0, RW_SEEK_CUR)
   11.50  #define SDL_RWread(ctx, ptr, size, n)	(ctx)->read(ctx, ptr, size, n)
   11.51  #define SDL_RWwrite(ctx, ptr, size, n)	(ctx)->write(ctx, ptr, size, n)
   11.52  #define SDL_RWclose(ctx)		(ctx)->close(ctx)
    12.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    12.2 +++ b/include/SDL_stdarg.h	Mon Feb 06 08:28:51 2006 +0000
    12.3 @@ -0,0 +1,34 @@
    12.4 +/*
    12.5 +    SDL - Simple DirectMedia Layer
    12.6 +    Copyright (C) 1997-2006 Sam Lantinga
    12.7 +
    12.8 +    This library is free software; you can redistribute it and/or
    12.9 +    modify it under the terms of the GNU Lesser General Public
   12.10 +    License as published by the Free Software Foundation; either
   12.11 +    version 2.1 of the License, or (at your option) any later version.
   12.12 +
   12.13 +    This library is distributed in the hope that it will be useful,
   12.14 +    but WITHOUT ANY WARRANTY; without even the implied warranty of
   12.15 +    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   12.16 +    Lesser General Public License for more details.
   12.17 +
   12.18 +    You should have received a copy of the GNU Lesser General Public
   12.19 +    License along with this library; if not, write to the Free Software
   12.20 +    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
   12.21 +
   12.22 +    Sam Lantinga
   12.23 +    slouken@libsdl.org
   12.24 +*/
   12.25 +
   12.26 +#ifndef _SDL_stdarg_h
   12.27 +#define _SDL_stdarg_h
   12.28 +
   12.29 +#include "SDL_config.h"
   12.30 +
   12.31 +#ifdef HAVE_STDARG_H
   12.32 +#include <stdarg.h>
   12.33 +#else
   12.34 +#error Need stdarg.h equivalent for this platform
   12.35 +#endif
   12.36 +
   12.37 +#endif /* _SDL_stdarg_h */
    13.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    13.2 +++ b/include/SDL_stdlib.h	Mon Feb 06 08:28:51 2006 +0000
    13.3 @@ -0,0 +1,105 @@
    13.4 +/*
    13.5 +    SDL - Simple DirectMedia Layer
    13.6 +    Copyright (C) 1997-2006 Sam Lantinga
    13.7 +
    13.8 +    This library is free software; you can redistribute it and/or
    13.9 +    modify it under the terms of the GNU Lesser General Public
   13.10 +    License as published by the Free Software Foundation; either
   13.11 +    version 2.1 of the License, or (at your option) any later version.
   13.12 +
   13.13 +    This library is distributed in the hope that it will be useful,
   13.14 +    but WITHOUT ANY WARRANTY; without even the implied warranty of
   13.15 +    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   13.16 +    Lesser General Public License for more details.
   13.17 +
   13.18 +    You should have received a copy of the GNU Lesser General Public
   13.19 +    License along with this library; if not, write to the Free Software
   13.20 +    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
   13.21 +
   13.22 +    Sam Lantinga
   13.23 +    slouken@libsdl.org
   13.24 +*/
   13.25 +
   13.26 +#ifndef _SDL_stdlib_h
   13.27 +#define _SDL_stdlib_h
   13.28 +
   13.29 +#include "SDL_config.h"
   13.30 +
   13.31 +/* AIX requires this to be the first thing in the file.  */
   13.32 +#ifndef __GNUC__
   13.33 +# if HAVE_ALLOCA_H
   13.34 +#  include <alloca.h>
   13.35 +# else
   13.36 +#  ifdef _AIX
   13.37 + #pragma alloca
   13.38 +#  else
   13.39 +#   ifndef alloca /* predefined by HP cc +Olibcalls */
   13.40 +char *alloca ();
   13.41 +#   endif
   13.42 +#  endif
   13.43 +# endif
   13.44 +#endif
   13.45 +
   13.46 +#ifdef HAVE_STDLIB_H
   13.47 +#include <stdlib.h>
   13.48 +#endif
   13.49 +
   13.50 +#ifdef HAVE_MALLOC_H
   13.51 +#include <malloc.h>
   13.52 +#endif
   13.53 +
   13.54 +#include "SDL_types.h"
   13.55 +#include "SDL_stdarg.h"
   13.56 +#include "SDL_getenv.h"
   13.57 +
   13.58 +
   13.59 +#include "begin_code.h"
   13.60 +/* Set up for C function definitions, even when using C++ */
   13.61 +#ifdef __cplusplus
   13.62 +extern "C" {
   13.63 +#endif
   13.64 +
   13.65 +#ifdef HAVE_MALLOC
   13.66 +#define SDL_malloc	malloc
   13.67 +#else
   13.68 +#define malloc		SDL_malloc
   13.69 +extern DECLSPEC void * SDLCALL SDL_malloc(size_t size);
   13.70 +#endif
   13.71 +
   13.72 +#ifdef HAVE_REALLOC
   13.73 +#define SDL_realloc	realloc
   13.74 +#else
   13.75 +#define realloc		SDL_realloc
   13.76 +extern DECLSPEC void * SDLCALL SDL_realloc(void *mem, size_t size);
   13.77 +#endif
   13.78 +
   13.79 +#ifdef HAVE_FREE
   13.80 +#define SDL_free	free
   13.81 +#else
   13.82 +#define free		SDL_free
   13.83 +extern DECLSPEC void SDLCALL SDL_free(void *mem);
   13.84 +#endif
   13.85 +
   13.86 +#ifdef HAVE_ALLOCA
   13.87 +#define SDL_stack_alloc(type, count)    (type*)alloca(sizeof(type)*count)
   13.88 +#define SDL_stack_free(data)
   13.89 +#else
   13.90 +#define SDL_stack_alloc(type, count)    SDL_malloc(sizeof(type)*count)
   13.91 +#define SDL_stack_free(data)            SDL_free(data)
   13.92 +#endif
   13.93 +
   13.94 +#ifdef HAVE_QSORT
   13.95 +#define SDL_qsort	qsort
   13.96 +#else
   13.97 +#define qsort		SDL_qsort
   13.98 +extern DECLSPEC void SDLCALL SDL_qsort(void *base, size_t nmemb, size_t size,
   13.99 +           int (*compare)(const void *, const void *));
  13.100 +#endif
  13.101 +
  13.102 +/* Ends C function definitions when using C++ */
  13.103 +#ifdef __cplusplus
  13.104 +}
  13.105 +#endif
  13.106 +#include "close_code.h"
  13.107 +
  13.108 +#endif /* _SDL_stdlib_h */
    14.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    14.2 +++ b/include/SDL_string.h	Mon Feb 06 08:28:51 2006 +0000
    14.3 @@ -0,0 +1,359 @@
    14.4 +/*
    14.5 +    SDL - Simple DirectMedia Layer
    14.6 +    Copyright (C) 1997-2006 Sam Lantinga
    14.7 +
    14.8 +    This library is free software; you can redistribute it and/or
    14.9 +    modify it under the terms of the GNU Lesser General Public
   14.10 +    License as published by the Free Software Foundation; either
   14.11 +    version 2.1 of the License, or (at your option) any later version.
   14.12 +
   14.13 +    This library is distributed in the hope that it will be useful,
   14.14 +    but WITHOUT ANY WARRANTY; without even the implied warranty of
   14.15 +    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   14.16 +    Lesser General Public License for more details.
   14.17 +
   14.18 +    You should have received a copy of the GNU Lesser General Public
   14.19 +    License along with this library; if not, write to the Free Software
   14.20 +    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
   14.21 +
   14.22 +    Sam Lantinga
   14.23 +    slouken@libsdl.org
   14.24 +*/
   14.25 +
   14.26 +/* This file contains portable string manipulation functions for SDL */
   14.27 +
   14.28 +#ifndef _SDL_string_h
   14.29 +#define _SDL_string_h
   14.30 +
   14.31 +#include "SDL_config.h"
   14.32 +
   14.33 +#ifdef HAVE_STDIO_H
   14.34 +#include <stdio.h>	/* For snprintf() and friends */
   14.35 +#endif
   14.36 +
   14.37 +#ifdef HAVE_STRING_H
   14.38 +#include <string.h>
   14.39 +#endif
   14.40 +
   14.41 +#include "SDL_types.h"
   14.42 +#include "SDL_stdarg.h"
   14.43 +
   14.44 +#include "begin_code.h"
   14.45 +/* Set up for C function definitions, even when using C++ */
   14.46 +#ifdef __cplusplus
   14.47 +extern "C" {
   14.48 +#endif
   14.49 +
   14.50 +#ifndef HAVE_MEMSET
   14.51 +#define memset          SDL_memset
   14.52 +#endif
   14.53 +#ifndef SDL_memset
   14.54 +extern DECLSPEC void * SDLCALL SDL_memset(void *dst, int c, size_t len);
   14.55 +#endif
   14.56 +
   14.57 +#if defined(__GNUC__) && defined(i386)
   14.58 +#define SDL_memset4(dst, val, len)				\
   14.59 +do {								\
   14.60 +	int u0, u1, u2;						\
   14.61 +	__asm__ __volatile__ (					\
   14.62 +		"cld\n\t"					\
   14.63 +		"rep ; stosl\n\t"				\
   14.64 +		: "=&D" (u0), "=&a" (u1), "=&c" (u2)		\
   14.65 +		: "0" (dst), "1" (val), "2" ((Uint32)(len))	\
   14.66 +		: "memory" );					\
   14.67 +} while(0)
   14.68 +#endif
   14.69 +#ifndef SDL_memset4
   14.70 +#define SDL_memset4(dst, val, len)		\
   14.71 +do {						\
   14.72 +	unsigned _count = (len);		\
   14.73 +	unsigned _n = (_count + 3) / 4;		\
   14.74 +	Uint32 *_p = (Uint32 *)(dst);		\
   14.75 +	Uint32 _val = (val);			\
   14.76 +        switch (_count % 4) {			\
   14.77 +        case 0: do {    *_p++ = _val;		\
   14.78 +        case 3:         *_p++ = _val;		\
   14.79 +        case 2:         *_p++ = _val;		\
   14.80 +        case 1:         *_p++ = _val;		\
   14.81 +		} while ( --_n );		\
   14.82 +	}					\
   14.83 +} while(0)
   14.84 +#endif
   14.85 +
   14.86 +#if defined(__GNUC__) && defined(i386)
   14.87 +#define SDL_memcpy(dst, src, len)					  \
   14.88 +do {									  \
   14.89 +	int u0, u1, u2;						  	  \
   14.90 +	__asm__ __volatile__ (						  \
   14.91 +		"cld\n\t"						  \
   14.92 +		"rep ; movsl\n\t"					  \
   14.93 +		"testb $2,%b4\n\t"					  \
   14.94 +		"je 1f\n\t"						  \
   14.95 +		"movsw\n"						  \
   14.96 +		"1:\ttestb $1,%b4\n\t"					  \
   14.97 +		"je 2f\n\t"						  \
   14.98 +		"movsb\n"						  \
   14.99 +		"2:"							  \
  14.100 +		: "=&c" (u0), "=&D" (u1), "=&S" (u2)			  \
  14.101 +		: "0" ((unsigned)(len)/4), "q" (len), "1" (dst),"2" (src) \
  14.102 +		: "memory" );						  \
  14.103 +} while(0)
  14.104 +#define SDL_memcpy4(dst, src, len)				\
  14.105 +do {								\
  14.106 +	int ecx, edi, esi;					\
  14.107 +	__asm__ __volatile__ (					\
  14.108 +		"cld\n\t"					\
  14.109 +		"rep ; movsl"					\
  14.110 +		: "=&c" (ecx), "=&D" (edi), "=&S" (esi)		\
  14.111 +		: "0" ((unsigned)(len)), "1" (dst), "2" (src)	\
  14.112 +		: "memory" );					\
  14.113 +} while(0)
  14.114 +#endif
  14.115 +#ifndef HAVE_MEMCPY
  14.116 +#define memcpy          SDL_memcpy
  14.117 +#endif
  14.118 +#ifndef SDL_memcpy
  14.119 +extern DECLSPEC void * SDLCALL SDL_memcpy(void *dst, const void *src, size_t len);
  14.120 +#endif
  14.121 +
  14.122 +#if defined(__GNUC__) && defined(i386)
  14.123 +#define SDL_memcpy4(dst, src, len)				\
  14.124 +do {								\
  14.125 +	int ecx, edi, esi;					\
  14.126 +	__asm__ __volatile__ (					\
  14.127 +		"cld\n\t"					\
  14.128 +		"rep ; movsl"					\
  14.129 +		: "=&c" (ecx), "=&D" (edi), "=&S" (esi)		\
  14.130 +		: "0" ((unsigned)(len)), "1" (dst), "2" (src)	\
  14.131 +		: "memory" );					\
  14.132 +} while(0)
  14.133 +#endif
  14.134 +#ifndef SDL_memcpy4
  14.135 +#define SDL_memcpy4(dst, src, len)	SDL_memcpy(dst, src, (len) << 2)
  14.136 +#endif
  14.137 +
  14.138 +#if defined(__GNUC__) && defined(i386)
  14.139 +#define SDL_revcpy(dst, src, len)			\
  14.140 +do {							\
  14.141 +	int u0, u1, u2;					\
  14.142 +	char *dstp = (char *)(dst);			\
  14.143 +	char *srcp = (char *)(src);			\
  14.144 +	int n = (len);					\
  14.145 +	if ( n >= 4 ) {					\
  14.146 +	__asm__ __volatile__ (				\
  14.147 +		"std\n\t"				\
  14.148 +		"rep ; movsl\n\t"			\
  14.149 +		: "=&c" (u0), "=&D" (u1), "=&S" (u2)	\
  14.150 +		: "0" (n >> 2),				\
  14.151 +		  "1" (dstp+(n-4)), "2" (srcp+(n-4))	\
  14.152 +		: "memory" );				\
  14.153 +	}						\
  14.154 +	switch (n & 3) {				\
  14.155 +		case 3: dstp[2] = srcp[2];		\
  14.156 +		case 2: dstp[1] = srcp[1];		\
  14.157 +		case 1: dstp[0] = srcp[0];		\
  14.158 +			break;				\
  14.159 +		default:				\
  14.160 +			break;				\
  14.161 +	}						\
  14.162 +} while(0)
  14.163 +#endif
  14.164 +#ifndef SDL_revcpy
  14.165 +extern DECLSPEC void * SDLCALL SDL_revcpy(void *dst, const void *src, size_t len);
  14.166 +#endif
  14.167 +
  14.168 +#ifndef HAVE_MEMMOVE
  14.169 +#define memmove         SDL_memmove
  14.170 +#endif
  14.171 +#define SDL_memmove(dst, src, len)			\
  14.172 +do {							\
  14.173 +	if ( dst < src ) {				\
  14.174 +		SDL_memcpy(dst, src, len);		\
  14.175 +	} else {					\
  14.176 +		SDL_revcpy(dst, src, len);		\
  14.177 +	}						\
  14.178 +} while(0)
  14.179 +
  14.180 +#ifndef HAVE_MEMCMP
  14.181 +#define memcmp          SDL_memcmp
  14.182 +#endif
  14.183 +#ifndef SDL_memcmp
  14.184 +extern DECLSPEC int SDLCALL SDL_memcmp(const void *s1, const void *s2, size_t len);
  14.185 +#endif
  14.186 +
  14.187 +#ifdef HAVE_STRLEN
  14.188 +#define SDL_strlen      strlen
  14.189 +#else
  14.190 +#define strlen          SDL_strlen
  14.191 +extern DECLSPEC size_t SDLCALL SDL_strlen(const char *string);
  14.192 +#endif
  14.193 +
  14.194 +#ifdef HAVE_STRCPY
  14.195 +#define SDL_strcpy     strcpy
  14.196 +#else
  14.197 +#define strcpy         SDL_strcpy
  14.198 +extern DECLSPEC char * SDLCALL SDL_strcpy(char *dst, const char *src);
  14.199 +#endif
  14.200 +
  14.201 +#ifdef HAVE_STRNCPY
  14.202 +#define SDL_strncpy     strncpy
  14.203 +#else
  14.204 +#define strncpy         SDL_strncpy
  14.205 +extern DECLSPEC char * SDLCALL SDL_strncpy(char *dst, const char *src, size_t maxlen);
  14.206 +#endif
  14.207 +
  14.208 +#ifdef HAVE__STRREV
  14.209 +#define SDL_strrev      _strrev
  14.210 +#else
  14.211 +#define _strrev	        SDL_strrev
  14.212 +extern DECLSPEC char * SDLCALL SDL_strrev(char *string);
  14.213 +#endif
  14.214 +
  14.215 +#ifdef HAVE__STRUPR
  14.216 +#define SDL_strupr      _strupr
  14.217 +#else
  14.218 +#define _strupr         SDL_strupr
  14.219 +extern DECLSPEC char * SDLCALL SDL_strupr(char *string);
  14.220 +#endif
  14.221 +
  14.222 +#ifdef HAVE__STRLWR
  14.223 +#define SDL_strlwr      _strlwr
  14.224 +#else
  14.225 +#define _strlwr         SDL_strlwr
  14.226 +extern DECLSPEC char * SDLCALL SDL_strlwr(char *string);
  14.227 +#endif
  14.228 +
  14.229 +#ifdef HAVE_STRCHR
  14.230 +#define SDL_strchr      strchr
  14.231 +#else
  14.232 +#define strchr          SDL_strchr
  14.233 +extern DECLSPEC char * SDLCALL SDL_strchr(const char *string, int c);
  14.234 +#endif
  14.235 +
  14.236 +#ifdef HAVE_STRRCHR
  14.237 +#define SDL_strrchr     strrchr
  14.238 +#else
  14.239 +#define strrchr         SDL_strrchr
  14.240 +extern DECLSPEC char * SDLCALL SDL_strrchr(const char *string, int c);
  14.241 +#endif
  14.242 +
  14.243 +#ifdef HAVE_STRSTR
  14.244 +#define SDL_strstr      strstr
  14.245 +#else
  14.246 +#define strstr          SDL_strstr
  14.247 +extern DECLSPEC char * SDLCALL SDL_strstr(const char *haystack, const char *needle);
  14.248 +#endif
  14.249 +
  14.250 +#ifdef HAVE_ITOA
  14.251 +#define SDL_itoa        itoa
  14.252 +#else
  14.253 +#define itoa            SDL_itoa
  14.254 +#define SDL_itoa(value, string, radix)	SDL_ltoa((long)value, string, radix)
  14.255 +#endif
  14.256 +
  14.257 +#ifdef HAVE__LTOA
  14.258 +#define SDL_ltoa        _ltoa
  14.259 +#else
  14.260 +#define _ltoa        SDL_ltoa
  14.261 +extern DECLSPEC char * SDLCALL SDL_ltoa(long value, char *string, int radix);
  14.262 +#endif
  14.263 +
  14.264 +#ifdef HAVE__UITOA
  14.265 +#define SDL_uitoa       _uitoa
  14.266 +#else
  14.267 +#define _uitoa          SDL_uitoa
  14.268 +#define SDL_uitoa(value, string, radix)	SDL_ultoa((long)value, string, radix)
  14.269 +#endif
  14.270 +
  14.271 +#ifdef HAVE__ULTOA
  14.272 +#define SDL_ultoa       _ultoa
  14.273 +#else
  14.274 +#define _ultoa          SDL_ultoa
  14.275 +extern DECLSPEC char * SDLCALL SDL_ultoa(unsigned long value, char *string, int radix);
  14.276 +#endif
  14.277 +
  14.278 +#ifdef HAVE_STRTOL
  14.279 +#define SDL_strtol      strtol
  14.280 +#else
  14.281 +#define strtol          SDL_strtol
  14.282 +extern DECLSPEC long SDLCALL SDL_strtol(const char *string, char **endp, int base);
  14.283 +#endif
  14.284 +
  14.285 +#ifdef SDL_HAS_64BIT_TYPE
  14.286 +
  14.287 +#ifdef HAVE__I64TOA
  14.288 +#define SDL_lltoa       _i64toa
  14.289 +#else
  14.290 +#define _i64toa         SDL_lltoa
  14.291 +extern DECLSPEC char* SDLCALL SDL_lltoa(Sint64 value, char *string, int radix);
  14.292 +#endif
  14.293 +
  14.294 +#ifdef HAVE__UI64TOA
  14.295 +#define SDL_ulltoa      _ui64toa
  14.296 +#else
  14.297 +#define _ui64toa        SDL_ulltoa
  14.298 +extern DECLSPEC char* SDLCALL SDL_ulltoa(Uint64 value, char *string, int radix);
  14.299 +#endif
  14.300 +
  14.301 +#ifdef HAVE_STRTOLL
  14.302 +#define SDL_strtoll     strtoll
  14.303 +#else
  14.304 +#define strtoll         SDL_strtoll
  14.305 +extern DECLSPEC Sint64 SDLCALL SDL_strtoll(const char *string, char **endp, int base);
  14.306 +#endif
  14.307 +
  14.308 +#endif /* SDL_HAS_64BIT_TYPE */
  14.309 +
  14.310 +#ifdef HAVE_STRCMP
  14.311 +#define SDL_strcmp      strcmp
  14.312 +#else
  14.313 +#define strcmp          SDL_strcmp
  14.314 +extern DECLSPEC int SDLCALL SDL_strcmp(const char *str1, const char *str2);
  14.315 +#endif
  14.316 +
  14.317 +#ifdef HAVE_STRNCMP
  14.318 +#define SDL_strncmp     strncmp
  14.319 +#else
  14.320 +#define strncmp         SDL_strncmp
  14.321 +extern DECLSPEC int SDLCALL SDL_strncmp(const char *str1, const char *str2, size_t maxlen);
  14.322 +#endif
  14.323 +
  14.324 +#if defined(HAVE_STRICMP) && !defined(HAVE_STRCASECMP)
  14.325 +#define strcasecmp      stricmp
  14.326 +#define HAVE_STRCASECMP
  14.327 +#endif
  14.328 +#ifdef HAVE_STRCASECMP
  14.329 +#define SDL_strcasecmp  strcasecmp
  14.330 +#else
  14.331 +#define strcasecmp      SDL_strcasecmp
  14.332 +extern DECLSPEC int SDLCALL SDL_strcasecmp(const char *str1, const char *str2);
  14.333 +#endif
  14.334 +
  14.335 +#ifdef HAVE_SSCANF
  14.336 +#define SDL_sscanf      sscanf
  14.337 +#else
  14.338 +#define sscanf          SDL_sscanf
  14.339 +extern DECLSPEC int SDLCALL SDL_sscanf(const char *text, const char *fmt, ...);
  14.340 +#endif
  14.341 +
  14.342 +#ifdef HAVE_SNPRINTF
  14.343 +#define SDL_snprintf    snprintf
  14.344 +#else
  14.345 +#define snprintf        SDL_snprintf
  14.346 +extern DECLSPEC int SDLCALL SDL_snprintf(char *text, size_t maxlen, const char *fmt, ...);
  14.347 +#endif
  14.348 +
  14.349 +#ifdef HAVE_VSNPRINTF
  14.350 +#define SDL_vsnprintf   vsnprintf
  14.351 +#else
  14.352 +#define vsnprintf       SDL_vsnprintf
  14.353 +extern DECLSPEC int SDLCALL SDL_vsnprintf(char *text, size_t maxlen, const char *fmt, va_list ap);
  14.354 +#endif
  14.355 +
  14.356 +/* Ends C function definitions when using C++ */
  14.357 +#ifdef __cplusplus
  14.358 +}
  14.359 +#endif
  14.360 +#include "close_code.h"
  14.361 +
  14.362 +#endif /* _SDL_string_h */
    15.1 --- a/include/SDL_syswm.h	Sat Feb 04 22:01:44 2006 +0000
    15.2 +++ b/include/SDL_syswm.h	Mon Feb 06 08:28:51 2006 +0000
    15.3 @@ -119,8 +119,7 @@
    15.4  } SDL_SysWMinfo;
    15.5  
    15.6  #elif defined(WIN32)
    15.7 -#define WIN32_LEAN_AND_MEAN
    15.8 -#include <windows.h>
    15.9 +#include "SDL_windows.h"
   15.10  
   15.11  /* The windows custom event structure */
   15.12  struct SDL_SysWMmsg {
    16.1 --- a/include/SDL_thread.h	Sat Feb 04 22:01:44 2006 +0000
    16.2 +++ b/include/SDL_thread.h	Mon Feb 06 08:28:51 2006 +0000
    16.3 @@ -45,7 +45,7 @@
    16.4  typedef struct SDL_Thread SDL_Thread;
    16.5  
    16.6  /* Create a thread */
    16.7 -#ifdef __OS2__
    16.8 +#if defined(_WIN32) || defined(__OS2__)
    16.9  /*
   16.10     We compile SDL into a DLL on OS/2. This means, that it's the DLL which
   16.11     creates a new thread for the calling process with the SDL_CreateThread()
   16.12 @@ -53,39 +53,39 @@
   16.13     be initialized for those threads, and not the RTL of the calling application!
   16.14     To solve this, we make a little hack here.
   16.15     We'll always use the caller's _beginthread() and _endthread() APIs to
   16.16 -   start a new thread. This way, it it's the SDL.DLL which uses this API,
   16.17 +   start a new thread. This way, if it's the SDL.DLL which uses this API,
   16.18     then the RTL of SDL.DLL will be used to create the new thread, and if it's
   16.19     the application, then the RTL of the application will be used.
   16.20     So, in short:
   16.21     Always use the _beginthread() and _endthread() of the calling runtime library!
   16.22  */
   16.23 -
   16.24 -#ifdef __WATCOMC__
   16.25  #include <process.h> // This has _beginthread() and _endthread() defined!
   16.26 -#endif
   16.27  #ifdef __EMX__
   16.28  #include <stdlib.h> // This has _beginthread() and _endthread() defined, if -Zmt flag is used!
   16.29  #endif
   16.30  
   16.31 -typedef Uint32 SDLCALL (*pfnSDL_CurrentBeginThread)(void (*pfnThreadFn)(void *), Uint32 uiStackSize, void *pParam);
   16.32 -typedef void   SDLCALL (*pfnSDL_CurrentEndThread)(void);
   16.33 +#ifdef __OS2__
   16.34 +typedef int (__cdecl *pfnSDL_CurrentBeginThread)(void (*func)(void *), void *, unsigned, void *arg); 
   16.35 +typedef void (__cdecl *pfnSDL_CurrentEndThread)(void);
   16.36 +#else
   16.37 +#ifdef __GNUC__
   16.38 +#include <stdint.h>
   16.39 +#endif
   16.40 +typedef uintptr_t (__cdecl *pfnSDL_CurrentBeginThread) (void *, unsigned,
   16.41 +        unsigned (__stdcall *func)(void *), void *arg, 
   16.42 +        unsigned, unsigned *threadID);
   16.43 +typedef void (__cdecl *pfnSDL_CurrentEndThread)(unsigned code);
   16.44 +#endif
   16.45  
   16.46 -extern DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread_Core(int (*fn)(void *), void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread);
   16.47 +extern DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread(int (*fn)(void *), void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread);
   16.48  
   16.49 -// Disable warnings about unreferenced symbol!
   16.50 -#pragma disable_message (202)
   16.51 -static Uint32 SDLCALL SDL_CurrentBeginThread(void (*pfnThreadFn)(void *), Uint32 uiStackSize, void *pParam)
   16.52 -{
   16.53 -  return _beginthread(pfnThreadFn, NULL, uiStackSize, pParam);
   16.54 -}
   16.55 -
   16.56 -static void   SDLCALL SDL_CurrentEndThread(void)
   16.57 -{
   16.58 -  _endthread();
   16.59 -}
   16.60 -
   16.61 -#define SDL_CreateThread(fn, data) SDL_CreateThread_Core(fn, data, SDL_CurrentBeginThread, SDL_CurrentEndThread)
   16.62 -
   16.63 +#ifdef __OS2__
   16.64 +#define SDL_CreateThread(fn, data) SDL_CreateThread(fn, data, _beginthread, _endthread)
   16.65 +#elif defined(_WIN32_WCE)
   16.66 +#define SDL_CreateThread(fn, data) SDL_CreateThread(fn, data, NULL, NULL)
   16.67 +#else
   16.68 +#define SDL_CreateThread(fn, data) SDL_CreateThread(fn, data, _beginthreadex, _endthreadex)
   16.69 +#endif
   16.70  #else
   16.71  extern DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread(int (SDLCALL *fn)(void *), void *data);
   16.72  #endif
    17.1 --- a/include/SDL_types.h	Sat Feb 04 22:01:44 2006 +0000
    17.2 +++ b/include/SDL_types.h	Mon Feb 06 08:28:51 2006 +0000
    17.3 @@ -25,11 +25,17 @@
    17.4  #ifndef _SDL_types_h
    17.5  #define _SDL_types_h
    17.6  
    17.7 -/* The number of elements in a table */
    17.8 -#define SDL_TABLESIZE(table)	(sizeof(table)/sizeof(table[0]))
    17.9 +#include <sys/types.h>
   17.10 +#ifdef _MSC_VER
   17.11 +#include <crtdefs.h>	/* For size_t */
   17.12 +#endif
   17.13 +
   17.14 +/* The number of elements in an array */
   17.15 +#define SDL_arraysize(array)	(sizeof(array)/sizeof(array[0]))
   17.16 +#define SDL_TABLESIZE(table)	SDL_arraysize(table)
   17.17  
   17.18  /* Basic data types */
   17.19 -typedef enum {
   17.20 +typedef enum SDL_bool {
   17.21  	SDL_FALSE = 0,
   17.22  	SDL_TRUE  = 1
   17.23  } SDL_bool;
   17.24 @@ -107,9 +113,4 @@
   17.25  
   17.26  SDL_COMPILE_TIME_ASSERT(enum, sizeof(SDL_DUMMY_ENUM) == sizeof(int));
   17.27  
   17.28 -#undef SDL_COMPILE_TIME_ASSERT
   17.29 -
   17.30 -/* General keyboard/mouse state definitions */
   17.31 -enum { SDL_PRESSED = 0x01, SDL_RELEASED = 0x00 };
   17.32 -
   17.33  #endif
    18.1 --- a/include/SDL_video.h	Sat Feb 04 22:01:44 2006 +0000
    18.2 +++ b/include/SDL_video.h	Mon Feb 06 08:28:51 2006 +0000
    18.3 @@ -25,8 +25,6 @@
    18.4  #ifndef _SDL_video_h
    18.5  #define _SDL_video_h
    18.6  
    18.7 -#include <stdio.h>
    18.8 -
    18.9  #include "SDL_types.h"
   18.10  #include "SDL_mutex.h"
   18.11  #include "SDL_rwops.h"
    19.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    19.2 +++ b/include/SDL_windows.h	Mon Feb 06 08:28:51 2006 +0000
    19.3 @@ -0,0 +1,46 @@
    19.4 +/*
    19.5 +    SDL - Simple DirectMedia Layer
    19.6 +    Copyright (C) 1997-2006 Sam Lantinga
    19.7 +
    19.8 +    This library is free software; you can redistribute it and/or
    19.9 +    modify it under the terms of the GNU Lesser General Public
   19.10 +    License as published by the Free Software Foundation; either
   19.11 +    version 2.1 of the License, or (at your option) any later version.
   19.12 +
   19.13 +    This library is distributed in the hope that it will be useful,
   19.14 +    but WITHOUT ANY WARRANTY; without even the implied warranty of
   19.15 +    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   19.16 +    Lesser General Public License for more details.
   19.17 +
   19.18 +    You should have received a copy of the GNU Lesser General Public
   19.19 +    License along with this library; if not, write to the Free Software
   19.20 +    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
   19.21 +
   19.22 +    Sam Lantinga
   19.23 +    slouken@libsdl.org
   19.24 +*/
   19.25 +
   19.26 +#ifndef _SDL_windows_h
   19.27 +#define _SDL_windows_h
   19.28 +
   19.29 +#include "SDL_config.h"
   19.30 +
   19.31 +/* This includes only the windows headers needed by SDL, with no C runtime */
   19.32 +#define WIN32_LEAN_AND_MEAN
   19.33 +#ifndef HAVE_LIBC
   19.34 +#ifdef _MSC_VER
   19.35 +#ifndef __FLTUSED__
   19.36 +#define __FLTUSED__
   19.37 +#ifdef __cplusplus
   19.38 +   extern "C"
   19.39 +#endif
   19.40 +	   __declspec(selectany) int _fltused=1;
   19.41 +#endif
   19.42 +#endif /* _MSC_VER */
   19.43 +#define _INC_STDLIB
   19.44 +#define _INC_STRING
   19.45 +#define __STRALIGN_H_
   19.46 +#endif/* !HAVE_LIBC */
   19.47 +#include <windows.h>
   19.48 +
   19.49 +#endif /* _SDL_windows_h */
    20.1 --- a/src/Makefile.am	Sat Feb 04 22:01:44 2006 +0000
    20.2 +++ b/src/Makefile.am	Mon Feb 06 08:28:51 2006 +0000
    20.3 @@ -3,7 +3,7 @@
    20.4  
    20.5  # These are the subdirectories that are always built
    20.6  CORE_SUBDIRS =			\
    20.7 -	main
    20.8 +	main stdlib
    20.9  
   20.10  # These are the subdirectories which may be built
   20.11  EXTRA_SUBDIRS =			\
   20.12 @@ -25,10 +25,12 @@
   20.13  	-version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE)
   20.14  libSDL_la_LIBADD =		\
   20.15  	main/libarch.la		\
   20.16 +	stdlib/libstdlib.la	\
   20.17  	@SDL_EXTRALIBS@		\
   20.18  	@SYSTEM_LIBS@
   20.19  libSDL_la_DEPENDENCIES =	\
   20.20  	main/libarch.la		\
   20.21 +	stdlib/libstdlib.la	\
   20.22  	@SDL_EXTRALIBS@
   20.23  
   20.24  # The SDL library sources
   20.25 @@ -38,6 +40,5 @@
   20.26  	SDL_error_c.h		\
   20.27  	SDL_fatal.c		\
   20.28  	SDL_fatal.h		\
   20.29 -	SDL_getenv.c		\
   20.30  	SDL_loadso.c
   20.31  
    21.1 --- a/src/SDL.c	Sat Feb 04 22:01:44 2006 +0000
    21.2 +++ b/src/SDL.c	Mon Feb 06 08:28:51 2006 +0000
    21.3 @@ -22,7 +22,6 @@
    21.4  
    21.5  /* Initialization code for SDL */
    21.6  
    21.7 -#include <stdlib.h>		/* For getenv() */
    21.8  #ifdef ENABLE_PTH
    21.9  #include <pth.h>
   21.10  #endif
   21.11 @@ -30,6 +29,7 @@
   21.12  #include "SDL.h"
   21.13  #include "SDL_endian.h"
   21.14  #include "SDL_fatal.h"
   21.15 +#include "SDL_stdlib.h"
   21.16  #ifndef DISABLE_VIDEO
   21.17  #include "SDL_leaks.h"
   21.18  #endif
   21.19 @@ -253,26 +253,7 @@
   21.20  	return(&version);
   21.21  }
   21.22  
   21.23 -#ifndef __OS2__
   21.24 -#if defined(_WIN32_WCE) || (defined(__WATCOMC__) && defined(BUILD_DLL))
   21.25 -/* Need to include DllMain() on Windows CE and Watcom C for some reason.. */
   21.26 -#include <windows.h>
   21.27 -
   21.28 -BOOL APIENTRY DllMain( HANDLE hModule, 
   21.29 -                       DWORD  ul_reason_for_call, 
   21.30 -                       LPVOID lpReserved )
   21.31 -{
   21.32 -	switch (ul_reason_for_call) {
   21.33 -		case DLL_PROCESS_ATTACH:
   21.34 -		case DLL_THREAD_ATTACH:
   21.35 -		case DLL_THREAD_DETACH:
   21.36 -		case DLL_PROCESS_DETACH:
   21.37 -			break;
   21.38 -	}
   21.39 -	return TRUE;
   21.40 -}
   21.41 -#endif /* _WIN32_WCE and building DLL with Watcom C */
   21.42 -#else
   21.43 +#if defined(__OS2__)
   21.44  // Building for OS/2
   21.45  #ifdef __WATCOMC__
   21.46  
   21.47 @@ -341,6 +322,27 @@
   21.48      return 1;
   21.49    }
   21.50  }
   21.51 +#endif /* __WATCOMC__ */
   21.52  
   21.53 -#endif
   21.54 -#endif
   21.55 +#elif defined(_WIN32)
   21.56 +
   21.57 +#if !defined(HAVE_LIBC) || defined(_WIN32_WCE) || (defined(__WATCOMC__) && defined(BUILD_DLL))
   21.58 +/* Need to include DllMain() on Windows CE and Watcom C for some reason.. */
   21.59 +#include "SDL_windows.h"
   21.60 +
   21.61 +BOOL APIENTRY _DllMainCRTStartup( HANDLE hModule, 
   21.62 +                       DWORD  ul_reason_for_call, 
   21.63 +                       LPVOID lpReserved )
   21.64 +{
   21.65 +	switch (ul_reason_for_call) {
   21.66 +		case DLL_PROCESS_ATTACH:
   21.67 +		case DLL_THREAD_ATTACH:
   21.68 +		case DLL_THREAD_DETACH:
   21.69 +		case DLL_PROCESS_DETACH:
   21.70 +			break;
   21.71 +	}
   21.72 +	return TRUE;
   21.73 +}
   21.74 +#endif /* _WIN32_WCE and building DLL with Watcom C */
   21.75 +
   21.76 +#endif /* OS/2 elif _WIN32 */
    22.1 --- a/src/SDL_error.c	Sat Feb 04 22:01:44 2006 +0000
    22.2 +++ b/src/SDL_error.c	Mon Feb 06 08:28:51 2006 +0000
    22.3 @@ -22,13 +22,9 @@
    22.4  
    22.5  /* Simple error handling in SDL */
    22.6  
    22.7 -#include <stdio.h>
    22.8 -#include <stdlib.h>
    22.9 -#include <stdarg.h>
   22.10 -#include <string.h>
   22.11 -
   22.12  #include "SDL_types.h"
   22.13 -#include "SDL_getenv.h"
   22.14 +#include "SDL_stdlib.h"
   22.15 +#include "SDL_string.h"
   22.16  #include "SDL_error.h"
   22.17  #include "SDL_error_c.h"
   22.18  #ifndef DISABLE_THREADS
   22.19 @@ -42,10 +38,6 @@
   22.20  #define SDL_GetErrBuf()	(&SDL_global_error)
   22.21  #endif /* DISABLE_THREADS */
   22.22  
   22.23 -#ifdef __CYGWIN__
   22.24 -#define DISABLE_STDIO
   22.25 -#endif
   22.26 -
   22.27  #define SDL_ERRBUFIZE	1024
   22.28  
   22.29  /* Private functions */
   22.30 @@ -121,16 +113,10 @@
   22.31  	}
   22.32  	va_end(ap);
   22.33  
   22.34 -#ifndef DISABLE_STDIO
   22.35  	/* If we are in debug mode, print out an error message */
   22.36  #ifdef DEBUG_ERROR
   22.37  	fprintf(stderr, "SDL_SetError: %s\n", SDL_GetError());
   22.38 -#else
   22.39 -	if ( getenv("SDL_DEBUG") ) {
   22.40 -		fprintf(stderr, "SDL_SetError: %s\n", SDL_GetError());
   22.41 -	}
   22.42  #endif
   22.43 -#endif /* !DISABLE_STDIO */
   22.44  }
   22.45  
   22.46  /* Print out an integer value to a UNICODE buffer */
   22.47 @@ -139,7 +125,7 @@
   22.48  	char tmp[128];
   22.49  	int len, i;
   22.50  
   22.51 -	sprintf(tmp, "%d", value);
   22.52 +	snprintf(tmp, SDL_arraysize(tmp), "%d", value);
   22.53  	len = 0;
   22.54  	if ( strlen(tmp) < maxlen ) {
   22.55  		for ( i=0; tmp[i]; ++i ) {
   22.56 @@ -155,7 +141,7 @@
   22.57  	char tmp[128];
   22.58  	int len, i;
   22.59  
   22.60 -	sprintf(tmp, "%f", value);
   22.61 +	snprintf(tmp, SDL_arraysize(tmp), "%f", value);
   22.62  	len = 0;
   22.63  	if ( strlen(tmp) < maxlen ) {
   22.64  		for ( i=0; tmp[i]; ++i ) {
   22.65 @@ -171,7 +157,7 @@
   22.66  	char tmp[128];
   22.67  	int len, i;
   22.68  
   22.69 -	sprintf(tmp, "%p", value);
   22.70 +	snprintf(tmp, SDL_arraysize(tmp), "%p", value);
   22.71  	len = 0;
   22.72  	if ( strlen(tmp) < maxlen ) {
   22.73  		for ( i=0; tmp[i]; ++i ) {
    23.1 --- a/src/SDL_fatal.c	Sat Feb 04 22:01:44 2006 +0000
    23.2 +++ b/src/SDL_fatal.c	Mon Feb 06 08:28:51 2006 +0000
    23.3 @@ -20,91 +20,27 @@
    23.4      slouken@libsdl.org
    23.5  */
    23.6  
    23.7 -#ifdef _WIN32_WCE
    23.8 -#define NO_SIGNAL_H
    23.9 -#endif
   23.10 - 
   23.11  /* General fatal signal handling code for SDL */
   23.12  
   23.13 -#ifdef NO_SIGNAL_H
   23.14 +#include "SDL_config.h"
   23.15  
   23.16 -/* No signals on this platform, nothing to do.. */
   23.17 +#ifdef HAVE_SIGNAL_H
   23.18  
   23.19 -void SDL_InstallParachute(void)
   23.20 -{
   23.21 -	return;
   23.22 -}
   23.23 -
   23.24 -void SDL_UninstallParachute(void)
   23.25 -{
   23.26 -	return;
   23.27 -}
   23.28 -
   23.29 -#else
   23.30 -
   23.31 -#include <stdlib.h>
   23.32 -#include <stdio.h>
   23.33  #include <signal.h>
   23.34 -#include <string.h>
   23.35  
   23.36  #include "SDL.h"
   23.37  #include "SDL_fatal.h"
   23.38  
   23.39 -#ifdef __CYGWIN__
   23.40 -#define DISABLE_STDIO
   23.41 -#endif
   23.42 -
   23.43  /* This installs some signal handlers for the more common fatal signals,
   23.44     so that if the programmer is lazy, the app doesn't die so horribly if
   23.45     the program crashes.
   23.46  */
   23.47  
   23.48 -static void print_msg(const char *text)
   23.49 -{
   23.50 -#ifndef DISABLE_STDIO
   23.51 -	fprintf(stderr, "%s", text);
   23.52 -#endif
   23.53 -}
   23.54 -
   23.55  static void SDL_Parachute(int sig)
   23.56  {
   23.57  	signal(sig, SIG_DFL);
   23.58 -	print_msg("Fatal signal: ");
   23.59 -	switch (sig) {
   23.60 -		case SIGSEGV:
   23.61 -			print_msg("Segmentation Fault");
   23.62 -			break;
   23.63 -#ifdef SIGBUS
   23.64 -#if SIGBUS != SIGSEGV
   23.65 -		case SIGBUS:
   23.66 -			print_msg("Bus Error");
   23.67 -			break;
   23.68 -#endif
   23.69 -#endif /* SIGBUS */
   23.70 -#ifdef SIGFPE
   23.71 -		case SIGFPE:
   23.72 -			print_msg("Floating Point Exception");
   23.73 -			break;
   23.74 -#endif /* SIGFPE */
   23.75 -#ifdef SIGQUIT
   23.76 -		case SIGQUIT:
   23.77 -			print_msg("Keyboard Quit");
   23.78 -			break;
   23.79 -#endif /* SIGQUIT */
   23.80 -#ifdef SIGPIPE
   23.81 -		case SIGPIPE:
   23.82 -			print_msg("Broken Pipe");
   23.83 -			break;
   23.84 -#endif /* SIGPIPE */
   23.85 -		default:
   23.86 -#ifndef DISABLE_STDIO
   23.87 -			fprintf(stderr, "# %d", sig);
   23.88 -#endif
   23.89 -			break;
   23.90 -	}
   23.91 -	print_msg(" (SDL Parachute Deployed)\n");
   23.92  	SDL_Quit();
   23.93 -	exit(-sig);
   23.94 +	raise(sig);
   23.95  }
   23.96  
   23.97  static int SDL_fatal_signals[] = {
   23.98 @@ -182,4 +118,18 @@
   23.99  #endif /* HAVE_SIGACTION */
  23.100  }
  23.101  
  23.102 -#endif /* NO_SIGNAL_H */
  23.103 +#else
  23.104 +
  23.105 +/* No signals on this platform, nothing to do.. */
  23.106 +
  23.107 +void SDL_InstallParachute(void)
  23.108 +{
  23.109 +	return;
  23.110 +}
  23.111 +
  23.112 +void SDL_UninstallParachute(void)
  23.113 +{
  23.114 +	return;
  23.115 +}
  23.116 +
  23.117 +#endif /* HAVE_SIGNAL_H */
    24.1 --- a/src/SDL_getenv.c	Sat Feb 04 22:01:44 2006 +0000
    24.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
    24.3 @@ -1,258 +0,0 @@
    24.4 -/*
    24.5 -    SDL - Simple DirectMedia Layer
    24.6 -    Copyright (C) 1997-2006 Sam Lantinga
    24.7 -
    24.8 -    This library is free software; you can redistribute it and/or
    24.9 -    modify it under the terms of the GNU Lesser General Public
   24.10 -    License as published by the Free Software Foundation; either
   24.11 -    version 2.1 of the License, or (at your option) any later version.
   24.12 -
   24.13 -    This library is distributed in the hope that it will be useful,
   24.14 -    but WITHOUT ANY WARRANTY; without even the implied warranty of
   24.15 -    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   24.16 -    Lesser General Public License for more details.
   24.17 -
   24.18 -    You should have received a copy of the GNU Lesser General Public
   24.19 -    License along with this library; if not, write to the Free Software
   24.20 -    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
   24.21 -
   24.22 -    Sam Lantinga
   24.23 -    slouken@libsdl.org
   24.24 -*/
   24.25 -
   24.26 -/* Not all environments have a working getenv()/putenv() */
   24.27 -
   24.28 -#ifdef TEST_MAIN
   24.29 -#define NEED_SDL_GETENV
   24.30 -#endif
   24.31 -
   24.32 -#include "SDL_getenv.h"
   24.33 -
   24.34 -#ifdef NEED_SDL_GETENV
   24.35 -
   24.36 -#if defined(WIN32) && !defined(_WIN32_WCE)
   24.37 -
   24.38 -#define WIN32_LEAN_AND_MEAN
   24.39 -#include <windows.h>
   24.40 -#include <malloc.h>
   24.41 -#include <string.h>
   24.42 -
   24.43 -/* Note this isn't thread-safe! */
   24.44 -
   24.45 -static char *SDL_envmem = NULL;	/* Ugh, memory leak */
   24.46 -static DWORD SDL_envmemlen = 0;
   24.47 -
   24.48 -/* Put a variable of the form "name=value" into the environment */
   24.49 -int SDL_putenv(const char *variable)
   24.50 -{
   24.51 -	DWORD bufferlen;
   24.52 -	char *value;
   24.53 -	const char *sep;
   24.54 -
   24.55 -	sep = strchr(variable, '=');
   24.56 -	if ( sep == NULL ) {
   24.57 -		return -1;
   24.58 -	}
   24.59 -	bufferlen = strlen(variable)+1;
   24.60 -	if ( bufferlen > SDL_envmemlen ) {
   24.61 -		char *newmem = (char *)realloc(SDL_envmem, bufferlen);
   24.62 -		if ( newmem == NULL ) {
   24.63 -			return -1;
   24.64 -		}
   24.65 -		SDL_envmem = newmem;
   24.66 -		SDL_envmemlen = bufferlen;
   24.67 -	}
   24.68 -	strcpy(SDL_envmem, variable);
   24.69 -	value = SDL_envmem + (sep - variable);
   24.70 -	*value++ = '\0';
   24.71 -	if ( !SetEnvironmentVariable(SDL_envmem, *value ? value : NULL) ) {
   24.72 -		return -1;
   24.73 -	}
   24.74 -	return 0;
   24.75 -}
   24.76 -
   24.77 -/* Retrieve a variable named "name" from the environment */
   24.78 -char *SDL_getenv(const char *name)
   24.79 -{
   24.80 -	DWORD bufferlen;
   24.81 -
   24.82 -	bufferlen = GetEnvironmentVariable(name, SDL_envmem, SDL_envmemlen);
   24.83 -	if ( bufferlen == 0 ) {
   24.84 -		return NULL;
   24.85 -	}
   24.86 -	if ( bufferlen > SDL_envmemlen ) {
   24.87 -		char *newmem = (char *)realloc(SDL_envmem, bufferlen);
   24.88 -		if ( newmem == NULL ) {
   24.89 -			return NULL;
   24.90 -		}
   24.91 -		SDL_envmem = newmem;
   24.92 -		SDL_envmemlen = bufferlen;
   24.93 -		GetEnvironmentVariable(name, SDL_envmem, SDL_envmemlen);
   24.94 -	}
   24.95 -	return SDL_envmem;
   24.96 -}
   24.97 -
   24.98 -#else /* roll our own */
   24.99 -
  24.100 -#include <stdlib.h>
  24.101 -#include <string.h>
  24.102 -
  24.103 -static char **SDL_env = (char **)0;
  24.104 -
  24.105 -/* Put a variable of the form "name=value" into the environment */
  24.106 -int SDL_putenv(const char *variable)
  24.107 -{
  24.108 -	const char *name, *value;
  24.109 -	int added;
  24.110 -	int len, i;
  24.111 -	char **new_env;
  24.112 -	char *new_variable;
  24.113 -
  24.114 -	/* A little error checking */
  24.115 -	if ( ! variable ) {
  24.116 -		return(-1);
  24.117 -	}
  24.118 -	name = variable;
  24.119 -	for ( value=variable; *value && (*value != '='); ++value ) {
  24.120 -		/* Keep looking for '=' */ ;
  24.121 -	}
  24.122 -	if ( *value ) {
  24.123 -		++value;
  24.124 -	} else {
  24.125 -		return(-1);
  24.126 -	}
  24.127 -
  24.128 -	/* Allocate memory for the variable */
  24.129 -	new_variable = (char *)malloc(strlen(variable)+1);
  24.130 -	if ( ! new_variable ) {
  24.131 -		return(-1);
  24.132 -	}
  24.133 -	strcpy(new_variable, variable);
  24.134 -
  24.135 -	/* Actually put it into the environment */
  24.136 -	added = 0;
  24.137 -	i = 0;
  24.138 -	if ( SDL_env ) {
  24.139 -		/* Check to see if it's already there... */
  24.140 -		len = (value - name);
  24.141 -		for ( ; SDL_env[i]; ++i ) {
  24.142 -			if ( strncmp(SDL_env[i], name, len) == 0 ) {
  24.143 -				break;
  24.144 -			}
  24.145 -		}
  24.146 -		/* If we found it, just replace the entry */
  24.147 -		if ( SDL_env[i] ) {
  24.148 -			free(SDL_env[i]);
  24.149 -			SDL_env[i] = new_variable;
  24.150 -			added = 1;
  24.151 -		}
  24.152 -	}
  24.153 -
  24.154 -	/* Didn't find it in the environment, expand and add */
  24.155 -	if ( ! added ) {
  24.156 -		new_env = realloc(SDL_env, (i+2)*sizeof(char *));
  24.157 -		if ( new_env ) {
  24.158 -			SDL_env = new_env;
  24.159 -			SDL_env[i++] = new_variable;
  24.160 -			SDL_env[i++] = (char *)0;
  24.161 -			added = 1;
  24.162 -		} else {
  24.163 -			free(new_variable);
  24.164 -		}
  24.165 -	}
  24.166 -	return (added ? 0 : -1);
  24.167 -}
  24.168 -
  24.169 -/* Retrieve a variable named "name" from the environment */
  24.170 -char *SDL_getenv(const char *name)
  24.171 -{
  24.172 -	int len, i;
  24.173 -	char *value;
  24.174 -
  24.175 -	value = (char *)0;
  24.176 -	if ( SDL_env ) {
  24.177 -		len = strlen(name);
  24.178 -		for ( i=0; SDL_env[i] && !value; ++i ) {
  24.179 -			if ( (strncmp(SDL_env[i], name, len) == 0) &&
  24.180 -			     (SDL_env[i][len] == '=') ) {
  24.181 -				value = &SDL_env[i][len+1];
  24.182 -			}
  24.183 -		}
  24.184 -	}
  24.185 -	return value;
  24.186 -}
  24.187 -
  24.188 -#endif /* WIN32 */
  24.189 -
  24.190 -#endif /* NEED_GETENV */
  24.191 -
  24.192 -#ifdef TEST_MAIN
  24.193 -#include <stdio.h>
  24.194 -
  24.195 -int main(int argc, char *argv[])
  24.196 -{
  24.197 -	char *value;
  24.198 -
  24.199 -	printf("Checking for non-existent variable... ");
  24.200 -	fflush(stdout);
  24.201 -	if ( ! getenv("EXISTS") ) {
  24.202 -		printf("okay\n");
  24.203 -	} else {
  24.204 -		printf("failed\n");
  24.205 -	}
  24.206 -	printf("Setting FIRST=VALUE1 in the environment... ");
  24.207 -	fflush(stdout);
  24.208 -	if ( putenv("FIRST=VALUE1") == 0 ) {
  24.209 -		printf("okay\n");
  24.210 -	} else {
  24.211 -		printf("failed\n");
  24.212 -	}
  24.213 -	printf("Getting FIRST from the environment... ");
  24.214 -	fflush(stdout);
  24.215 -	value = getenv("FIRST");
  24.216 -	if ( value && (strcmp(value, "VALUE1") == 0) ) {
  24.217 -		printf("okay\n");
  24.218 -	} else {
  24.219 -		printf("failed\n");
  24.220 -	}
  24.221 -	printf("Setting SECOND=VALUE2 in the environment... ");
  24.222 -	fflush(stdout);
  24.223 -	if ( putenv("SECOND=VALUE2") == 0 ) {
  24.224 -		printf("okay\n");
  24.225 -	} else {
  24.226 -		printf("failed\n");
  24.227 -	}
  24.228 -	printf("Getting SECOND from the environment... ");
  24.229 -	fflush(stdout);
  24.230 -	value = getenv("SECOND");
  24.231 -	if ( value && (strcmp(value, "VALUE2") == 0) ) {
  24.232 -		printf("okay\n");
  24.233 -	} else {
  24.234 -		printf("failed\n");
  24.235 -	}
  24.236 -	printf("Setting FIRST=NOVALUE in the environment... ");
  24.237 -	fflush(stdout);
  24.238 -	if ( putenv("FIRST=NOVALUE") == 0 ) {
  24.239 -		printf("okay\n");
  24.240 -	} else {
  24.241 -		printf("failed\n");
  24.242 -	}
  24.243 -	printf("Getting FIRST from the environment... ");
  24.244 -	fflush(stdout);
  24.245 -	value = getenv("FIRST");
  24.246 -	if ( value && (strcmp(value, "NOVALUE") == 0) ) {
  24.247 -		printf("okay\n");
  24.248 -	} else {
  24.249 -		printf("failed\n");
  24.250 -	}
  24.251 -	printf("Checking for non-existent variable... ");
  24.252 -	fflush(stdout);
  24.253 -	if ( ! getenv("EXISTS") ) {
  24.254 -		printf("okay\n");
  24.255 -	} else {
  24.256 -		printf("failed\n");
  24.257 -	}
  24.258 -	return(0);
  24.259 -}
  24.260 -#endif /* TEST_MAIN */
  24.261 -
    25.1 --- a/src/audio/SDL_audio.c	Sat Feb 04 22:01:44 2006 +0000
    25.2 +++ b/src/audio/SDL_audio.c	Mon Feb 06 08:28:51 2006 +0000
    25.3 @@ -21,14 +21,12 @@
    25.4  */
    25.5  
    25.6  /* Allow access to a raw mixing buffer */
    25.7 -#include <stdlib.h>
    25.8 -#include <stdio.h>
    25.9 -#include <string.h>
   25.10  
   25.11  #include "SDL.h"
   25.12  #include "SDL_audio.h"
   25.13  #include "SDL_timer.h"
   25.14  #include "SDL_error.h"
   25.15 +#include "SDL_string.h"
   25.16  #include "SDL_audio_c.h"
   25.17  #include "SDL_audiomem.h"
   25.18  #include "SDL_sysaudio.h"
   25.19 @@ -456,7 +454,12 @@
   25.20  	D(bug("Locking semaphore..."));
   25.21  	SDL_mutexP(audio->mixer_lock);
   25.22  
   25.23 +#if (defined(_WIN32) && !defined(_WIN32_WCE)) && !defined(HAVE_LIBC)
   25.24 +#undef SDL_CreateThread
   25.25 +	audio->thread = SDL_CreateThread(SDL_RunAudio, audio, NULL, NULL);
   25.26 +#else
   25.27  	audio->thread = SDL_CreateThread(SDL_RunAudio, audio);
   25.28 +#endif
   25.29  	D(bug("Created thread...\n"));
   25.30  
   25.31  	if ( audio->thread == NULL ) {
   25.32 @@ -516,7 +519,12 @@
   25.33  	switch (audio->opened) {
   25.34  		case  1:
   25.35  			/* Start the audio thread */
   25.36 +#if (defined(_WIN32) && !defined(_WIN32_WCE)) && !defined(HAVE_LIBC)
   25.37 +#undef SDL_CreateThread
   25.38 +			audio->thread = SDL_CreateThread(SDL_RunAudio, audio, NULL, NULL);
   25.39 +#else
   25.40  			audio->thread = SDL_CreateThread(SDL_RunAudio, audio);
   25.41 +#endif
   25.42  			if ( audio->thread == NULL ) {
   25.43  				SDL_CloseAudio();
   25.44  				SDL_SetError("Couldn't create audio thread");
    26.1 --- a/src/audio/SDL_audiocvt.c	Sat Feb 04 22:01:44 2006 +0000
    26.2 +++ b/src/audio/SDL_audiocvt.c	Mon Feb 06 08:28:51 2006 +0000
    26.3 @@ -22,8 +22,6 @@
    26.4  
    26.5  /* Functions for audio drivers to perform runtime conversion of audio format */
    26.6  
    26.7 -#include <stdio.h>
    26.8 -
    26.9  #include "SDL_error.h"
   26.10  #include "SDL_audio.h"
   26.11  
    27.1 --- a/src/audio/SDL_audiomem.c	Sat Feb 04 22:01:44 2006 +0000
    27.2 +++ b/src/audio/SDL_audiomem.c	Mon Feb 06 08:28:51 2006 +0000
    27.3 @@ -24,7 +24,6 @@
    27.4  	(necessary because SDL audio emulates threads with fork()
    27.5   */
    27.6  
    27.7 -#include <stdlib.h>
    27.8  #ifdef FORK_HACK
    27.9  #include <sys/types.h>
   27.10  #include <sys/ipc.h>
   27.11 @@ -33,6 +32,7 @@
   27.12  #endif
   27.13  
   27.14  #include "SDL_audiomem.h"
   27.15 +#include "SDL_stdlib.h"
   27.16  
   27.17  /* Allocate memory that will be shared between threads (freed on exit) */
   27.18  void *SDL_AllocAudioMem(int size)
    28.1 --- a/src/audio/SDL_mixer.c	Sat Feb 04 22:01:44 2006 +0000
    28.2 +++ b/src/audio/SDL_mixer.c	Mon Feb 06 08:28:51 2006 +0000
    28.3 @@ -22,10 +22,6 @@
    28.4  
    28.5  /* This provides the default mixing callback for the SDL audio routines */
    28.6  
    28.7 -#include <stdio.h>
    28.8 -#include <stdlib.h>
    28.9 -#include <string.h>
   28.10 -
   28.11  #include "SDL_audio.h"
   28.12  #include "SDL_mutex.h"
   28.13  #include "SDL_timer.h"
    29.1 --- a/src/audio/SDL_mixer_MMX_VC.c	Sat Feb 04 22:01:44 2006 +0000
    29.2 +++ b/src/audio/SDL_mixer_MMX_VC.c	Mon Feb 06 08:28:51 2006 +0000
    29.3 @@ -1,3 +1,6 @@
    29.4 +
    29.5 +#include "SDL_mixer_MMX_VC.h"
    29.6 +
    29.7  #if defined(USE_ASM_MIXER_VC)
    29.8  // MMX assembler version of SDL_MixAudio for signed little endian 16 bit samples and signed 8 bit samples
    29.9  // Copyright 2002 Stephane Marchesin (stephane.marchesin@wanadoo.fr)
   29.10 @@ -12,11 +15,6 @@
   29.11  // Mixing for 16 bit signed buffers
   29.12  ////////////////////////////////////////////////
   29.13  
   29.14 -#ifndef __WATCOMC__
   29.15 -#include <windows.h>
   29.16 -#include <stdio.h>
   29.17 -#endif
   29.18 -
   29.19  void SDL_MixAudio_MMX_S16_VC(char* dst,char* src,unsigned int nSize,int volume)
   29.20  {
   29.21  	__asm
    30.1 --- a/src/audio/SDL_mixer_MMX_VC.h	Sat Feb 04 22:01:44 2006 +0000
    30.2 +++ b/src/audio/SDL_mixer_MMX_VC.h	Mon Feb 06 08:28:51 2006 +0000
    30.3 @@ -1,3 +1,6 @@
    30.4 +#ifdef _MSC_VER
    30.5 +#define USE_ASM_MIXER_VC
    30.6 +#endif
    30.7  #if defined(USE_ASM_MIXER_VC)
    30.8  // headers for MMX assembler version of SDL_MixAudio
    30.9  // Copyright 2002 Stephane Marchesin (stephane.marchesin@wanadoo.fr)
    31.1 --- a/src/audio/SDL_wave.c	Sat Feb 04 22:01:44 2006 +0000
    31.2 +++ b/src/audio/SDL_wave.c	Mon Feb 06 08:28:51 2006 +0000
    31.3 @@ -24,17 +24,13 @@
    31.4  
    31.5  /* Microsoft WAVE file loading routines */
    31.6  
    31.7 -#include <stdlib.h>
    31.8 -#include <string.h>
    31.9 -
   31.10  #include "SDL_error.h"
   31.11  #include "SDL_audio.h"
   31.12 +#include "SDL_stdlib.h"
   31.13 +#include "SDL_string.h"
   31.14  #include "SDL_wave.h"
   31.15  #include "SDL_endian.h"
   31.16  
   31.17 -#ifndef NELEMS
   31.18 -#define NELEMS(array)	((sizeof array)/(sizeof array[0]))
   31.19 -#endif
   31.20  
   31.21  static int ReadChunk(SDL_RWops *src, Chunk *chunk);
   31.22  
   31.23 @@ -342,9 +338,9 @@
   31.24  
   31.25  	/* Check to make sure we have enough variables in the state array */
   31.26  	channels = IMA_ADPCM_state.wavefmt.channels;
   31.27 -	if ( channels > NELEMS(IMA_ADPCM_state.state) ) {
   31.28 +	if ( channels > SDL_arraysize(IMA_ADPCM_state.state) ) {
   31.29  		SDL_SetError("IMA ADPCM decoder can only handle %d channels",
   31.30 -						NELEMS(IMA_ADPCM_state.state));
   31.31 +					SDL_arraysize(IMA_ADPCM_state.state));
   31.32  		return(-1);
   31.33  	}
   31.34  	state = IMA_ADPCM_state.state;
   31.35 @@ -564,7 +560,7 @@
   31.36  	}
   31.37  	else {
   31.38  		// seek to the end of the file (given by the RIFF chunk)
   31.39 -		SDL_RWseek(src, wavelen - chunk.length - headerDiff, SEEK_CUR);
   31.40 +		SDL_RWseek(src, wavelen - chunk.length - headerDiff, RW_SEEK_CUR);
   31.41  	}
   31.42  	if ( was_error ) {
   31.43  		spec = NULL;
    32.1 --- a/src/audio/windib/SDL_dibaudio.c	Sat Feb 04 22:01:44 2006 +0000
    32.2 +++ b/src/audio/windib/SDL_dibaudio.c	Mon Feb 06 08:28:51 2006 +0000
    32.3 @@ -22,14 +22,14 @@
    32.4  
    32.5  /* Allow access to a raw mixing buffer */
    32.6  
    32.7 -#include <stdio.h>
    32.8 -#include <stdlib.h>
    32.9 -#include <windows.h>
   32.10 +#include "SDL_windows.h"
   32.11  #include <mmsystem.h>
   32.12  
   32.13  #include "SDL_audio.h"
   32.14  #include "SDL_mutex.h"
   32.15  #include "SDL_timer.h"
   32.16 +#include "SDL_stdlib.h"
   32.17 +#include "SDL_string.h"
   32.18  #include "SDL_audio_c.h"
   32.19  #include "SDL_dibaudio.h"
   32.20  #if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
   32.21 @@ -125,7 +125,7 @@
   32.22  	wchar_t werrbuf[MAXERRORLENGTH];
   32.23  #endif
   32.24  
   32.25 -	sprintf(errbuf, "%s: ", function);
   32.26 +	snprintf(errbuf, SDL_arraysize(errbuf), "%s: ", function);
   32.27  	len = strlen(errbuf);
   32.28  
   32.29  #ifdef _WIN32_WCE
    33.1 --- a/src/audio/windx5/SDL_dx5audio.c	Sat Feb 04 22:01:44 2006 +0000
    33.2 +++ b/src/audio/windx5/SDL_dx5audio.c	Mon Feb 06 08:28:51 2006 +0000
    33.3 @@ -22,12 +22,12 @@
    33.4  
    33.5  /* Allow access to a raw mixing buffer */
    33.6  
    33.7 -#include <stdio.h>
    33.8 -
    33.9  #include "SDL_types.h"
   33.10  #include "SDL_error.h"
   33.11  #include "SDL_timer.h"
   33.12  #include "SDL_audio.h"
   33.13 +#include "SDL_stdlib.h"
   33.14 +#include "SDL_string.h"
   33.15  #include "SDL_audio_c.h"
   33.16  #include "SDL_dx5audio.h"
   33.17  
   33.18 @@ -223,12 +223,13 @@
   33.19  			error = "Function not supported";
   33.20  			break;
   33.21  		default:
   33.22 -			sprintf(errbuf, "%s: Unknown DirectSound error: 0x%x",
   33.23 +			snprintf(errbuf, SDL_arraysize(errbuf),
   33.24 +			         "%s: Unknown DirectSound error: 0x%x",
   33.25  								function, code);
   33.26  			break;
   33.27  	}
   33.28  	if ( ! errbuf[0] ) {
   33.29 -		sprintf(errbuf, "%s: %s", function, error);
   33.30 +		snprintf(errbuf, SDL_arraysize(errbuf), "%s: %s", function, error);
   33.31  	}
   33.32  	SDL_SetError("%s", errbuf);
   33.33  	return;
    34.1 --- a/src/audio/windx5/directx.h	Sat Feb 04 22:01:44 2006 +0000
    34.2 +++ b/src/audio/windx5/directx.h	Mon Feb 06 08:28:51 2006 +0000
    34.3 @@ -4,7 +4,7 @@
    34.4  
    34.5  /* Include all of the DirectX 5.0 headers and adds any necessary tweaks */
    34.6  
    34.7 -#include <windows.h>
    34.8 +#include "SDL_windows.h"
    34.9  #include <mmsystem.h>
   34.10  #ifndef WIN32
   34.11  #define WIN32
    35.1 --- a/src/cdrom/SDL_cdrom.c	Sat Feb 04 22:01:44 2006 +0000
    35.2 +++ b/src/cdrom/SDL_cdrom.c	Mon Feb 06 08:28:51 2006 +0000
    35.3 @@ -22,12 +22,10 @@
    35.4  
    35.5  /* This is the CD-audio control API for Simple DirectMedia Layer */
    35.6  
    35.7 -#include <stdio.h>
    35.8 -#include <stdlib.h>
    35.9 -#include <string.h>
   35.10 -
   35.11  #include "SDL_error.h"
   35.12  #include "SDL_cdrom.h"
   35.13 +#include "SDL_stdlib.h"
   35.14 +#include "SDL_string.h"
   35.15  #include "SDL_syscdrom.h"
   35.16  
   35.17  #if !defined(macintosh)
    36.1 --- a/src/cdrom/win32/SDL_syscdrom.c	Sat Feb 04 22:01:44 2006 +0000
    36.2 +++ b/src/cdrom/win32/SDL_syscdrom.c	Mon Feb 06 08:28:51 2006 +0000
    36.3 @@ -22,13 +22,13 @@
    36.4  
    36.5  /* Functions for system-level CD-ROM audio control */
    36.6  
    36.7 -#include <stdlib.h>
    36.8 -#include <stdio.h>
    36.9 -#include <windows.h>
   36.10 +#include "SDL_windows.h"
   36.11  #include <mmsystem.h>
   36.12  
   36.13  #include "SDL_error.h"
   36.14  #include "SDL_cdrom.h"
   36.15 +#include "SDL_stdlib.h"
   36.16 +#include "SDL_string.h"
   36.17  #include "SDL_syscdrom.h"
   36.18  
   36.19  /* This really broken?? */
   36.20 @@ -99,7 +99,7 @@
   36.21  
   36.22  	/* Scan the system for CD-ROM drives */
   36.23  	for ( i='A'; i<='Z'; ++i ) {
   36.24 -		sprintf(drive, "%c:\\", i);
   36.25 +		snprintf(drive, SDL_arraysize(drive), "%c:\\", i);
   36.26  		if ( GetDriveType(drive) == DRIVE_CDROM ) {
   36.27  			AddDrive(drive);
   36.28  		}
    37.1 --- a/src/events/SDL_active.c	Sat Feb 04 22:01:44 2006 +0000
    37.2 +++ b/src/events/SDL_active.c	Mon Feb 06 08:28:51 2006 +0000
    37.3 @@ -22,10 +22,8 @@
    37.4  
    37.5  /* Application focus/iconification handling code for SDL */
    37.6  
    37.7 -#include <stdio.h>
    37.8 -#include <string.h>
    37.9 -
   37.10  #include "SDL_events.h"
   37.11 +#include "SDL_string.h"
   37.12  #include "SDL_events_c.h"
   37.13  
   37.14  
    38.1 --- a/src/events/SDL_events.c	Sat Feb 04 22:01:44 2006 +0000
    38.2 +++ b/src/events/SDL_events.c	Mon Feb 06 08:28:51 2006 +0000
    38.3 @@ -22,13 +22,11 @@
    38.4  
    38.5  /* General event handling code for SDL */
    38.6  
    38.7 -#include <stdio.h>
    38.8 -#include <string.h>
    38.9 -
   38.10  #include "SDL.h"
   38.11  #include "SDL_thread.h"
   38.12  #include "SDL_mutex.h"
   38.13  #include "SDL_events.h"
   38.14 +#include "SDL_string.h"
   38.15  #include "SDL_events_c.h"
   38.16  #include "SDL_timer_c.h"
   38.17  #ifndef DISABLE_JOYSTICK
   38.18 @@ -177,7 +175,12 @@
   38.19  
   38.20  		/* The event thread will handle timers too */
   38.21  		SDL_SetTimerThreaded(2);
   38.22 +#if (defined(_WIN32) && !defined(_WIN32_WCE)) && !defined(HAVE_LIBC)
   38.23 +#undef SDL_CreateThread
   38.24 +		SDL_EventThread = SDL_CreateThread(SDL_GobbleEvents, NULL, NULL, NULL);
   38.25 +#else
   38.26  		SDL_EventThread = SDL_CreateThread(SDL_GobbleEvents, NULL);
   38.27 +#endif
   38.28  		if ( SDL_EventThread == NULL ) {
   38.29  			return(-1);
   38.30  		}
    39.1 --- a/src/events/SDL_keyboard.c	Sat Feb 04 22:01:44 2006 +0000
    39.2 +++ b/src/events/SDL_keyboard.c	Mon Feb 06 08:28:51 2006 +0000
    39.3 @@ -22,14 +22,10 @@
    39.4  
    39.5  /* General keyboard handling code for SDL */
    39.6  
    39.7 -#include <stdio.h>
    39.8 -#include <ctype.h>
    39.9 -#include <stdlib.h>
   39.10 -#include <string.h>
   39.11 -
   39.12  #include "SDL_error.h"
   39.13  #include "SDL_events.h"
   39.14  #include "SDL_timer.h"
   39.15 +#include "SDL_string.h"
   39.16  #include "SDL_events_c.h"
   39.17  #include "SDL_sysevents.h"
   39.18  
   39.19 @@ -58,17 +54,14 @@
   39.20  {
   39.21  	SDL_VideoDevice *video = current_video;
   39.22  	SDL_VideoDevice *this  = current_video;
   39.23 -	Uint16 i;
   39.24  
   39.25  	/* Set default mode of UNICODE translation */
   39.26  	SDL_EnableUNICODE(DEFAULT_UNICODE_TRANSLATION);
   39.27  
   39.28  	/* Initialize the tables */
   39.29  	SDL_ModState = KMOD_NONE;
   39.30 -	for ( i=0; i<SDL_TABLESIZE(keynames); ++i )
   39.31 -		keynames[i] = NULL;
   39.32 -	for ( i=0; i<SDL_TABLESIZE(SDL_KeyState); ++i )
   39.33 -		SDL_KeyState[i] = SDL_RELEASED;
   39.34 +	memset(keynames, 0, sizeof(keynames));
   39.35 +	memset(SDL_KeyState, 0, sizeof(SDL_KeyState));
   39.36  	video->InitOSKeymap(this);
   39.37  
   39.38  	SDL_EnableKeyRepeat(0, 0);
    40.1 --- a/src/events/SDL_mouse.c	Sat Feb 04 22:01:44 2006 +0000
    40.2 +++ b/src/events/SDL_mouse.c	Mon Feb 06 08:28:51 2006 +0000
    40.3 @@ -22,11 +22,8 @@
    40.4  
    40.5  /* General mouse handling code for SDL */
    40.6  
    40.7 -#include <stdio.h>
    40.8 -#include <stdlib.h>
    40.9 -#include <string.h>
   40.10 -
   40.11  #include "SDL_events.h"
   40.12 +#include "SDL_string.h"
   40.13  #include "SDL_events_c.h"
   40.14  #include "SDL_cursor_c.h"
   40.15  #include "SDL_sysvideo.h"
    41.1 --- a/src/events/SDL_quit.c	Sat Feb 04 22:01:44 2006 +0000
    41.2 +++ b/src/events/SDL_quit.c	Mon Feb 06 08:28:51 2006 +0000
    41.3 @@ -22,12 +22,9 @@
    41.4  
    41.5  /* General quit handling code for SDL */
    41.6  
    41.7 -#if defined (_WIN32_WCE)
    41.8 -#define NO_SIGNAL_H
    41.9 -#endif
   41.10 +#include "SDL_config.h"
   41.11  
   41.12 -#include <stdio.h>
   41.13 -#ifndef NO_SIGNAL_H
   41.14 +#ifdef HAVE_SIGNAL_H
   41.15  #include <signal.h>
   41.16  #endif
   41.17  
   41.18 @@ -35,7 +32,7 @@
   41.19  #include "SDL_events_c.h"
   41.20  
   41.21  
   41.22 -#ifndef NO_SIGNAL_H
   41.23 +#ifdef HAVE_SIGNAL_H
   41.24  static void SDL_HandleSIG(int sig)
   41.25  {
   41.26  	/* Reset the signal handler */
   41.27 @@ -44,12 +41,12 @@
   41.28  	/* Signal a quit interrupt */
   41.29  	SDL_PrivateQuit();
   41.30  }
   41.31 -#endif /* NO_SIGNAL_H */
   41.32 +#endif /* HAVE_SIGNAL_H */
   41.33  
   41.34  /* Public functions */
   41.35  int SDL_QuitInit(void)
   41.36  {
   41.37 -#ifndef NO_SIGNAL_H
   41.38 +#ifdef HAVE_SIGNAL_H
   41.39  	void (*ohandler)(int);
   41.40  
   41.41  	/* Both SIGINT and SIGTERM are translated into quit interrupts */
   41.42 @@ -59,14 +56,14 @@
   41.43  	ohandler = signal(SIGTERM, SDL_HandleSIG);
   41.44  	if ( ohandler != SIG_DFL )
   41.45  		signal(SIGTERM, ohandler);
   41.46 -#endif /* NO_SIGNAL_H */
   41.47 +#endif /* HAVE_SIGNAL_H */
   41.48  
   41.49  	/* That's it! */
   41.50  	return(0);
   41.51  }
   41.52  void SDL_QuitQuit(void)
   41.53  {
   41.54 -#ifndef NO_SIGNAL_H
   41.55 +#ifdef HAVE_SIGNAL_H
   41.56  	void (*ohandler)(int);
   41.57  
   41.58  	ohandler = signal(SIGINT, SIG_DFL);
   41.59 @@ -75,7 +72,7 @@
   41.60  	ohandler = signal(SIGTERM, SIG_DFL);
   41.61  	if ( ohandler != SDL_HandleSIG )
   41.62  		signal(SIGTERM, ohandler);
   41.63 -#endif /* NO_SIGNAL_H */
   41.64 +#endif /* HAVE_SIGNAL_H */
   41.65  }
   41.66  
   41.67  /* This function returns 1 if it's okay to close the application window */
    42.1 --- a/src/file/SDL_rwops.c	Sat Feb 04 22:01:44 2006 +0000
    42.2 +++ b/src/file/SDL_rwops.c	Mon Feb 06 08:28:51 2006 +0000
    42.3 @@ -24,12 +24,12 @@
    42.4     data sources.  It can easily be extended to files, memory, etc.
    42.5  */
    42.6  
    42.7 -#include <stdlib.h>
    42.8 -#include <stdio.h>
    42.9 -#include <string.h>
   42.10 -
   42.11  #include "SDL_error.h"
   42.12  #include "SDL_rwops.h"
   42.13 +#include "SDL_stdlib.h"
   42.14 +#include "SDL_string.h"
   42.15 +
   42.16 +#ifdef HAVE_STDIO_H
   42.17  
   42.18  /* Functions to read/write stdio file pointers */
   42.19  
   42.20 @@ -74,6 +74,8 @@
   42.21  	return(0);
   42.22  }
   42.23  
   42.24 +#endif /* HAVE_STDIO_H */
   42.25 +
   42.26  /* Functions to read/write memory pointers */
   42.27  
   42.28  static int mem_seek(SDL_RWops *context, int offset, int whence)
   42.29 @@ -81,13 +83,13 @@
   42.30  	Uint8 *newpos;
   42.31  
   42.32  	switch (whence) {
   42.33 -		case SEEK_SET:
   42.34 +		case RW_SEEK_SET:
   42.35  			newpos = context->hidden.mem.base+offset;
   42.36  			break;
   42.37 -		case SEEK_CUR:
   42.38 +		case RW_SEEK_CUR:
   42.39  			newpos = context->hidden.mem.here+offset;
   42.40  			break;
   42.41 -		case SEEK_END:
   42.42 +		case RW_SEEK_END:
   42.43  			newpos = context->hidden.mem.stop+offset;
   42.44  			break;
   42.45  		default:
   42.46 @@ -199,10 +201,9 @@
   42.47  
   42.48  SDL_RWops *SDL_RWFromFile(const char *file, const char *mode)
   42.49  {
   42.50 +	SDL_RWops *rwops = NULL;
   42.51 +#ifdef HAVE_STDIO_H
   42.52  	FILE *fp;
   42.53 -	SDL_RWops *rwops;
   42.54 -
   42.55 -	rwops = NULL;
   42.56  
   42.57  #ifdef macintosh
   42.58  	{
   42.59 @@ -224,12 +225,14 @@
   42.60  		rwops = SDL_RWFromFP(fp, 1);
   42.61  #endif
   42.62  	}
   42.63 +#endif /* HAVE_STDIO_H */
   42.64  	return(rwops);
   42.65  }
   42.66  
   42.67 +#ifdef HAVE_STDIO_H
   42.68  SDL_RWops *SDL_RWFromFP(FILE *fp, int autoclose)
   42.69  {
   42.70 -	SDL_RWops *rwops;
   42.71 +	SDL_RWops *rwops = NULL;
   42.72  
   42.73  #ifdef WIN32
   42.74  	if ( ! in_sdl ) {
   42.75 @@ -249,6 +252,7 @@
   42.76  	}
   42.77  	return(rwops);
   42.78  }
   42.79 +#endif /* HAVE_STDIO_H */
   42.80  
   42.81  SDL_RWops *SDL_RWFromMem(void *mem, int size)
   42.82  {
    43.1 --- a/src/joystick/SDL_joystick.c	Sat Feb 04 22:01:44 2006 +0000
    43.2 +++ b/src/joystick/SDL_joystick.c	Mon Feb 06 08:28:51 2006 +0000
    43.3 @@ -22,12 +22,10 @@
    43.4  
    43.5  /* This is the joystick API for Simple DirectMedia Layer */
    43.6  
    43.7 -#include <stdio.h>
    43.8 -#include <stdlib.h>
    43.9 -#include <string.h>
   43.10 -
   43.11  #include "SDL_error.h"
   43.12  #include "SDL_events.h"
   43.13 +#include "SDL_stdlib.h"
   43.14 +#include "SDL_string.h"
   43.15  #ifndef DISABLE_EVENTS
   43.16  #include "SDL_events_c.h"
   43.17  #endif
    44.1 --- a/src/joystick/win32/SDL_mmjoystick.c	Sat Feb 04 22:01:44 2006 +0000
    44.2 +++ b/src/joystick/win32/SDL_mmjoystick.c	Mon Feb 06 08:28:51 2006 +0000
    44.3 @@ -22,15 +22,15 @@
    44.4  
    44.5  /* Win32 MultiMedia Joystick driver, contributed by Andrei de A. Formiga */
    44.6  
    44.7 -#include <stdlib.h>
    44.8 -#include <stdio.h>		/* For the definition of NULL */
    44.9 -
   44.10  #include "SDL_error.h"
   44.11 +#include "SDL_events.h"
   44.12  #include "SDL_joystick.h"
   44.13 +#include "SDL_stdlib.h"
   44.14 +#include "SDL_string.h"
   44.15  #include "SDL_sysjoystick.h"
   44.16  #include "SDL_joystick_c.h"
   44.17  
   44.18 -#include <windows.h>
   44.19 +#include "SDL_windows.h"
   44.20  #include <mmsystem.h>
   44.21  #include <regstr.h>
   44.22  
   44.23 @@ -82,7 +82,7 @@
   44.24  	unsigned char regvalue[256];
   44.25  	unsigned char regname[256];
   44.26  
   44.27 -	sprintf((char *) regkey, "%s\\%s\\%s",
   44.28 +	snprintf((char *) regkey, SDL_arraysize(regkey), "%s\\%s\\%s",
   44.29  		REGSTR_PATH_JOYCONFIG,
   44.30  		szRegKey,
   44.31  		REGSTR_KEY_JOYCURR);
   44.32 @@ -95,7 +95,7 @@
   44.33  			joystick's properties
   44.34  		*/
   44.35  		regsize = sizeof(regname);
   44.36 -		sprintf((char *) regvalue,
   44.37 +		snprintf((char *) regvalue, SDL_arraysize(regvalue),
   44.38  			"Joystick%d%s", index+1,
   44.39  			REGSTR_VAL_JOYOEMNAME);
   44.40  		regresult = RegQueryValueExA(hKey,
   44.41 @@ -105,7 +105,7 @@
   44.42  		if (regresult == ERROR_SUCCESS)
   44.43  		{
   44.44  			/* open that registry key */
   44.45 -			sprintf((char *) regkey, "%s\\%s",
   44.46 +			snprintf((char *) regkey, SDL_arraysize(regkey), "%s\\%s",
   44.47  				REGSTR_PATH_JOYOEM, regname);
   44.48  			regresult = RegOpenKeyExA(HKEY_LOCAL_MACHINE,
   44.49  				(char *) regkey, 0, KEY_READ, &hKey);
   44.50 @@ -379,7 +379,7 @@
   44.51  void SetMMerror(char *function, int code)
   44.52  {
   44.53  	static char *error;
   44.54 -	static char  errbuf[BUFSIZ];
   44.55 +	static char  errbuf[1024];
   44.56  
   44.57  	errbuf[0] = 0;
   44.58  	switch (code) 
   44.59 @@ -406,13 +406,14 @@
   44.60  		break;
   44.61  
   44.62  		default:
   44.63 -			sprintf(errbuf, "%s: Unknown Multimedia system error: 0x%x",
   44.64 +			snprintf(errbuf, SDL_arraysize(errbuf),
   44.65 +			         "%s: Unknown Multimedia system error: 0x%x",
   44.66  								function, code);
   44.67  		break;
   44.68  	}
   44.69  
   44.70  	if ( ! errbuf[0] ) {
   44.71 -		sprintf(errbuf, "%s: %s", function, error);
   44.72 +		snprintf(errbuf, SDL_arraysize(errbuf), "%s: %s", function, error);
   44.73  	}
   44.74  	SDL_SetError("%s", errbuf);
   44.75  }
    45.1 --- a/src/loadso/windows/SDL_loadso.c	Sat Feb 04 22:01:44 2006 +0000
    45.2 +++ b/src/loadso/windows/SDL_loadso.c	Mon Feb 06 08:28:51 2006 +0000
    45.3 @@ -31,8 +31,7 @@
    45.4  #error Compiling for the wrong platform?
    45.5  #endif
    45.6  
    45.7 -#include <stdio.h>
    45.8 -#include <windows.h>
    45.9 +#include "SDL_windows.h"
   45.10  
   45.11  #include "SDL_types.h"
   45.12  #include "SDL_error.h"
    46.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    46.2 +++ b/src/stdlib/.cvsignore	Mon Feb 06 08:28:51 2006 +0000
    46.3 @@ -0,0 +1,6 @@
    46.4 +Makefile.in
    46.5 +Makefile
    46.6 +.libs
    46.7 +*.o
    46.8 +*.lo
    46.9 +*.la
    47.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    47.2 +++ b/src/stdlib/Makefile.am	Mon Feb 06 08:28:51 2006 +0000
    47.3 @@ -0,0 +1,15 @@
    47.4 +
    47.5 +## Makefile.am for the SDL file library
    47.6 +
    47.7 +noinst_LTLIBRARIES = libstdlib.la
    47.8 +
    47.9 +# Include the architecture-independent sources
   47.10 +COMMON_SRCS =			\
   47.11 +	SDL_getenv.c		\
   47.12 +	SDL_malloc.c		\
   47.13 +	SDL_qsort.c		\
   47.14 +	SDL_stdlib.c		\
   47.15 +	SDL_string.c
   47.16 +
   47.17 +libstdlib_la_SOURCES = $(COMMON_SRCS)
   47.18 +
    48.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    48.2 +++ b/src/stdlib/SDL_getenv.c	Mon Feb 06 08:28:51 2006 +0000
    48.3 @@ -0,0 +1,245 @@
    48.4 +/*
    48.5 +    SDL - Simple DirectMedia Layer
    48.6 +    Copyright (C) 1997-2006 Sam Lantinga
    48.7 +
    48.8 +    This library is free software; you can redistribute it and/or
    48.9 +    modify it under the terms of the GNU Lesser General Public
   48.10 +    License as published by the Free Software Foundation; either
   48.11 +    version 2.1 of the License, or (at your option) any later version.
   48.12 +
   48.13 +    This library is distributed in the hope that it will be useful,
   48.14 +    but WITHOUT ANY WARRANTY; without even the implied warranty of
   48.15 +    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   48.16 +    Lesser General Public License for more details.
   48.17 +
   48.18 +    You should have received a copy of the GNU Lesser General Public
   48.19 +    License along with this library; if not, write to the Free Software
   48.20 +    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
   48.21 +
   48.22 +    Sam Lantinga
   48.23 +    slouken@libsdl.org
   48.24 +*/
   48.25 +
   48.26 +#include "SDL_stdlib.h"
   48.27 +#include "SDL_string.h"
   48.28 +
   48.29 +
   48.30 +#if defined(WIN32) && !defined(_WIN32_WCE)
   48.31 +
   48.32 +#include "SDL_windows.h"
   48.33 +#include "SDL_string.h"
   48.34 +
   48.35 +/* Note this isn't thread-safe! */
   48.36 +
   48.37 +static char *SDL_envmem = NULL;	/* Ugh, memory leak */
   48.38 +static DWORD SDL_envmemlen = 0;
   48.39 +
   48.40 +/* Put a variable of the form "name=value" into the environment */
   48.41 +int SDL_putenv(const char *variable)
   48.42 +{
   48.43 +	DWORD bufferlen;
   48.44 +	char *value;
   48.45 +	const char *sep;
   48.46 +
   48.47 +	sep = strchr(variable, '=');
   48.48 +	if ( sep == NULL ) {
   48.49 +		return -1;
   48.50 +	}
   48.51 +	bufferlen = strlen(variable)+1;
   48.52 +	if ( bufferlen > SDL_envmemlen ) {
   48.53 +		char *newmem = (char *)realloc(SDL_envmem, bufferlen);
   48.54 +		if ( newmem == NULL ) {
   48.55 +			return -1;
   48.56 +		}
   48.57 +		SDL_envmem = newmem;
   48.58 +		SDL_envmemlen = bufferlen;
   48.59 +	}
   48.60 +	strcpy(SDL_envmem, variable);
   48.61 +	value = SDL_envmem + (sep - variable);
   48.62 +	*value++ = '\0';
   48.63 +	if ( !SetEnvironmentVariable(SDL_envmem, *value ? value : NULL) ) {
   48.64 +		return -1;
   48.65 +	}
   48.66 +	return 0;
   48.67 +}
   48.68 +
   48.69 +/* Retrieve a variable named "name" from the environment */
   48.70 +char *SDL_getenv(const char *name)
   48.71 +{
   48.72 +	DWORD bufferlen;
   48.73 +
   48.74 +	bufferlen = GetEnvironmentVariable(name, SDL_envmem, SDL_envmemlen);
   48.75 +	if ( bufferlen == 0 ) {
   48.76 +		return NULL;
   48.77 +	}
   48.78 +	if ( bufferlen > SDL_envmemlen ) {
   48.79 +		char *newmem = (char *)realloc(SDL_envmem, bufferlen);
   48.80 +		if ( newmem == NULL ) {
   48.81 +			return NULL;
   48.82 +		}
   48.83 +		SDL_envmem = newmem;
   48.84 +		SDL_envmemlen = bufferlen;
   48.85 +		GetEnvironmentVariable(name, SDL_envmem, SDL_envmemlen);
   48.86 +	}
   48.87 +	return SDL_envmem;
   48.88 +}
   48.89 +
   48.90 +#else /* roll our own */
   48.91 +
   48.92 +static char **SDL_env = (char **)0;
   48.93 +
   48.94 +/* Put a variable of the form "name=value" into the environment */
   48.95 +int SDL_putenv(const char *variable)
   48.96 +{
   48.97 +	const char *name, *value;
   48.98 +	int added;
   48.99 +	int len, i;
  48.100 +	char **new_env;
  48.101 +	char *new_variable;
  48.102 +
  48.103 +	/* A little error checking */
  48.104 +	if ( ! variable ) {
  48.105 +		return(-1);
  48.106 +	}
  48.107 +	name = variable;
  48.108 +	for ( value=variable; *value && (*value != '='); ++value ) {
  48.109 +		/* Keep looking for '=' */ ;
  48.110 +	}
  48.111 +	if ( *value ) {
  48.112 +		++value;
  48.113 +	} else {
  48.114 +		return(-1);
  48.115 +	}
  48.116 +
  48.117 +	/* Allocate memory for the variable */
  48.118 +	new_variable = (char *)malloc(strlen(variable)+1);
  48.119 +	if ( ! new_variable ) {
  48.120 +		return(-1);
  48.121 +	}
  48.122 +	strcpy(new_variable, variable);
  48.123 +
  48.124 +	/* Actually put it into the environment */
  48.125 +	added = 0;
  48.126 +	i = 0;
  48.127 +	if ( SDL_env ) {
  48.128 +		/* Check to see if it's already there... */
  48.129 +		len = (value - name);
  48.130 +		for ( ; SDL_env[i]; ++i ) {
  48.131 +			if ( strncmp(SDL_env[i], name, len) == 0 ) {
  48.132 +				break;
  48.133 +			}
  48.134 +		}
  48.135 +		/* If we found it, just replace the entry */
  48.136 +		if ( SDL_env[i] ) {
  48.137 +			free(SDL_env[i]);
  48.138 +			SDL_env[i] = new_variable;
  48.139 +			added = 1;
  48.140 +		}
  48.141 +	}
  48.142 +
  48.143 +	/* Didn't find it in the environment, expand and add */
  48.144 +	if ( ! added ) {
  48.145 +		new_env = realloc(SDL_env, (i+2)*sizeof(char *));
  48.146 +		if ( new_env ) {
  48.147 +			SDL_env = new_env;
  48.148 +			SDL_env[i++] = new_variable;
  48.149 +			SDL_env[i++] = (char *)0;
  48.150 +			added = 1;
  48.151 +		} else {
  48.152 +			free(new_variable);
  48.153 +		}
  48.154 +	}
  48.155 +	return (added ? 0 : -1);
  48.156 +}
  48.157 +
  48.158 +/* Retrieve a variable named "name" from the environment */
  48.159 +char *SDL_getenv(const char *name)
  48.160 +{
  48.161 +	int len, i;
  48.162 +	char *value;
  48.163 +
  48.164 +	value = (char *)0;
  48.165 +	if ( SDL_env ) {
  48.166 +		len = strlen(name);
  48.167 +		for ( i=0; SDL_env[i] && !value; ++i ) {
  48.168 +			if ( (strncmp(SDL_env[i], name, len) == 0) &&
  48.169 +			     (SDL_env[i][len] == '=') ) {
  48.170 +				value = &SDL_env[i][len+1];
  48.171 +			}
  48.172 +		}
  48.173 +	}
  48.174 +	return value;
  48.175 +}
  48.176 +
  48.177 +#endif /* WIN32 */
  48.178 +
  48.179 +#ifdef TEST_MAIN
  48.180 +#include <stdio.h>
  48.181 +
  48.182 +int main(int argc, char *argv[])
  48.183 +{
  48.184 +	char *value;
  48.185 +
  48.186 +	printf("Checking for non-existent variable... ");
  48.187 +	fflush(stdout);
  48.188 +	if ( ! getenv("EXISTS") ) {
  48.189 +		printf("okay\n");
  48.190 +	} else {
  48.191 +		printf("failed\n");
  48.192 +	}
  48.193 +	printf("Setting FIRST=VALUE1 in the environment... ");
  48.194 +	fflush(stdout);
  48.195 +	if ( putenv("FIRST=VALUE1") == 0 ) {
  48.196 +		printf("okay\n");
  48.197 +	} else {
  48.198 +		printf("failed\n");
  48.199 +	}
  48.200 +	printf("Getting FIRST from the environment... ");
  48.201 +	fflush(stdout);
  48.202 +	value = getenv("FIRST");
  48.203 +	if ( value && (strcmp(value, "VALUE1") == 0) ) {
  48.204 +		printf("okay\n");
  48.205 +	} else {
  48.206 +		printf("failed\n");
  48.207 +	}
  48.208 +	printf("Setting SECOND=VALUE2 in the environment... ");
  48.209 +	fflush(stdout);
  48.210 +	if ( putenv("SECOND=VALUE2") == 0 ) {
  48.211 +		printf("okay\n");
  48.212 +	} else {
  48.213 +		printf("failed\n");
  48.214 +	}
  48.215 +	printf("Getting SECOND from the environment... ");
  48.216 +	fflush(stdout);
  48.217 +	value = getenv("SECOND");
  48.218 +	if ( value && (strcmp(value, "VALUE2") == 0) ) {
  48.219 +		printf("okay\n");
  48.220 +	} else {
  48.221 +		printf("failed\n");
  48.222 +	}
  48.223 +	printf("Setting FIRST=NOVALUE in the environment... ");
  48.224 +	fflush(stdout);
  48.225 +	if ( putenv("FIRST=NOVALUE") == 0 ) {
  48.226 +		printf("okay\n");
  48.227 +	} else {
  48.228 +		printf("failed\n");
  48.229 +	}
  48.230 +	printf("Getting FIRST from the environment... ");
  48.231 +	fflush(stdout);
  48.232 +	value = getenv("FIRST");
  48.233 +	if ( value && (strcmp(value, "NOVALUE") == 0) ) {
  48.234 +		printf("okay\n");
  48.235 +	} else {
  48.236 +		printf("failed\n");
  48.237 +	}
  48.238 +	printf("Checking for non-existent variable... ");
  48.239 +	fflush(stdout);
  48.240 +	if ( ! getenv("EXISTS") ) {
  48.241 +		printf("okay\n");
  48.242 +	} else {
  48.243 +		printf("failed\n");
  48.244 +	}
  48.245 +	return(0);
  48.246 +}
  48.247 +#endif /* TEST_MAIN */
  48.248 +
    49.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    49.2 +++ b/src/stdlib/SDL_malloc.c	Mon Feb 06 08:28:51 2006 +0000
    49.3 @@ -0,0 +1,5108 @@
    49.4 +/*
    49.5 +    SDL - Simple DirectMedia Layer
    49.6 +    Copyright (C) 1997-2006 Sam Lantinga
    49.7 +
    49.8 +    This library is free software; you can redistribute it and/or
    49.9 +    modify it under the terms of the GNU Lesser General Public
   49.10 +    License as published by the Free Software Foundation; either
   49.11 +    version 2.1 of the License, or (at your option) any later version.
   49.12 +
   49.13 +    This library is distributed in the hope that it will be useful,
   49.14 +    but WITHOUT ANY WARRANTY; without even the implied warranty of
   49.15 +    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   49.16 +    Lesser General Public License for more details.
   49.17 +
   49.18 +    You should have received a copy of the GNU Lesser General Public
   49.19 +    License along with this library; if not, write to the Free Software
   49.20 +    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
   49.21 +
   49.22 +    Sam Lantinga
   49.23 +    slouken@libsdl.org
   49.24 +*/
   49.25 +
   49.26 +
   49.27 +/* This file contains portable memory management functions for SDL */
   49.28 +
   49.29 +#include "SDL_stdlib.h"
   49.30 +#include "SDL_string.h"
   49.31 +
   49.32 +#ifndef HAVE_MALLOC
   49.33 +
   49.34 +#define LACKS_STDIO_H
   49.35 +#define LACKS_UNISTD_H
   49.36 +#define LACKS_FCNTL_H
   49.37 +#define LACKS_SYS_PARAM_H
   49.38 +#define LACKS_SYS_MMAN_H
   49.39 +#define LACKS_STRINGS_H
   49.40 +#define LACKS_STRING_H
   49.41 +#define LACKS_SYS_TYPES_H
   49.42 +#define LACKS_ERRNO_H
   49.43 +#define LACKS_STDLIB_H
   49.44 +#define ABORT
   49.45 +
   49.46 +/*
   49.47 +  This is a version (aka dlmalloc) of malloc/free/realloc written by
   49.48 +  Doug Lea and released to the public domain, as explained at
   49.49 +  http://creativecommons.org/licenses/publicdomain.  Send questions,
   49.50 +  comments, complaints, performance data, etc to dl@cs.oswego.edu
   49.51 +
   49.52 +* Version 2.8.3 Thu Sep 22 11:16:15 2005  Doug Lea  (dl at gee)
   49.53 +
   49.54 +   Note: There may be an updated version of this malloc obtainable at
   49.55 +           ftp://gee.cs.oswego.edu/pub/misc/malloc.c
   49.56 +         Check before installing!
   49.57 +
   49.58 +* Quickstart
   49.59 +
   49.60 +  This library is all in one file to simplify the most common usage:
   49.61 +  ftp it, compile it (-O3), and link it into another program. All of
   49.62 +  the compile-time options default to reasonable values for use on
   49.63 +  most platforms.  You might later want to step through various
   49.64 +  compile-time and dynamic tuning options.
   49.65 +
   49.66 +  For convenience, an include file for code using this malloc is at:
   49.67 +     ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.3.h
   49.68 +  You don't really need this .h file unless you call functions not
   49.69 +  defined in your system include files.  The .h file contains only the
   49.70 +  excerpts from this file needed for using this malloc on ANSI C/C++
   49.71 +  systems, so long as you haven't changed compile-time options about
   49.72 +  naming and tuning parameters.  If you do, then you can create your
   49.73 +  own malloc.h that does include all settings by cutting at the point
   49.74 +  indicated below. Note that you may already by default be using a C
   49.75 +  library containing a malloc that is based on some version of this
   49.76 +  malloc (for example in linux). You might still want to use the one
   49.77 +  in this file to customize settings or to avoid overheads associated
   49.78 +  with library versions.
   49.79 +
   49.80 +* Vital statistics:
   49.81 +
   49.82 +  Supported pointer/size_t representation:       4 or 8 bytes
   49.83 +       size_t MUST be an unsigned type of the same width as
   49.84 +       pointers. (If you are using an ancient system that declares
   49.85 +       size_t as a signed type, or need it to be a different width
   49.86 +       than pointers, you can use a previous release of this malloc
   49.87 +       (e.g. 2.7.2) supporting these.)
   49.88 +
   49.89 +  Alignment:                                     8 bytes (default)
   49.90 +       This suffices for nearly all current machines and C compilers.
   49.91 +       However, you can define MALLOC_ALIGNMENT to be wider than this
   49.92 +       if necessary (up to 128bytes), at the expense of using more space.
   49.93 +
   49.94 +  Minimum overhead per allocated chunk:   4 or  8 bytes (if 4byte sizes)
   49.95 +                                          8 or 16 bytes (if 8byte sizes)
   49.96 +       Each malloced chunk has a hidden word of overhead holding size
   49.97 +       and status information, and additional cross-check word
   49.98 +       if FOOTERS is defined.
   49.99 +
  49.100 +  Minimum allocated size: 4-byte ptrs:  16 bytes    (including overhead)
  49.101 +                          8-byte ptrs:  32 bytes    (including overhead)
  49.102 +
  49.103 +       Even a request for zero bytes (i.e., malloc(0)) returns a
  49.104 +       pointer to something of the minimum allocatable size.
  49.105 +       The maximum overhead wastage (i.e., number of extra bytes
  49.106 +       allocated than were requested in malloc) is less than or equal
  49.107 +       to the minimum size, except for requests >= mmap_threshold that
  49.108 +       are serviced via mmap(), where the worst case wastage is about
  49.109 +       32 bytes plus the remainder from a system page (the minimal
  49.110 +       mmap unit); typically 4096 or 8192 bytes.
  49.111 +
  49.112 +  Security: static-safe; optionally more or less
  49.113 +       The "security" of malloc refers to the ability of malicious
  49.114 +       code to accentuate the effects of errors (for example, freeing
  49.115 +       space that is not currently malloc'ed or overwriting past the
  49.116 +       ends of chunks) in code that calls malloc.  This malloc
  49.117 +       guarantees not to modify any memory locations below the base of
  49.118 +       heap, i.e., static variables, even in the presence of usage
  49.119 +       errors.  The routines additionally detect most improper frees
  49.120 +       and reallocs.  All this holds as long as the static bookkeeping
  49.121 +       for malloc itself is not corrupted by some other means.  This
  49.122 +       is only one aspect of security -- these checks do not, and
  49.123 +       cannot, detect all possible programming errors.
  49.124 +
  49.125 +       If FOOTERS is defined nonzero, then each allocated chunk
  49.126 +       carries an additional check word to verify that it was malloced
  49.127 +       from its space.  These check words are the same within each
  49.128 +       execution of a program using malloc, but differ across
  49.129 +       executions, so externally crafted fake chunks cannot be
  49.130 +       freed. This improves security by rejecting frees/reallocs that
  49.131 +       could corrupt heap memory, in addition to the checks preventing
  49.132 +       writes to statics that are always on.  This may further improve
  49.133 +       security at the expense of time and space overhead.  (Note that
  49.134 +       FOOTERS may also be worth using with MSPACES.)
  49.135 +
  49.136 +       By default detected errors cause the program to abort (calling
  49.137 +       "abort()"). You can override this to instead proceed past
  49.138 +       errors by defining PROCEED_ON_ERROR.  In this case, a bad free
  49.139 +       has no effect, and a malloc that encounters a bad address
  49.140 +       caused by user overwrites will ignore the bad address by
  49.141 +       dropping pointers and indices to all known memory. This may
  49.142 +       be appropriate for programs that should continue if at all
  49.143 +       possible in the face of programming errors, although they may
  49.144 +       run out of memory because dropped memory is never reclaimed.
  49.145 +
  49.146 +       If you don't like either of these options, you can define
  49.147 +       CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything
  49.148 +       else. And if if you are sure that your program using malloc has
  49.149 +       no errors or vulnerabilities, you can define INSECURE to 1,
  49.150 +       which might (or might not) provide a small performance improvement.
  49.151 +
  49.152 +  Thread-safety: NOT thread-safe unless USE_LOCKS defined
  49.153 +       When USE_LOCKS is defined, each public call to malloc, free,
  49.154 +       etc is surrounded with either a pthread mutex or a win32
  49.155 +       spinlock (depending on WIN32). This is not especially fast, and
  49.156 +       can be a major bottleneck.  It is designed only to provide
  49.157 +       minimal protection in concurrent environments, and to provide a
  49.158 +       basis for extensions.  If you are using malloc in a concurrent
  49.159 +       program, consider instead using ptmalloc, which is derived from
  49.160 +       a version of this malloc. (See http://www.malloc.de).
  49.161 +
  49.162 +  System requirements: Any combination of MORECORE and/or MMAP/MUNMAP
  49.163 +       This malloc can use unix sbrk or any emulation (invoked using
  49.164 +       the CALL_MORECORE macro) and/or mmap/munmap or any emulation
  49.165 +       (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system
  49.166 +       memory.  On most unix systems, it tends to work best if both
  49.167 +       MORECORE and MMAP are enabled.  On Win32, it uses emulations
  49.168 +       based on VirtualAlloc. It also uses common C library functions
  49.169 +       like memset.
  49.170 +
  49.171 +  Compliance: I believe it is compliant with the Single Unix Specification
  49.172 +       (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably
  49.173 +       others as well.
  49.174 +
  49.175 +* Overview of algorithms
  49.176 +
  49.177 +  This is not the fastest, most space-conserving, most portable, or
  49.178 +  most tunable malloc ever written. However it is among the fastest
  49.179 +  while also being among the most space-conserving, portable and
  49.180 +  tunable.  Consistent balance across these factors results in a good
  49.181 +  general-purpose allocator for malloc-intensive programs.
  49.182 +
  49.183 +  In most ways, this malloc is a best-fit allocator. Generally, it
  49.184 +  chooses the best-fitting existing chunk for a request, with ties
  49.185 +  broken in approximately least-recently-used order. (This strategy
  49.186 +  normally maintains low fragmentation.) However, for requests less
  49.187 +  than 256bytes, it deviates from best-fit when there is not an
  49.188 +  exactly fitting available chunk by preferring to use space adjacent
  49.189 +  to that used for the previous small request, as well as by breaking
  49.190 +  ties in approximately most-recently-used order. (These enhance
  49.191 +  locality of series of small allocations.)  And for very large requests
  49.192 +  (>= 256Kb by default), it relies on system memory mapping
  49.193 +  facilities, if supported.  (This helps avoid carrying around and
  49.194 +  possibly fragmenting memory used only for large chunks.)
  49.195 +
  49.196 +  All operations (except malloc_stats and mallinfo) have execution
  49.197 +  times that are bounded by a constant factor of the number of bits in
  49.198 +  a size_t, not counting any clearing in calloc or copying in realloc,
  49.199 +  or actions surrounding MORECORE and MMAP that have times
  49.200 +  proportional to the number of non-contiguous regions returned by
  49.201 +  system allocation routines, which is often just 1.
  49.202 +
  49.203 +  The implementation is not very modular and seriously overuses
  49.204 +  macros. Perhaps someday all C compilers will do as good a job
  49.205 +  inlining modular code as can now be done by brute-force expansion,
  49.206 +  but now, enough of them seem not to.
  49.207 +
  49.208 +  Some compilers issue a lot of warnings about code that is
  49.209 +  dead/unreachable only on some platforms, and also about intentional
  49.210 +  uses of negation on unsigned types. All known cases of each can be
  49.211 +  ignored.
  49.212 +
  49.213 +  For a longer but out of date high-level description, see
  49.214 +     http://gee.cs.oswego.edu/dl/html/malloc.html
  49.215 +
  49.216 +* MSPACES
  49.217 +  If MSPACES is defined, then in addition to malloc, free, etc.,
  49.218 +  this file also defines mspace_malloc, mspace_free, etc. These
  49.219 +  are versions of malloc routines that take an "mspace" argument
  49.220 +  obtained using create_mspace, to control all internal bookkeeping.
  49.221 +  If ONLY_MSPACES is defined, only these versions are compiled.
  49.222 +  So if you would like to use this allocator for only some allocations,
  49.223 +  and your system malloc for others, you can compile with
  49.224 +  ONLY_MSPACES and then do something like...
  49.225 +    static mspace mymspace = create_mspace(0,0); // for example
  49.226 +    #define mymalloc(bytes)  mspace_malloc(mymspace, bytes)
  49.227 +
  49.228 +  (Note: If you only need one instance of an mspace, you can instead
  49.229 +  use "USE_DL_PREFIX" to relabel the global malloc.)
  49.230 +
  49.231 +  You can similarly create thread-local allocators by storing
  49.232 +  mspaces as thread-locals. For example:
  49.233 +    static __thread mspace tlms = 0;
  49.234 +    void*  tlmalloc(size_t bytes) {
  49.235 +      if (tlms == 0) tlms = create_mspace(0, 0);
  49.236 +      return mspace_malloc(tlms, bytes);
  49.237 +    }
  49.238 +    void  tlfree(void* mem) { mspace_free(tlms, mem); }
  49.239 +
  49.240 +  Unless FOOTERS is defined, each mspace is completely independent.
  49.241 +  You cannot allocate from one and free to another (although
  49.242 +  conformance is only weakly checked, so usage errors are not always
  49.243 +  caught). If FOOTERS is defined, then each chunk carries around a tag
  49.244 +  indicating its originating mspace, and frees are directed to their
  49.245 +  originating spaces.
  49.246 +
  49.247 + -------------------------  Compile-time options ---------------------------
  49.248 +
  49.249 +Be careful in setting #define values for numerical constants of type
  49.250 +size_t. On some systems, literal values are not automatically extended
  49.251 +to size_t precision unless they are explicitly casted.
  49.252 +
  49.253 +WIN32                    default: defined if _WIN32 defined
  49.254 +  Defining WIN32 sets up defaults for MS environment and compilers.
  49.255 +  Otherwise defaults are for unix.
  49.256 +
  49.257 +MALLOC_ALIGNMENT         default: (size_t)8
  49.258 +  Controls the minimum alignment for malloc'ed chunks.  It must be a
  49.259 +  power of two and at least 8, even on machines for which smaller
  49.260 +  alignments would suffice. It may be defined as larger than this
  49.261 +  though. Note however that code and data structures are optimized for
  49.262 +  the case of 8-byte alignment.
  49.263 +
  49.264 +MSPACES                  default: 0 (false)
  49.265 +  If true, compile in support for independent allocation spaces.
  49.266 +  This is only supported if HAVE_MMAP is true.
  49.267 +
  49.268 +ONLY_MSPACES             default: 0 (false)
  49.269 +  If true, only compile in mspace versions, not regular versions.
  49.270 +
  49.271 +USE_LOCKS                default: 0 (false)
  49.272 +  Causes each call to each public routine to be surrounded with
  49.273 +  pthread or WIN32 mutex lock/unlock. (If set true, this can be
  49.274 +  overridden on a per-mspace basis for mspace versions.)
  49.275 +
  49.276 +FOOTERS                  default: 0
  49.277 +  If true, provide extra checking and dispatching by placing
  49.278 +  information in the footers of allocated chunks. This adds
  49.279 +  space and time overhead.
  49.280 +
  49.281 +INSECURE                 default: 0
  49.282 +  If true, omit checks for usage errors and heap space overwrites.
  49.283 +
  49.284 +USE_DL_PREFIX            default: NOT defined
  49.285 +  Causes compiler to prefix all public routines with the string 'dl'.
  49.286 +  This can be useful when you only want to use this malloc in one part
  49.287 +  of a program, using your regular system malloc elsewhere.
  49.288 +
  49.289 +ABORT                    default: defined as abort()
  49.290 +  Defines how to abort on failed checks.  On most systems, a failed
  49.291 +  check cannot die with an "assert" or even print an informative
  49.292 +  message, because the underlying print routines in turn call malloc,
  49.293 +  which will fail again.  Generally, the best policy is to simply call
  49.294 +  abort(). It's not very useful to do more than this because many
  49.295 +  errors due to overwriting will show up as address faults (null, odd
  49.296 +  addresses etc) rather than malloc-triggered checks, so will also
  49.297 +  abort.  Also, most compilers know that abort() does not return, so
  49.298 +  can better optimize code conditionally calling it.
  49.299 +
  49.300 +PROCEED_ON_ERROR           default: defined as 0 (false)
  49.301 +  Controls whether detected bad addresses cause them to bypassed
  49.302 +  rather than aborting. If set, detected bad arguments to free and
  49.303 +  realloc are ignored. And all bookkeeping information is zeroed out
  49.304 +  upon a detected overwrite of freed heap space, thus losing the
  49.305 +  ability to ever return it from malloc again, but enabling the
  49.306 +  application to proceed. If PROCEED_ON_ERROR is defined, the
  49.307 +  static variable malloc_corruption_error_count is compiled in
  49.308 +  and can be examined to see if errors have occurred. This option
  49.309 +  generates slower code than the default abort policy.
  49.310 +
  49.311 +DEBUG                    default: NOT defined
  49.312 +  The DEBUG setting is mainly intended for people trying to modify
  49.313 +  this code or diagnose problems when porting to new platforms.
  49.314 +  However, it may also be able to better isolate user errors than just
  49.315 +  using runtime checks.  The assertions in the check routines spell
  49.316 +  out in more detail the assumptions and invariants underlying the
  49.317 +  algorithms.  The checking is fairly extensive, and will slow down
  49.318 +  execution noticeably. Calling malloc_stats or mallinfo with DEBUG
  49.319 +  set will attempt to check every non-mmapped allocated and free chunk
  49.320 +  in the course of computing the summaries.
  49.321 +
  49.322 +ABORT_ON_ASSERT_FAILURE   default: defined as 1 (true)
  49.323 +  Debugging assertion failures can be nearly impossible if your
  49.324 +  version of the assert macro causes malloc to be called, which will
  49.325 +  lead to a cascade of further failures, blowing the runtime stack.
  49.326 +  ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),
  49.327 +  which will usually make debugging easier.
  49.328 +
  49.329 +MALLOC_FAILURE_ACTION     default: sets errno to ENOMEM, or no-op on win32
  49.330 +  The action to take before "return 0" when malloc fails to be able to
  49.331 +  return memory because there is none available.
  49.332 +
  49.333 +HAVE_MORECORE             default: 1 (true) unless win32 or ONLY_MSPACES
  49.334 +  True if this system supports sbrk or an emulation of it.
  49.335 +
  49.336 +MORECORE                  default: sbrk
  49.337 +  The name of the sbrk-style system routine to call to obtain more
  49.338 +  memory.  See below for guidance on writing custom MORECORE
  49.339 +  functions. The type of the argument to sbrk/MORECORE varies across
  49.340 +  systems.  It cannot be size_t, because it supports negative
  49.341 +  arguments, so it is normally the signed type of the same width as
  49.342 +  size_t (sometimes declared as "intptr_t").  It doesn't much matter
  49.343 +  though. Internally, we only call it with arguments less than half
  49.344 +  the max value of a size_t, which should work across all reasonable
  49.345 +  possibilities, although sometimes generating compiler warnings.  See
  49.346 +  near the end of this file for guidelines for creating a custom
  49.347 +  version of MORECORE.
  49.348 +
  49.349 +MORECORE_CONTIGUOUS       default: 1 (true)
  49.350 +  If true, take advantage of fact that consecutive calls to MORECORE
  49.351 +  with positive arguments always return contiguous increasing
  49.352 +  addresses.  This is true of unix sbrk. It does not hurt too much to
  49.353 +  set it true anyway, since malloc copes with non-contiguities.
  49.354 +  Setting it false when definitely non-contiguous saves time
  49.355 +  and possibly wasted space it would take to discover this though.
  49.356 +
  49.357 +MORECORE_CANNOT_TRIM      default: NOT defined
  49.358 +  True if MORECORE cannot release space back to the system when given
  49.359 +  negative arguments. This is generally necessary only if you are
  49.360 +  using a hand-crafted MORECORE function that cannot handle negative
  49.361 +  arguments.
  49.362 +
  49.363 +HAVE_MMAP                 default: 1 (true)
  49.364 +  True if this system supports mmap or an emulation of it.  If so, and
  49.365 +  HAVE_MORECORE is not true, MMAP is used for all system
  49.366 +  allocation. If set and HAVE_MORECORE is true as well, MMAP is
  49.367 +  primarily used to directly allocate very large blocks. It is also
  49.368 +  used as a backup strategy in cases where MORECORE fails to provide
  49.369 +  space from system. Note: A single call to MUNMAP is assumed to be
  49.370 +  able to unmap memory that may have be allocated using multiple calls
  49.371 +  to MMAP, so long as they are adjacent.
  49.372 +
  49.373 +HAVE_MREMAP               default: 1 on linux, else 0
  49.374 +  If true realloc() uses mremap() to re-allocate large blocks and
  49.375 +  extend or shrink allocation spaces.
  49.376 +
  49.377 +MMAP_CLEARS               default: 1 on unix
  49.378 +  True if mmap clears memory so calloc doesn't need to. This is true
  49.379 +  for standard unix mmap using /dev/zero.
  49.380 +
  49.381 +USE_BUILTIN_FFS            default: 0 (i.e., not used)
  49.382 +  Causes malloc to use the builtin ffs() function to compute indices.
  49.383 +  Some compilers may recognize and intrinsify ffs to be faster than the
  49.384 +  supplied C version. Also, the case of x86 using gcc is special-cased
  49.385 +  to an asm instruction, so is already as fast as it can be, and so
  49.386 +  this setting has no effect. (On most x86s, the asm version is only
  49.387 +  slightly faster than the C version.)
  49.388 +
  49.389 +malloc_getpagesize         default: derive from system includes, or 4096.
  49.390 +  The system page size. To the extent possible, this malloc manages
  49.391 +  memory from the system in page-size units.  This may be (and
  49.392 +  usually is) a function rather than a constant. This is ignored
  49.393 +  if WIN32, where page size is determined using getSystemInfo during
  49.394 +  initialization.
  49.395 +
  49.396 +USE_DEV_RANDOM             default: 0 (i.e., not used)
  49.397 +  Causes malloc to use /dev/random to initialize secure magic seed for
  49.398 +  stamping footers. Otherwise, the current time is used.
  49.399 +
  49.400 +NO_MALLINFO                default: 0
  49.401 +  If defined, don't compile "mallinfo". This can be a simple way
  49.402 +  of dealing with mismatches between system declarations and
  49.403 +  those in this file.
  49.404 +
  49.405 +MALLINFO_FIELD_TYPE        default: size_t
  49.406 +  The type of the fields in the mallinfo struct. This was originally
  49.407 +  defined as "int" in SVID etc, but is more usefully defined as
  49.408 +  size_t. The value is used only if  HAVE_USR_INCLUDE_MALLOC_H is not set
  49.409 +
  49.410 +REALLOC_ZERO_BYTES_FREES    default: not defined
  49.411 +  This should be set if a call to realloc with zero bytes should 
  49.412 +  be the same as a call to free. Some people think it should. Otherwise, 
  49.413 +  since this malloc returns a unique pointer for malloc(0), so does 
  49.414 +  realloc(p, 0).
  49.415 +
  49.416 +LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H
  49.417 +LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H,  LACKS_ERRNO_H
  49.418 +LACKS_STDLIB_H                default: NOT defined unless on WIN32
  49.419 +  Define these if your system does not have these header files.
  49.420 +  You might need to manually insert some of the declarations they provide.
  49.421 +
  49.422 +DEFAULT_GRANULARITY        default: page size if MORECORE_CONTIGUOUS,
  49.423 +                                system_info.dwAllocationGranularity in WIN32,
  49.424 +                                otherwise 64K.
  49.425 +      Also settable using mallopt(M_GRANULARITY, x)
  49.426 +  The unit for allocating and deallocating memory from the system.  On
  49.427 +  most systems with contiguous MORECORE, there is no reason to
  49.428 +  make this more than a page. However, systems with MMAP tend to
  49.429 +  either require or encourage larger granularities.  You can increase
  49.430 +  this value to prevent system allocation functions to be called so
  49.431 +  often, especially if they are slow.  The value must be at least one
  49.432 +  page and must be a power of two.  Setting to 0 causes initialization
  49.433 +  to either page size or win32 region size.  (Note: In previous
  49.434 +  versions of malloc, the equivalent of this option was called
  49.435 +  "TOP_PAD")
  49.436 +
  49.437 +DEFAULT_TRIM_THRESHOLD    default: 2MB
  49.438 +      Also settable using mallopt(M_TRIM_THRESHOLD, x)
  49.439 +  The maximum amount of unused top-most memory to keep before
  49.440 +  releasing via malloc_trim in free().  Automatic trimming is mainly
  49.441 +  useful in long-lived programs using contiguous MORECORE.  Because
  49.442 +  trimming via sbrk can be slow on some systems, and can sometimes be
  49.443 +  wasteful (in cases where programs immediately afterward allocate
  49.444 +  more large chunks) the value should be high enough so that your
  49.445 +  overall system performance would improve by releasing this much
  49.446 +  memory.  As a rough guide, you might set to a value close to the
  49.447 +  average size of a process (program) running on your system.
  49.448 +  Releasing this much memory would allow such a process to run in
  49.449 +  memory.  Generally, it is worth tuning trim thresholds when a
  49.450 +  program undergoes phases where several large chunks are allocated
  49.451 +  and released in ways that can reuse each other's storage, perhaps
  49.452 +  mixed with phases where there are no such chunks at all. The trim
  49.453 +  value must be greater than page size to have any useful effect.  To
  49.454 +  disable trimming completely, you can set to MAX_SIZE_T. Note that the trick
  49.455 +  some people use of mallocing a huge space and then freeing it at
  49.456 +  program startup, in an attempt to reserve system memory, doesn't
  49.457 +  have the intended effect under automatic trimming, since that memory
  49.458 +  will immediately be returned to the system.
  49.459 +
  49.460 +DEFAULT_MMAP_THRESHOLD       default: 256K
  49.461 +      Also settable using mallopt(M_MMAP_THRESHOLD, x)
  49.462 +  The request size threshold for using MMAP to directly service a
  49.463 +  request. Requests of at least this size that cannot be allocated
  49.464 +  using already-existing space will be serviced via mmap.  (If enough
  49.465 +  normal freed space already exists it is used instead.)  Using mmap
  49.466 +  segregates relatively large chunks of memory so that they can be
  49.467 +  individually obtained and released from the host system. A request
  49.468 +  serviced through mmap is never reused by any other request (at least
  49.469 +  not directly; the system may just so happen to remap successive
  49.470 +  requests to the same locations).  Segregating space in this way has
  49.471 +  the benefits that: Mmapped space can always be individually released
  49.472 +  back to the system, which helps keep the system level memory demands
  49.473 +  of a long-lived program low.  Also, mapped memory doesn't become
  49.474 +  `locked' between other chunks, as can happen with normally allocated
  49.475 +  chunks, which means that even trimming via malloc_trim would not
  49.476 +  release them.  However, it has the disadvantage that the space
  49.477 +  cannot be reclaimed, consolidated, and then used to service later
  49.478 +  requests, as happens with normal chunks.  The advantages of mmap
  49.479 +  nearly always outweigh disadvantages for "large" chunks, but the
  49.480 +  value of "large" may vary across systems.  The default is an
  49.481 +  empirically derived value that works well in most systems. You can
  49.482 +  disable mmap by setting to MAX_SIZE_T.
  49.483 +
  49.484 +*/
  49.485 +
  49.486 +#ifndef WIN32
  49.487 +#ifdef _WIN32
  49.488 +#define WIN32 1
  49.489 +#endif  /* _WIN32 */
  49.490 +#endif  /* WIN32 */
  49.491 +#ifdef WIN32
  49.492 +#include "SDL_windows.h"
  49.493 +#define HAVE_MMAP 1
  49.494 +#define HAVE_MORECORE 0
  49.495 +#define LACKS_UNISTD_H
  49.496 +#define LACKS_SYS_PARAM_H
  49.497 +#define LACKS_SYS_MMAN_H
  49.498 +#define LACKS_STRING_H
  49.499 +#define LACKS_STRINGS_H
  49.500 +#define LACKS_SYS_TYPES_H
  49.501 +#define LACKS_ERRNO_H
  49.502 +#define MALLOC_FAILURE_ACTION
  49.503 +#define MMAP_CLEARS 0 /* WINCE and some others apparently don't clear */
  49.504 +#endif  /* WIN32 */
  49.505 +
  49.506 +#if defined(DARWIN) || defined(_DARWIN)
  49.507 +/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */
  49.508 +#ifndef HAVE_MORECORE
  49.509 +#define HAVE_MORECORE 0
  49.510 +#define HAVE_MMAP 1
  49.511 +#endif  /* HAVE_MORECORE */
  49.512 +#endif  /* DARWIN */
  49.513 +
  49.514 +#ifndef LACKS_SYS_TYPES_H
  49.515 +#include <sys/types.h>  /* For size_t */
  49.516 +#endif  /* LACKS_SYS_TYPES_H */
  49.517 +
  49.518 +/* The maximum possible size_t value has all bits set */
  49.519 +#define MAX_SIZE_T           (~(size_t)0)
  49.520 +
  49.521 +#ifndef ONLY_MSPACES
  49.522 +#define ONLY_MSPACES 0
  49.523 +#endif  /* ONLY_MSPACES */
  49.524 +#ifndef MSPACES
  49.525 +#if ONLY_MSPACES
  49.526 +#define MSPACES 1
  49.527 +#else   /* ONLY_MSPACES */
  49.528 +#define MSPACES 0
  49.529 +#endif  /* ONLY_MSPACES */
  49.530 +#endif  /* MSPACES */
  49.531 +#ifndef MALLOC_ALIGNMENT
  49.532 +#define MALLOC_ALIGNMENT ((size_t)8U)
  49.533 +#endif  /* MALLOC_ALIGNMENT */
  49.534 +#ifndef FOOTERS
  49.535 +#define FOOTERS 0
  49.536 +#endif  /* FOOTERS */
  49.537 +#ifndef ABORT
  49.538 +#define ABORT  abort()
  49.539 +#endif  /* ABORT */
  49.540 +#ifndef ABORT_ON_ASSERT_FAILURE
  49.541 +#define ABORT_ON_ASSERT_FAILURE 1
  49.542 +#endif  /* ABORT_ON_ASSERT_FAILURE */
  49.543 +#ifndef PROCEED_ON_ERROR
  49.544 +#define PROCEED_ON_ERROR 0
  49.545 +#endif  /* PROCEED_ON_ERROR */
  49.546 +#ifndef USE_LOCKS
  49.547 +#define USE_LOCKS 0
  49.548 +#endif  /* USE_LOCKS */
  49.549 +#ifndef INSECURE
  49.550 +#define INSECURE 0
  49.551 +#endif  /* INSECURE */
  49.552 +#ifndef HAVE_MMAP
  49.553 +#define HAVE_MMAP 1
  49.554 +#endif  /* HAVE_MMAP */
  49.555 +#ifndef MMAP_CLEARS
  49.556 +#define MMAP_CLEARS 1
  49.557 +#endif  /* MMAP_CLEARS */
  49.558 +#ifndef HAVE_MREMAP
  49.559 +#ifdef linux
  49.560 +#define HAVE_MREMAP 1
  49.561 +#else   /* linux */
  49.562 +#define HAVE_MREMAP 0
  49.563 +#endif  /* linux */
  49.564 +#endif  /* HAVE_MREMAP */
  49.565 +#ifndef MALLOC_FAILURE_ACTION
  49.566 +#define MALLOC_FAILURE_ACTION  errno = ENOMEM;
  49.567 +#endif  /* MALLOC_FAILURE_ACTION */
  49.568 +#ifndef HAVE_MORECORE
  49.569 +#if ONLY_MSPACES
  49.570 +#define HAVE_MORECORE 0
  49.571 +#else   /* ONLY_MSPACES */
  49.572 +#define HAVE_MORECORE 1
  49.573 +#endif  /* ONLY_MSPACES */
  49.574 +#endif  /* HAVE_MORECORE */
  49.575 +#if !HAVE_MORECORE
  49.576 +#define MORECORE_CONTIGUOUS 0
  49.577 +#else   /* !HAVE_MORECORE */
  49.578 +#ifndef MORECORE
  49.579 +#define MORECORE sbrk
  49.580 +#endif  /* MORECORE */
  49.581 +#ifndef MORECORE_CONTIGUOUS
  49.582 +#define MORECORE_CONTIGUOUS 1
  49.583 +#endif  /* MORECORE_CONTIGUOUS */
  49.584 +#endif  /* HAVE_MORECORE */
  49.585 +#ifndef DEFAULT_GRANULARITY
  49.586 +#if MORECORE_CONTIGUOUS
  49.587 +#define DEFAULT_GRANULARITY (0)  /* 0 means to compute in init_mparams */
  49.588 +#else   /* MORECORE_CONTIGUOUS */
  49.589 +#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)
  49.590 +#endif  /* MORECORE_CONTIGUOUS */
  49.591 +#endif  /* DEFAULT_GRANULARITY */
  49.592 +#ifndef DEFAULT_TRIM_THRESHOLD
  49.593 +#ifndef MORECORE_CANNOT_TRIM
  49.594 +#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)
  49.595 +#else   /* MORECORE_CANNOT_TRIM */
  49.596 +#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T
  49.597 +#endif  /* MORECORE_CANNOT_TRIM */
  49.598 +#endif  /* DEFAULT_TRIM_THRESHOLD */
  49.599 +#ifndef DEFAULT_MMAP_THRESHOLD
  49.600 +#if HAVE_MMAP
  49.601 +#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)
  49.602 +#else   /* HAVE_MMAP */
  49.603 +#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
  49.604 +#endif  /* HAVE_MMAP */
  49.605 +#endif  /* DEFAULT_MMAP_THRESHOLD */
  49.606 +#ifndef USE_BUILTIN_FFS
  49.607 +#define USE_BUILTIN_FFS 0
  49.608 +#endif  /* USE_BUILTIN_FFS */
  49.609 +#ifndef USE_DEV_RANDOM
  49.610 +#define USE_DEV_RANDOM 0
  49.611 +#endif  /* USE_DEV_RANDOM */
  49.612 +#ifndef NO_MALLINFO
  49.613 +#define NO_MALLINFO 0
  49.614 +#endif  /* NO_MALLINFO */
  49.615 +#ifndef MALLINFO_FIELD_TYPE
  49.616 +#define MALLINFO_FIELD_TYPE size_t
  49.617 +#endif  /* MALLINFO_FIELD_TYPE */
  49.618 +
  49.619 +/*
  49.620 +  mallopt tuning options.  SVID/XPG defines four standard parameter
  49.621 +  numbers for mallopt, normally defined in malloc.h.  None of these
  49.622 +  are used in this malloc, so setting them has no effect. But this
  49.623 +  malloc does support the following options.
  49.624 +*/
  49.625 +
  49.626 +#define M_TRIM_THRESHOLD     (-1)
  49.627 +#define M_GRANULARITY        (-2)
  49.628 +#define M_MMAP_THRESHOLD     (-3)
  49.629 +
  49.630 +/* ------------------------ Mallinfo declarations ------------------------ */
  49.631 +
  49.632 +#if !NO_MALLINFO
  49.633 +/*
  49.634 +  This version of malloc supports the standard SVID/XPG mallinfo
  49.635 +  routine that returns a struct containing usage properties and
  49.636 +  statistics. It should work on any system that has a
  49.637 +  /usr/include/malloc.h defining struct mallinfo.  The main
  49.638 +  declaration needed is the mallinfo struct that is returned (by-copy)
  49.639 +  by mallinfo().  The malloinfo struct contains a bunch of fields that
  49.640 +  are not even meaningful in this version of malloc.  These fields are
  49.641 +  are instead filled by mallinfo() with other numbers that might be of
  49.642 +  interest.
  49.643 +
  49.644 +  HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
  49.645 +  /usr/include/malloc.h file that includes a declaration of struct
  49.646 +  mallinfo.  If so, it is included; else a compliant version is
  49.647 +  declared below.  These must be precisely the same for mallinfo() to
  49.648 +  work.  The original SVID version of this struct, defined on most
  49.649 +  systems with mallinfo, declares all fields as ints. But some others
  49.650 +  define as unsigned long. If your system defines the fields using a
  49.651 +  type of different width than listed here, you MUST #include your
  49.652 +  system version and #define HAVE_USR_INCLUDE_MALLOC_H.
  49.653 +*/
  49.654 +
  49.655 +/* #define HAVE_USR_INCLUDE_MALLOC_H */
  49.656 +
  49.657 +#ifdef HAVE_USR_INCLUDE_MALLOC_H
  49.658 +#include "/usr/include/malloc.h"
  49.659 +#else /* HAVE_USR_INCLUDE_MALLOC_H */
  49.660 +
  49.661 +struct mallinfo {
  49.662 +  MALLINFO_FIELD_TYPE arena;    /* non-mmapped space allocated from system */
  49.663 +  MALLINFO_FIELD_TYPE ordblks;  /* number of free chunks */
  49.664 +  MALLINFO_FIELD_TYPE smblks;   /* always 0 */
  49.665 +  MALLINFO_FIELD_TYPE hblks;    /* always 0 */
  49.666 +  MALLINFO_FIELD_TYPE hblkhd;   /* space in mmapped regions */
  49.667 +  MALLINFO_FIELD_TYPE usmblks;  /* maximum total allocated space */
  49.668 +  MALLINFO_FIELD_TYPE fsmblks;  /* always 0 */
  49.669 +  MALLINFO_FIELD_TYPE uordblks; /* total allocated space */
  49.670 +  MALLINFO_FIELD_TYPE fordblks; /* total free space */
  49.671 +  MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */
  49.672 +};
  49.673 +
  49.674 +#endif /* HAVE_USR_INCLUDE_MALLOC_H */
  49.675 +#endif /* NO_MALLINFO */
  49.676 +
  49.677 +#ifdef __cplusplus
  49.678 +extern "C" {
  49.679 +#endif /* __cplusplus */
  49.680 +
  49.681 +#if !ONLY_MSPACES
  49.682 +
  49.683 +/* ------------------- Declarations of public routines ------------------- */
  49.684 +
  49.685 +#ifndef USE_DL_PREFIX
  49.686 +#define dlcalloc               calloc
  49.687 +#define dlfree                 free
  49.688 +#define dlmalloc               malloc
  49.689 +#define dlmemalign             memalign
  49.690 +#define dlrealloc              realloc
  49.691 +#define dlvalloc               valloc
  49.692 +#define dlpvalloc              pvalloc
  49.693 +#define dlmallinfo             mallinfo
  49.694 +#define dlmallopt              mallopt
  49.695 +#define dlmalloc_trim          malloc_trim
  49.696 +#define dlmalloc_stats         malloc_stats
  49.697 +#define dlmalloc_usable_size   malloc_usable_size
  49.698 +#define dlmalloc_footprint     malloc_footprint
  49.699 +#define dlmalloc_max_footprint malloc_max_footprint
  49.700 +#define dlindependent_calloc   independent_calloc
  49.701 +#define dlindependent_comalloc independent_comalloc
  49.702 +#endif /* USE_DL_PREFIX */
  49.703 +
  49.704 +
  49.705 +/*
  49.706 +  malloc(size_t n)
  49.707 +  Returns a pointer to a newly allocated chunk of at least n bytes, or
  49.708 +  null if no space is available, in which case errno is set to ENOMEM
  49.709 +  on ANSI C systems.
  49.710 +
  49.711 +  If n is zero, malloc returns a minimum-sized chunk. (The minimum
  49.712 +  size is 16 bytes on most 32bit systems, and 32 bytes on 64bit
  49.713 +  systems.)  Note that size_t is an unsigned type, so calls with
  49.714 +  arguments that would be negative if signed are interpreted as
  49.715 +  requests for huge amounts of space, which will often fail. The
  49.716 +  maximum supported value of n differs across systems, but is in all
  49.717 +  cases less than the maximum representable value of a size_t.
  49.718 +*/
  49.719 +void* dlmalloc(size_t);
  49.720 +
  49.721 +/*
  49.722 +  free(void* p)
  49.723 +  Releases the chunk of memory pointed to by p, that had been previously
  49.724 +  allocated using malloc or a related routine such as realloc.
  49.725 +  It has no effect if p is null. If p was not malloced or already
  49.726 +  freed, free(p) will by default cause the current program to abort.
  49.727 +*/
  49.728 +void  dlfree(void*);
  49.729 +
  49.730 +/*
  49.731 +  calloc(size_t n_elements, size_t element_size);
  49.732 +  Returns a pointer to n_elements * element_size bytes, with all locations
  49.733 +  set to zero.
  49.734 +*/
  49.735 +void* dlcalloc(size_t, size_t);
  49.736 +
  49.737 +/*
  49.738 +  realloc(void* p, size_t n)
  49.739 +  Returns a pointer to a chunk of size n that contains the same data
  49.740 +  as does chunk p up to the minimum of (n, p's size) bytes, or null
  49.741 +  if no space is available.
  49.742 +
  49.743 +  The returned pointer may or may not be the same as p. The algorithm
  49.744 +  prefers extending p in most cases when possible, otherwise it
  49.745 +  employs the equivalent of a malloc-copy-free sequence.
  49.746 +
  49.747 +  If p is null, realloc is equivalent to malloc.
  49.748 +
  49.749 +  If space is not available, realloc returns null, errno is set (if on
  49.750 +  ANSI) and p is NOT freed.
  49.751 +
  49.752 +  if n is for fewer bytes than already held by p, the newly unused
  49.753 +  space is lopped off and freed if possible.  realloc with a size
  49.754 +  argument of zero (re)allocates a minimum-sized chunk.
  49.755 +
  49.756 +  The old unix realloc convention of allowing the last-free'd chunk
  49.757 +  to be used as an argument to realloc is not supported.
  49.758 +*/
  49.759 +
  49.760 +void* dlrealloc(void*, size_t);
  49.761 +
  49.762 +/*
  49.763 +  memalign(size_t alignment, size_t n);
  49.764 +  Returns a pointer to a newly allocated chunk of n bytes, aligned
  49.765 +  in accord with the alignment argument.
  49.766 +
  49.767 +  The alignment argument should be a power of two. If the argument is
  49.768 +  not a power of two, the nearest greater power is used.
  49.769 +  8-byte alignment is guaranteed by normal malloc calls, so don't
  49.770 +  bother calling memalign with an argument of 8 or less.
  49.771 +
  49.772 +  Overreliance on memalign is a sure way to fragment space.
  49.773 +*/
  49.774 +void* dlmemalign(size_t, size_t);
  49.775 +
  49.776 +/*
  49.777 +  valloc(size_t n);
  49.778 +  Equivalent to memalign(pagesize, n), where pagesize is the page
  49.779 +  size of the system. If the pagesize is unknown, 4096 is used.
  49.780 +*/
  49.781 +void* dlvalloc(size_t);
  49.782 +
  49.783 +/*
  49.784 +  mallopt(int parameter_number, int parameter_value)
  49.785 +  Sets tunable parameters The format is to provide a
  49.786 +  (parameter-number, parameter-value) pair.  mallopt then sets the
  49.787 +  corresponding parameter to the argument value if it can (i.e., so
  49.788 +  long as the value is meaningful), and returns 1 if successful else
  49.789 +  0.  SVID/XPG/ANSI defines four standard param numbers for mallopt,
  49.790 +  normally defined in malloc.h.  None of these are use in this malloc,
  49.791 +  so setting them has no effect. But this malloc also supports other
  49.792 +  options in mallopt. See below for details.  Briefly, supported
  49.793 +  parameters are as follows (listed defaults are for "typical"
  49.794 +  configurations).
  49.795 +
  49.796 +  Symbol            param #  default    allowed param values
  49.797 +  M_TRIM_THRESHOLD     -1   2*1024*1024   any   (MAX_SIZE_T disables)
  49.798 +  M_GRANULARITY        -2     page size   any power of 2 >= page size
  49.799 +  M_MMAP_THRESHOLD     -3      256*1024   any   (or 0 if no MMAP support)
  49.800 +*/
  49.801 +int dlmallopt(int, int);
  49.802 +
  49.803 +/*
  49.804 +  malloc_footprint();
  49.805 +  Returns the number of bytes obtained from the system.  The total
  49.806 +  number of bytes allocated by malloc, realloc etc., is less than this
  49.807 +  value. Unlike mallinfo, this function returns only a precomputed
  49.808 +  result, so can be called frequently to monitor memory consumption.
  49.809 +  Even if locks are otherwise defined, this function does not use them,
  49.810 +  so results might not be up to date.
  49.811 +*/
  49.812 +size_t dlmalloc_footprint(void);
  49.813 +
  49.814 +/*
  49.815 +  malloc_max_footprint();
  49.816 +  Returns the maximum number of bytes obtained from the system. This
  49.817 +  value will be greater than current footprint if deallocated space
  49.818 +  has been reclaimed by the system. The peak number of bytes allocated
  49.819 +  by malloc, realloc etc., is less than this value. Unlike mallinfo,
  49.820 +  this function returns only a precomputed result, so can be called
  49.821 +  frequently to monitor memory consumption.  Even if locks are
  49.822 +  otherwise defined, this function does not use them, so results might
  49.823 +  not be up to date.
  49.824 +*/
  49.825 +size_t dlmalloc_max_footprint(void);
  49.826 +
  49.827 +#if !NO_MALLINFO
  49.828 +/*
  49.829 +  mallinfo()
  49.830 +  Returns (by copy) a struct containing various summary statistics:
  49.831 +
  49.832 +  arena:     current total non-mmapped bytes allocated from system
  49.833 +  ordblks:   the number of free chunks
  49.834 +  smblks:    always zero.
  49.835 +  hblks:     current number of mmapped regions
  49.836 +  hblkhd:    total bytes held in mmapped regions
  49.837 +  usmblks:   the maximum total allocated space. This will be greater
  49.838 +                than current total if trimming has occurred.
  49.839 +  fsmblks:   always zero
  49.840 +  uordblks:  current total allocated space (normal or mmapped)
  49.841 +  fordblks:  total free space
  49.842 +  keepcost:  the maximum number of bytes that could ideally be released
  49.843 +               back to system via malloc_trim. ("ideally" means that
  49.844 +               it ignores page restrictions etc.)
  49.845 +
  49.846 +  Because these fields are ints, but internal bookkeeping may
  49.847 +  be kept as longs, the reported values may wrap around zero and
  49.848 +  thus be inaccurate.
  49.849 +*/
  49.850 +struct mallinfo dlmallinfo(void);
  49.851 +#endif /* NO_MALLINFO */
  49.852 +
  49.853 +/*
  49.854 +  independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);
  49.855 +
  49.856 +  independent_calloc is similar to calloc, but instead of returning a
  49.857 +  single cleared space, it returns an array of pointers to n_elements
  49.858 +  independent elements that can hold contents of size elem_size, each
  49.859 +  of which starts out cleared, and can be independently freed,
  49.860 +  realloc'ed etc. The elements are guaranteed to be adjacently
  49.861 +  allocated (this is not guaranteed to occur with multiple callocs or
  49.862 +  mallocs), which may also improve cache locality in some
  49.863 +  applications.
  49.864 +
  49.865 +  The "chunks" argument is optional (i.e., may be null, which is
  49.866 +  probably the most typical usage). If it is null, the returned array
  49.867 +  is itself dynamically allocated and should also be freed when it is
  49.868 +  no longer needed. Otherwise, the chunks array must be of at least
  49.869 +  n_elements in length. It is filled in with the pointers to the
  49.870 +  chunks.
  49.871 +
  49.872 +  In either case, independent_calloc returns this pointer array, or
  49.873 +  null if the allocation failed.  If n_elements is zero and "chunks"
  49.874 +  is null, it returns a chunk representing an array with zero elements
  49.875 +  (which should be freed if not wanted).
  49.876 +
  49.877 +  Each element must be individually freed when it is no longer
  49.878 +  needed. If you'd like to instead be able to free all at once, you
  49.879 +  should instead use regular calloc and assign pointers into this
  49.880 +  space to represent elements.  (In this case though, you cannot
  49.881 +  independently free elements.)
  49.882 +
  49.883 +  independent_calloc simplifies and speeds up implementations of many
  49.884 +  kinds of pools.  It may also be useful when constructing large data
  49.885 +  structures that initially have a fixed number of fixed-sized nodes,
  49.886 +  but the number is not known at compile time, and some of the nodes
  49.887 +  may later need to be freed. For example:
  49.888 +
  49.889 +  struct Node { int item; struct Node* next; };
  49.890 +
  49.891 +  struct Node* build_list() {
  49.892 +    struct Node** pool;
  49.893 +    int n = read_number_of_nodes_needed();
  49.894 +    if (n <= 0) return 0;
  49.895 +    pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
  49.896 +    if (pool == 0) die();
  49.897 +    // organize into a linked list...
  49.898 +    struct Node* first = pool[0];
  49.899 +    for (i = 0; i < n-1; ++i)
  49.900 +      pool[i]->next = pool[i+1];
  49.901 +    free(pool);     // Can now free the array (or not, if it is needed later)
  49.902 +    return first;
  49.903 +  }
  49.904 +*/
  49.905 +void** dlindependent_calloc(size_t, size_t, void**);
  49.906 +
  49.907 +/*
  49.908 +  independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
  49.909 +
  49.910 +  independent_comalloc allocates, all at once, a set of n_elements
  49.911 +  chunks with sizes indicated in the "sizes" array.    It returns
  49.912 +  an array of pointers to these elements, each of which can be
  49.913 +  independently freed, realloc'ed etc. The elements are guaranteed to
  49.914 +  be adjacently allocated (this is not guaranteed to occur with
  49.915 +  multiple callocs or mallocs), which may also improve cache locality
  49.916 +  in some applications.
  49.917 +
  49.918 +  The "chunks" argument is optional (i.e., may be null). If it is null
  49.919 +  the returned array is itself dynamically allocated and should also
  49.920 +  be freed when it is no longer needed. Otherwise, the chunks array
  49.921 +  must be of at least n_elements in length. It is filled in with the
  49.922 +  pointers to the chunks.
  49.923 +
  49.924 +  In either case, independent_comalloc returns this pointer array, or
  49.925 +  null if the allocation failed.  If n_elements is zero and chunks is
  49.926 +  null, it returns a chunk representing an array with zero elements
  49.927 +  (which should be freed if not wanted).
  49.928 +
  49.929 +  Each element must be individually freed when it is no longer
  49.930 +  needed. If you'd like to instead be able to free all at once, you
  49.931 +  should instead use a single regular malloc, and assign pointers at
  49.932 +  particular offsets in the aggregate space. (In this case though, you
  49.933 +  cannot independently free elements.)
  49.934 +
  49.935 +  independent_comallac differs from independent_calloc in that each
  49.936 +  element may have a different size, and also that it does not
  49.937 +  automatically clear elements.
  49.938 +
  49.939 +  independent_comalloc can be used to speed up allocation in cases
  49.940 +  where several structs or objects must always be allocated at the
  49.941 +  same time.  For example:
  49.942 +
  49.943 +  struct Head { ... }
  49.944 +  struct Foot { ... }
  49.945 +
  49.946 +  void send_message(char* msg) {
  49.947 +    int msglen = strlen(msg);
  49.948 +    size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
  49.949 +    void* chunks[3];
  49.950 +    if (independent_comalloc(3, sizes, chunks) == 0)
  49.951 +      die();
  49.952 +    struct Head* head = (struct Head*)(chunks[0]);
  49.953 +    char*        body = (char*)(chunks[1]);
  49.954 +    struct Foot* foot = (struct Foot*)(chunks[2]);
  49.955 +    // ...
  49.956 +  }
  49.957 +
  49.958 +  In general though, independent_comalloc is worth using only for
  49.959 +  larger values of n_elements. For small values, you probably won't
  49.960 +  detect enough difference from series of malloc calls to bother.
  49.961 +
  49.962 +  Overuse of independent_comalloc can increase overall memory usage,
  49.963 +  since it cannot reuse existing noncontiguous small chunks that
  49.964 +  might be available for some of the elements.
  49.965 +*/
  49.966 +void** dlindependent_comalloc(size_t, size_t*, void**);
  49.967 +
  49.968 +
  49.969 +/*
  49.970 +  pvalloc(size_t n);
  49.971 +  Equivalent to valloc(minimum-page-that-holds(n)), that is,
  49.972 +  round up n to nearest pagesize.
  49.973 + */
  49.974 +void*  dlpvalloc(size_t);
  49.975 +
  49.976 +/*
  49.977 +  malloc_trim(size_t pad);
  49.978 +
  49.979 +  If possible, gives memory back to the system (via negative arguments
  49.980 +  to sbrk) if there is unused memory at the `high' end of the malloc
  49.981 +  pool or in unused MMAP segments. You can call this after freeing
  49.982 +  large blocks of memory to potentially reduce the system-level memory
  49.983 +  requirements of a program. However, it cannot guarantee to reduce
  49.984 +  memory. Under some allocation patterns, some large free blocks of
  49.985 +  memory will be locked between two used chunks, so they cannot be
  49.986 +  given back to the system.
  49.987 +
  49.988 +  The `pad' argument to malloc_trim represents the amount of free
  49.989 +  trailing space to leave untrimmed. If this argument is zero, only
  49.990 +  the minimum amount of memory to maintain internal data structures
  49.991 +  will be left. Non-zero arguments can be supplied to maintain enough
  49.992 +  trailing space to service future expected allocations without having
  49.993 +  to re-obtain memory from the system.
  49.994 +
  49.995 +  Malloc_trim returns 1 if it actually released any memory, else 0.
  49.996 +*/
  49.997 +int  dlmalloc_trim(size_t);
  49.998 +
  49.999 +/*
 49.1000 +  malloc_usable_size(void* p);
 49.1001 +
 49.1002 +  Returns the number of bytes you can actually use in
 49.1003 +  an allocated chunk, which may be more than you requested (although
 49.1004 +  often not) due to alignment and minimum size constraints.
 49.1005 +  You can use this many bytes without worrying about
 49.1006 +  overwriting other allocated objects. This is not a particularly great
 49.1007 +  programming practice. malloc_usable_size can be more useful in
 49.1008 +  debugging and assertions, for example:
 49.1009 +
 49.1010 +  p = malloc(n);
 49.1011 +  assert(malloc_usable_size(p) >= 256);
 49.1012 +*/
 49.1013 +size_t dlmalloc_usable_size(void*);
 49.1014 +
 49.1015 +/*
 49.1016 +  malloc_stats();
 49.1017 +  Prints on stderr the amount of space obtained from the system (both
 49.1018 +  via sbrk and mmap), the maximum amount (which may be more than
 49.1019 +  current if malloc_trim and/or munmap got called), and the current
 49.1020 +  number of bytes allocated via malloc (or realloc, etc) but not yet
 49.1021 +  freed. Note that this is the number of bytes allocated, not the
 49.1022 +  number requested. It will be larger than the number requested
 49.1023 +  because of alignment and bookkeeping overhead. Because it includes
 49.1024 +  alignment wastage as being in use, this figure may be greater than
 49.1025 +  zero even when no user-level chunks are allocated.
 49.1026 +
 49.1027 +  The reported current and maximum system memory can be inaccurate if
 49.1028 +  a program makes other calls to system memory allocation functions
 49.1029 +  (normally sbrk) outside of malloc.
 49.1030 +
 49.1031 +  malloc_stats prints only the most commonly interesting statistics.
 49.1032 +  More information can be obtained by calling mallinfo.
 49.1033 +*/
 49.1034 +void  dlmalloc_stats(void);
 49.1035 +
 49.1036 +#endif /* ONLY_MSPACES */
 49.1037 +
 49.1038 +#if MSPACES
 49.1039 +
 49.1040 +/*
 49.1041 +  mspace is an opaque type representing an independent
 49.1042 +  region of space that supports mspace_malloc, etc.
 49.1043 +*/
 49.1044 +typedef void* mspace;
 49.1045 +
 49.1046 +/*
 49.1047 +  create_mspace creates and returns a new independent space with the
 49.1048 +  given initial capacity, or, if 0, the default granularity size.  It
 49.1049 +  returns null if there is no system memory available to create the
 49.1050 +  space.  If argument locked is non-zero, the space uses a separate
 49.1051 +  lock to control access. The capacity of the space will grow
 49.1052 +  dynamically as needed to service mspace_malloc requests.  You can
 49.1053 +  control the sizes of incremental increases of this space by
 49.1054 +  compiling with a different DEFAULT_GRANULARITY or dynamically
 49.1055 +  setting with mallopt(M_GRANULARITY, value).
 49.1056 +*/
 49.1057 +mspace create_mspace(size_t capacity, int locked);
 49.1058 +
 49.1059 +/*
 49.1060 +  destroy_mspace destroys the given space, and attempts to return all
 49.1061 +  of its memory back to the system, returning the total number of
 49.1062 +  bytes freed. After destruction, the results of access to all memory
 49.1063 +  used by the space become undefined.
 49.1064 +*/
 49.1065 +size_t destroy_mspace(mspace msp);
 49.1066 +
 49.1067 +/*
 49.1068 +  create_mspace_with_base uses the memory supplied as the initial base
 49.1069 +  of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this
 49.1070 +  space is used for bookkeeping, so the capacity must be at least this
 49.1071 +  large. (Otherwise 0 is returned.) When this initial space is
 49.1072 +  exhausted, additional memory will be obtained from the system.
 49.1073 +  Destroying this space will deallocate all additionally allocated
 49.1074 +  space (if possible) but not the initial base.
 49.1075 +*/
 49.1076 +mspace create_mspace_with_base(void* base, size_t capacity, int locked);
 49.1077 +
 49.1078 +/*
 49.1079 +  mspace_malloc behaves as malloc, but operates within
 49.1080 +  the given space.
 49.1081 +*/
 49.1082 +void* mspace_malloc(mspace msp, size_t bytes);
 49.1083 +
 49.1084 +/*
 49.1085 +  mspace_free behaves as free, but operates within
 49.1086 +  the given space.
 49.1087 +
 49.1088 +  If compiled with FOOTERS==1, mspace_free is not actually needed.
 49.1089 +  free may be called instead of mspace_free because freed chunks from
 49.1090 +  any space are handled by their originating spaces.
 49.1091 +*/
 49.1092 +void mspace_free(mspace msp, void* mem);
 49.1093 +
 49.1094 +/*
 49.1095 +  mspace_realloc behaves as realloc, but operates within
 49.1096 +  the given space.
 49.1097 +
 49.1098 +  If compiled with FOOTERS==1, mspace_realloc is not actually
 49.1099 +  needed.  realloc may be called instead of mspace_realloc because
 49.1100 +  realloced chunks from any space are handled by their originating
 49.1101 +  spaces.
 49.1102 +*/
 49.1103 +void* mspace_realloc(mspace msp, void* mem, size_t newsize);
 49.1104 +
 49.1105 +/*
 49.1106 +  mspace_calloc behaves as calloc, but operates within
 49.1107 +  the given space.
 49.1108 +*/
 49.1109 +void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);
 49.1110 +
 49.1111 +/*
 49.1112 +  mspace_memalign behaves as memalign, but operates within
 49.1113 +  the given space.
 49.1114 +*/
 49.1115 +void* mspace_memalign(mspace msp, size_t alignment, size_t bytes);
 49.1116 +
 49.1117 +/*
 49.1118 +  mspace_independent_calloc behaves as independent_calloc, but
 49.1119 +  operates within the given space.
 49.1120 +*/
 49.1121 +void** mspace_independent_calloc(mspace msp, size_t n_elements,
 49.1122 +                                 size_t elem_size, void* chunks[]);
 49.1123 +
 49.1124 +/*
 49.1125 +  mspace_independent_comalloc behaves as independent_comalloc, but
 49.1126 +  operates within the given space.
 49.1127 +*/
 49.1128 +void** mspace_independent_comalloc(mspace msp, size_t n_elements,
 49.1129 +                                   size_t sizes[], void* chunks[]);
 49.1130 +
 49.1131 +/*
 49.1132 +  mspace_footprint() returns the number of bytes obtained from the
 49.1133 +  system for this space.
 49.1134 +*/
 49.1135 +size_t mspace_footprint(mspace msp);
 49.1136 +
 49.1137 +/*
 49.1138 +  mspace_max_footprint() returns the peak number of bytes obtained from the
 49.1139 +  system for this space.
 49.1140 +*/
 49.1141 +size_t mspace_max_footprint(mspace msp);
 49.1142 +
 49.1143 +
 49.1144 +#if !NO_MALLINFO
 49.1145 +/*
 49.1146 +  mspace_mallinfo behaves as mallinfo, but reports properties of
 49.1147 +  the given space.
 49.1148 +*/
 49.1149 +struct mallinfo mspace_mallinfo(mspace msp);
 49.1150 +#endif /* NO_MALLINFO */
 49.1151 +
 49.1152 +/*
 49.1153 +  mspace_malloc_stats behaves as malloc_stats, but reports
 49.1154 +  properties of the given space.
 49.1155 +*/
 49.1156 +void mspace_malloc_stats(mspace msp);
 49.1157 +
 49.1158 +/*
 49.1159 +  mspace_trim behaves as malloc_trim, but
 49.1160 +  operates within the given space.
 49.1161 +*/
 49.1162 +int mspace_trim(mspace msp, size_t pad);
 49.1163 +
 49.1164 +/*
 49.1165 +  An alias for mallopt.
 49.1166 +*/
 49.1167 +int mspace_mallopt(int, int);
 49.1168 +
 49.1169 +#endif /* MSPACES */
 49.1170 +
 49.1171 +#ifdef __cplusplus
 49.1172 +};  /* end of extern "C" */
 49.1173 +#endif /* __cplusplus */
 49.1174 +
 49.1175 +/*
 49.1176 +  ========================================================================
 49.1177 +  To make a fully customizable malloc.h header file, cut everything
 49.1178 +  above this line, put into file malloc.h, edit to suit, and #include it
 49.1179 +  on the next line, as well as in programs that use this malloc.
 49.1180 +  ========================================================================
 49.1181 +*/
 49.1182 +
 49.1183 +/* #include "malloc.h" */
 49.1184 +
 49.1185 +/*------------------------------ internal #includes ---------------------- */
 49.1186 +
 49.1187 +#ifdef _MSC_VER
 49.1188 +#pragma warning( disable : 4146 ) /* no "unsigned" warnings */
 49.1189 +#endif /* _MSC_VER */
 49.1190 +
 49.1191 +#ifndef LACKS_STDIO_H
 49.1192 +#include <stdio.h>       /* for printing in malloc_stats */
 49.1193 +#endif
 49.1194 +
 49.1195 +#ifndef LACKS_ERRNO_H
 49.1196 +#include <errno.h>       /* for MALLOC_FAILURE_ACTION */
 49.1197 +#endif /* LACKS_ERRNO_H */
 49.1198 +#if FOOTERS
 49.1199 +#include <time.h>        /* for magic initialization */
 49.1200 +#endif /* FOOTERS */
 49.1201 +#ifndef LACKS_STDLIB_H
 49.1202 +#include <stdlib.h>      /* for abort() */
 49.1203 +#endif /* LACKS_STDLIB_H */
 49.1204 +#ifdef DEBUG
 49.1205 +#if ABORT_ON_ASSERT_FAILURE
 49.1206 +#define assert(x) if(!(x)) ABORT
 49.1207 +#else /* ABORT_ON_ASSERT_FAILURE */
 49.1208 +#include <assert.h>
 49.1209 +#endif /* ABORT_ON_ASSERT_FAILURE */
 49.1210 +#else  /* DEBUG */
 49.1211 +#define assert(x)
 49.1212 +#endif /* DEBUG */
 49.1213 +#ifndef LACKS_STRING_H
 49.1214 +#include <string.h>      /* for memset etc */
 49.1215 +#endif  /* LACKS_STRING_H */
 49.1216 +#if USE_BUILTIN_FFS
 49.1217 +#ifndef LACKS_STRINGS_H
 49.1218 +#include <strings.h>     /* for ffs */
 49.1219 +#endif /* LACKS_STRINGS_H */
 49.1220 +#endif /* USE_BUILTIN_FFS */
 49.1221 +#if HAVE_MMAP
 49.1222 +#ifndef LACKS_SYS_MMAN_H
 49.1223 +#include <sys/mman.h>    /* for mmap */
 49.1224 +#endif /* LACKS_SYS_MMAN_H */
 49.1225 +#ifndef LACKS_FCNTL_H
 49.1226 +#include <fcntl.h>
 49.1227 +#endif /* LACKS_FCNTL_H */
 49.1228 +#endif /* HAVE_MMAP */
 49.1229 +#if HAVE_MORECORE
 49.1230 +#ifndef LACKS_UNISTD_H
 49.1231 +#include <unistd.h>     /* for sbrk */
 49.1232 +#else /* LACKS_UNISTD_H */
 49.1233 +#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
 49.1234 +extern void*     sbrk(ptrdiff_t);
 49.1235 +#endif /* FreeBSD etc */
 49.1236 +#endif /* LACKS_UNISTD_H */
 49.1237 +#endif /* HAVE_MMAP */
 49.1238 +
 49.1239 +#ifndef WIN32
 49.1240 +#ifndef malloc_getpagesize
 49.1241 +#  ifdef _SC_PAGESIZE         /* some SVR4 systems omit an underscore */
 49.1242 +#    ifndef _SC_PAGE_SIZE
 49.1243 +#      define _SC_PAGE_SIZE _SC_PAGESIZE
 49.1244 +#    endif
 49.1245 +#  endif
 49.1246 +#  ifdef _SC_PAGE_SIZE
 49.1247 +#    define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
 49.1248 +#  else
 49.1249 +#    if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
 49.1250 +       extern size_t getpagesize();
 49.1251 +#      define malloc_getpagesize getpagesize()
 49.1252 +#    else
 49.1253 +#      ifdef WIN32 /* use supplied emulation of getpagesize */
 49.1254 +#        define malloc_getpagesize getpagesize()
 49.1255 +#      else
 49.1256 +#        ifndef LACKS_SYS_PARAM_H
 49.1257 +#          include <sys/param.h>
 49.1258 +#        endif
 49.1259 +#        ifdef EXEC_PAGESIZE
 49.1260 +#          define malloc_getpagesize EXEC_PAGESIZE
 49.1261 +#        else
 49.1262 +#          ifdef NBPG
 49.1263 +#            ifndef CLSIZE
 49.1264 +#              define malloc_getpagesize NBPG
 49.1265 +#            else
 49.1266 +#              define malloc_getpagesize (NBPG * CLSIZE)
 49.1267 +#            endif
 49.1268 +#          else
 49.1269 +#            ifdef NBPC
 49.1270 +#              define malloc_getpagesize NBPC
 49.1271 +#            else
 49.1272 +#              ifdef PAGESIZE
 49.1273 +#                define malloc_getpagesize PAGESIZE
 49.1274 +#              else /* just guess */
 49.1275 +#                define malloc_getpagesize ((size_t)4096U)
 49.1276 +#              endif
 49.1277 +#            endif
 49.1278 +#          endif
 49.1279 +#        endif
 49.1280 +#      endif
 49.1281 +#    endif
 49.1282 +#  endif
 49.1283 +#endif
 49.1284 +#endif
 49.1285 +
 49.1286 +/* ------------------- size_t and alignment properties -------------------- */
 49.1287 +
 49.1288 +/* The byte and bit size of a size_t */
 49.1289 +#define SIZE_T_SIZE         (sizeof(size_t))
 49.1290 +#define SIZE_T_BITSIZE      (sizeof(size_t) << 3)
 49.1291 +
 49.1292 +/* Some constants coerced to size_t */
 49.1293 +/* Annoying but necessary to avoid errors on some plaftorms */
 49.1294 +#define SIZE_T_ZERO         ((size_t)0)
 49.1295 +#define SIZE_T_ONE          ((size_t)1)
 49.1296 +#define SIZE_T_TWO          ((size_t)2)
 49.1297 +#define TWO_SIZE_T_SIZES    (SIZE_T_SIZE<<1)
 49.1298 +#define FOUR_SIZE_T_SIZES   (SIZE_T_SIZE<<2)
 49.1299 +#define SIX_SIZE_T_SIZES    (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES)
 49.1300 +#define HALF_MAX_SIZE_T     (MAX_SIZE_T / 2U)
 49.1301 +
 49.1302 +/* The bit mask value corresponding to MALLOC_ALIGNMENT */
 49.1303 +#define CHUNK_ALIGN_MASK    (MALLOC_ALIGNMENT - SIZE_T_ONE)
 49.1304 +
 49.1305 +/* True if address a has acceptable alignment */
 49.1306 +#define is_aligned(A)       (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0)
 49.1307 +
 49.1308 +/* the number of bytes to offset an address to align it */
 49.1309 +#define align_offset(A)\
 49.1310 + ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\
 49.1311 +  ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK))
 49.1312 +
 49.1313 +/* -------------------------- MMAP preliminaries ------------------------- */
 49.1314 +
 49.1315 +/*
 49.1316 +   If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and
 49.1317 +   checks to fail so compiler optimizer can delete code rather than
 49.1318 +   using so many "#if"s.
 49.1319 +*/
 49.1320 +
 49.1321 +
 49.1322 +/* MORECORE and MMAP must return MFAIL on failure */
 49.1323 +#define MFAIL                ((void*)(MAX_SIZE_T))
 49.1324 +#define CMFAIL               ((char*)(MFAIL)) /* defined for convenience */
 49.1325 +
 49.1326 +#if !HAVE_MMAP
 49.1327 +#define IS_MMAPPED_BIT       (SIZE_T_ZERO)
 49.1328 +#define USE_MMAP_BIT         (SIZE_T_ZERO)
 49.1329 +#define CALL_MMAP(s)         MFAIL
 49.1330 +#define CALL_MUNMAP(a, s)    (-1)
 49.1331 +#define DIRECT_MMAP(s)       MFAIL
 49.1332 +
 49.1333 +#else /* HAVE_MMAP */
 49.1334 +#define IS_MMAPPED_BIT       (SIZE_T_ONE)
 49.1335 +#define USE_MMAP_BIT         (SIZE_T_ONE)
 49.1336 +
 49.1337 +#ifndef WIN32
 49.1338 +#define CALL_MUNMAP(a, s)    munmap((a), (s))
 49.1339 +#define MMAP_PROT            (PROT_READ|PROT_WRITE)
 49.1340 +#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
 49.1341 +#define MAP_ANONYMOUS        MAP_ANON
 49.1342 +#endif /* MAP_ANON */
 49.1343 +#ifdef MAP_ANONYMOUS
 49.1344 +#define MMAP_FLAGS           (MAP_PRIVATE|MAP_ANONYMOUS)
 49.1345 +#define CALL_MMAP(s)         mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0)
 49.1346 +#else /* MAP_ANONYMOUS */
 49.1347 +/*
 49.1348 +   Nearly all versions of mmap support MAP_ANONYMOUS, so the following
 49.1349 +   is unlikely to be needed, but is supplied just in case.
 49.1350 +*/
 49.1351 +#define MMAP_FLAGS           (MAP_PRIVATE)
 49.1352 +static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
 49.1353 +#define CALL_MMAP(s) ((dev_zero_fd < 0) ? \
 49.1354 +           (dev_zero_fd = open("/dev/zero", O_RDWR), \
 49.1355 +            mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \
 49.1356 +            mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0))
 49.1357 +#endif /* MAP_ANONYMOUS */
 49.1358 +
 49.1359 +#define DIRECT_MMAP(s)       CALL_MMAP(s)
 49.1360 +#else /* WIN32 */
 49.1361 +
 49.1362 +/* Win32 MMAP via VirtualAlloc */
 49.1363 +static void* win32mmap(size_t size) {
 49.1364 +  void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
 49.1365 +  return (ptr != 0)? ptr: MFAIL;
 49.1366 +}
 49.1367 +
 49.1368 +/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */
 49.1369 +static void* win32direct_mmap(size_t size) {
 49.1370 +  void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN,
 49.1371 +                           PAGE_READWRITE);
 49.1372 +  return (ptr != 0)? ptr: MFAIL;
 49.1373 +}
 49.1374 +
 49.1375 +/* This function supports releasing coalesed segments */
 49.1376 +static int win32munmap(void* ptr, size_t size) {
 49.1377 +  MEMORY_BASIC_INFORMATION minfo;
 49.1378 +  char* cptr = ptr;
 49.1379 +  while (size) {
 49.1380 +    if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0)
 49.1381 +      return -1;
 49.1382 +    if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr ||
 49.1383 +        minfo.State != MEM_COMMIT || minfo.RegionSize > size)
 49.1384 +      return -1;
 49.1385 +    if (VirtualFree(cptr, 0, MEM_RELEASE) == 0)
 49.1386 +      return -1;
 49.1387 +    cptr += minfo.RegionSize;
 49.1388 +    size -= minfo.RegionSize;
 49.1389 +  }
 49.1390 +  return 0;
 49.1391 +}
 49.1392 +
 49.1393 +#define CALL_MMAP(s)         win32mmap(s)
 49.1394 +#define CALL_MUNMAP(a, s)    win32munmap((a), (s))
 49.1395 +#define DIRECT_MMAP(s)       win32direct_mmap(s)
 49.1396 +#endif /* WIN32 */
 49.1397 +#endif /* HAVE_MMAP */
 49.1398 +
 49.1399 +#if HAVE_MMAP && HAVE_MREMAP
 49.1400 +#define CALL_MREMAP(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv))
 49.1401 +#else  /* HAVE_MMAP && HAVE_MREMAP */
 49.1402 +#define CALL_MREMAP(addr, osz, nsz, mv) MFAIL
 49.1403 +#endif /* HAVE_MMAP && HAVE_MREMAP */
 49.1404 +
 49.1405 +#if HAVE_MORECORE
 49.1406 +#define CALL_MORECORE(S)     MORECORE(S)
 49.1407 +#else  /* HAVE_MORECORE */
 49.1408 +#define CALL_MORECORE(S)     MFAIL
 49.1409 +#endif /* HAVE_MORECORE */
 49.1410 +
 49.1411 +/* mstate bit set if continguous morecore disabled or failed */
 49.1412 +#define USE_NONCONTIGUOUS_BIT (4U)
 49.1413 +
 49.1414 +/* segment bit set in create_mspace_with_base */
 49.1415 +#define EXTERN_BIT            (8U)
 49.1416 +
 49.1417 +
 49.1418 +/* --------------------------- Lock preliminaries ------------------------ */
 49.1419 +
 49.1420 +#if USE_LOCKS
 49.1421 +
 49.1422 +/*
 49.1423 +  When locks are defined, there are up to two global locks:
 49.1424 +
 49.1425 +  * If HAVE_MORECORE, morecore_mutex protects sequences of calls to
 49.1426 +    MORECORE.  In many cases sys_alloc requires two calls, that should
 49.1427 +    not be interleaved with calls by other threads.  This does not
 49.1428 +    protect against direct calls to MORECORE by other threads not
 49.1429 +    using this lock, so there is still code to cope the best we can on
 49.1430 +    interference.
 49.1431 +
 49.1432 +  * magic_init_mutex ensures that mparams.magic and other
 49.1433 +    unique mparams values are initialized only once.
 49.1434 +*/
 49.1435 +
 49.1436 +#ifndef WIN32
 49.1437 +/* By default use posix locks */
 49.1438 +#include <pthread.h>
 49.1439 +#define MLOCK_T pthread_mutex_t
 49.1440 +#define INITIAL_LOCK(l)      pthread_mutex_init(l, NULL)
 49.1441 +#define ACQUIRE_LOCK(l)      pthread_mutex_lock(l)
 49.1442 +#define RELEASE_LOCK(l)      pthread_mutex_unlock(l)
 49.1443 +
 49.1444 +#if HAVE_MORECORE
 49.1445 +static MLOCK_T morecore_mutex = PTHREAD_MUTEX_INITIALIZER;
 49.1446 +#endif /* HAVE_MORECORE */
 49.1447 +
 49.1448 +static MLOCK_T magic_init_mutex = PTHREAD_MUTEX_INITIALIZER;
 49.1449 +
 49.1450 +#else /* WIN32 */
 49.1451 +/*
 49.1452 +   Because lock-protected regions have bounded times, and there
 49.1453 +   are no recursive lock calls, we can use simple spinlocks.
 49.1454 +*/
 49.1455 +
 49.1456 +#define MLOCK_T long
 49.1457 +static int win32_acquire_lock (MLOCK_T *sl) {
 49.1458 +  for (;;) {
 49.1459 +#ifdef InterlockedCompareExchangePointer
 49.1460 +    if (!InterlockedCompareExchange(sl, 1, 0))
 49.1461 +      return 0;
 49.1462 +#else  /* Use older void* version */
 49.1463 +    if (!InterlockedCompareExchange((void**)sl, (void*)1, (void*)0))
 49.1464 +      return 0;
 49.1465 +#endif /* InterlockedCompareExchangePointer */
 49.1466 +    Sleep (0);
 49.1467 +  }
 49.1468 +}
 49.1469 +
 49.1470 +static void win32_release_lock (MLOCK_T *sl) {
 49.1471 +  InterlockedExchange (sl, 0);
 49.1472 +}
 49.1473 +
 49.1474 +#define INITIAL_LOCK(l)      *(l)=0
 49.1475 +#define ACQUIRE_LOCK(l)      win32_acquire_lock(l)
 49.1476 +#define RELEASE_LOCK(l)      win32_release_lock(l)
 49.1477 +#if HAVE_MORECORE
 49.1478 +static MLOCK_T morecore_mutex;
 49.1479 +#endif /* HAVE_MORECORE */
 49.1480 +static MLOCK_T magic_init_mutex;
 49.1481 +#endif /* WIN32 */
 49.1482 +
 49.1483 +#define USE_LOCK_BIT               (2U)
 49.1484 +#else  /* USE_LOCKS */
 49.1485 +#define USE_LOCK_BIT               (0U)
 49.1486 +#define INITIAL_LOCK(l)
 49.1487 +#endif /* USE_LOCKS */
 49.1488 +
 49.1489 +#if USE_LOCKS && HAVE_MORECORE
 49.1490 +#define ACQUIRE_MORECORE_LOCK()    ACQUIRE_LOCK(&morecore_mutex);
 49.1491 +#define RELEASE_MORECORE_LOCK()    RELEASE_LOCK(&morecore_mutex);
 49.1492 +#else /* USE_LOCKS && HAVE_MORECORE */
 49.1493 +#define ACQUIRE_MORECORE_LOCK()
 49.1494 +#define RELEASE_MORECORE_LOCK()
 49.1495 +#endif /* USE_LOCKS && HAVE_MORECORE */
 49.1496 +
 49.1497 +#if USE_LOCKS
 49.1498 +#define ACQUIRE_MAGIC_INIT_LOCK()  ACQUIRE_LOCK(&magic_init_mutex);
 49.1499 +#define RELEASE_MAGIC_INIT_LOCK()  RELEASE_LOCK(&magic_init_mutex);
 49.1500 +#else  /* USE_LOCKS */
 49.1501 +#define ACQUIRE_MAGIC_INIT_LOCK()
 49.1502 +#define RELEASE_MAGIC_INIT_LOCK()
 49.1503 +#endif /* USE_LOCKS */
 49.1504 +
 49.1505 +
 49.1506 +/* -----------------------  Chunk representations ------------------------ */
 49.1507 +
 49.1508 +/*
 49.1509 +  (The following includes lightly edited explanations by Colin Plumb.)
 49.1510 +
 49.1511 +  The malloc_chunk declaration below is misleading (but accurate and
 49.1512 +  necessary).  It declares a "view" into memory allowing access to
 49.1513 +  necessary fields at known offsets from a given base.
 49.1514 +
 49.1515 +  Chunks of memory are maintained using a `boundary tag' method as
 49.1516 +  originally described by Knuth.  (See the paper by Paul Wilson
 49.1517 +  ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such
 49.1518 +  techniques.)  Sizes of free chunks are stored both in the front of
 49.1519 +  each chunk and at the end.  This makes consolidating fragmented
 49.1520 +  chunks into bigger chunks fast.  The head fields also hold bits
 49.1521 +  representing whether chunks are free or in use.
 49.1522 +
 49.1523 +  Here are some pictures to make it clearer.  They are "exploded" to
 49.1524 +  show that the state of a chunk can be thought of as extending from
 49.1525 +  the high 31 bits of the head field of its header through the
 49.1526 +  prev_foot and PINUSE_BIT bit of the following chunk header.
 49.1527 +
 49.1528 +  A chunk that's in use looks like:
 49.1529 +
 49.1530 +   chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1531 +           | Size of previous chunk (if P = 1)                             |
 49.1532 +           +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1533 +         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
 49.1534 +         | Size of this chunk                                         1| +-+
 49.1535 +   mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1536 +         |                                                               |
 49.1537 +         +-                                                             -+
 49.1538 +         |                                                               |
 49.1539 +         +-                                                             -+
 49.1540 +         |                                                               :
 49.1541 +         +-      size - sizeof(size_t) available payload bytes          -+
 49.1542 +         :                                                               |
 49.1543 + chunk-> +-                                                             -+
 49.1544 +         |                                                               |
 49.1545 +         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1546 +       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1|
 49.1547 +       | Size of next chunk (may or may not be in use)               | +-+
 49.1548 + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1549 +
 49.1550 +    And if it's free, it looks like this:
 49.1551 +
 49.1552 +   chunk-> +-                                                             -+
 49.1553 +           | User payload (must be in use, or we would have merged!)       |
 49.1554 +           +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1555 +         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
 49.1556 +         | Size of this chunk                                         0| +-+
 49.1557 +   mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1558 +         | Next pointer                                                  |
 49.1559 +         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1560 +         | Prev pointer                                                  |
 49.1561 +         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1562 +         |                                                               :
 49.1563 +         +-      size - sizeof(struct chunk) unused bytes               -+
 49.1564 +         :                                                               |
 49.1565 + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1566 +         | Size of this chunk                                            |
 49.1567 +         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1568 +       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|
 49.1569 +       | Size of next chunk (must be in use, or we would have merged)| +-+
 49.1570 + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1571 +       |                                                               :
 49.1572 +       +- User payload                                                -+
 49.1573 +       :                                                               |
 49.1574 +       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1575 +                                                                     |0|
 49.1576 +                                                                     +-+
 49.1577 +  Note that since we always merge adjacent free chunks, the chunks
 49.1578 +  adjacent to a free chunk must be in use.
 49.1579 +
 49.1580 +  Given a pointer to a chunk (which can be derived trivially from the
 49.1581 +  payload pointer) we can, in O(1) time, find out whether the adjacent
 49.1582 +  chunks are free, and if so, unlink them from the lists that they
 49.1583 +  are on and merge them with the current chunk.
 49.1584 +
 49.1585 +  Chunks always begin on even word boundaries, so the mem portion
 49.1586 +  (which is returned to the user) is also on an even word boundary, and
 49.1587 +  thus at least double-word aligned.
 49.1588 +
 49.1589 +  The P (PINUSE_BIT) bit, stored in the unused low-order bit of the
 49.1590 +  chunk size (which is always a multiple of two words), is an in-use
 49.1591 +  bit for the *previous* chunk.  If that bit is *clear*, then the
 49.1592 +  word before the current chunk size contains the previous chunk
 49.1593 +  size, and can be used to find the front of the previous chunk.
 49.1594 +  The very first chunk allocated always has this bit set, preventing
 49.1595 +  access to non-existent (or non-owned) memory. If pinuse is set for
 49.1596 +  any given chunk, then you CANNOT determine the size of the
 49.1597 +  previous chunk, and might even get a memory addressing fault when
 49.1598 +  trying to do so.
 49.1599 +
 49.1600 +  The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of
 49.1601 +  the chunk size redundantly records whether the current chunk is
 49.1602 +  inuse. This redundancy enables usage checks within free and realloc,
 49.1603 +  and reduces indirection when freeing and consolidating chunks.
 49.1604 +
 49.1605 +  Each freshly allocated chunk must have both cinuse and pinuse set.
 49.1606 +  That is, each allocated chunk borders either a previously allocated
 49.1607 +  and still in-use chunk, or the base of its memory arena. This is
 49.1608 +  ensured by making all allocations from the the `lowest' part of any
 49.1609 +  found chunk.  Further, no free chunk physically borders another one,
 49.1610 +  so each free chunk is known to be preceded and followed by either
 49.1611 +  inuse chunks or the ends of memory.
 49.1612 +
 49.1613 +  Note that the `foot' of the current chunk is actually represented
 49.1614 +  as the prev_foot of the NEXT chunk. This makes it easier to
 49.1615 +  deal with alignments etc but can be very confusing when trying
 49.1616 +  to extend or adapt this code.
 49.1617 +
 49.1618 +  The exceptions to all this are
 49.1619 +
 49.1620 +     1. The special chunk `top' is the top-most available chunk (i.e.,
 49.1621 +        the one bordering the end of available memory). It is treated
 49.1622 +        specially.  Top is never included in any bin, is used only if
 49.1623 +        no other chunk is available, and is released back to the
 49.1624 +        system if it is very large (see M_TRIM_THRESHOLD).  In effect,
 49.1625 +        the top chunk is treated as larger (and thus less well
 49.1626 +        fitting) than any other available chunk.  The top chunk
 49.1627 +        doesn't update its trailing size field since there is no next
 49.1628 +        contiguous chunk that would have to index off it. However,
 49.1629 +        space is still allocated for it (TOP_FOOT_SIZE) to enable
 49.1630 +        separation or merging when space is extended.
 49.1631 +
 49.1632 +     3. Chunks allocated via mmap, which have the lowest-order bit
 49.1633 +        (IS_MMAPPED_BIT) set in their prev_foot fields, and do not set
 49.1634 +        PINUSE_BIT in their head fields.  Because they are allocated
 49.1635 +        one-by-one, each must carry its own prev_foot field, which is
 49.1636 +        also used to hold the offset this chunk has within its mmapped
 49.1637 +        region, which is needed to preserve alignment. Each mmapped
 49.1638 +        chunk is trailed by the first two fields of a fake next-chunk
 49.1639 +        for sake of usage checks.
 49.1640 +
 49.1641 +*/
 49.1642 +
 49.1643 +struct malloc_chunk {
 49.1644 +  size_t               prev_foot;  /* Size of previous chunk (if free).  */
 49.1645 +  size_t               head;       /* Size and inuse bits. */
 49.1646 +  struct malloc_chunk* fd;         /* double links -- used only if free. */
 49.1647 +  struct malloc_chunk* bk;
 49.1648 +};
 49.1649 +
 49.1650 +typedef struct malloc_chunk  mchunk;
 49.1651 +typedef struct malloc_chunk* mchunkptr;
 49.1652 +typedef struct malloc_chunk* sbinptr;  /* The type of bins of chunks */
 49.1653 +typedef unsigned int bindex_t;         /* Described below */
 49.1654 +typedef unsigned int binmap_t;         /* Described below */
 49.1655 +typedef unsigned int flag_t;           /* The type of various bit flag sets */
 49.1656 +
 49.1657 +/* ------------------- Chunks sizes and alignments ----------------------- */
 49.1658 +
 49.1659 +#define MCHUNK_SIZE         (sizeof(mchunk))
 49.1660 +
 49.1661 +#if FOOTERS
 49.1662 +#define CHUNK_OVERHEAD      (TWO_SIZE_T_SIZES)
 49.1663 +#else /* FOOTERS */
 49.1664 +#define CHUNK_OVERHEAD      (SIZE_T_SIZE)
 49.1665 +#endif /* FOOTERS */
 49.1666 +
 49.1667 +/* MMapped chunks need a second word of overhead ... */
 49.1668 +#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
 49.1669 +/* ... and additional padding for fake next-chunk at foot */
 49.1670 +#define MMAP_FOOT_PAD       (FOUR_SIZE_T_SIZES)
 49.1671 +
 49.1672 +/* The smallest size we can malloc is an aligned minimal chunk */
 49.1673 +#define MIN_CHUNK_SIZE\
 49.1674 +  ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
 49.1675 +
 49.1676 +/* conversion from malloc headers to user pointers, and back */
 49.1677 +#define chunk2mem(p)        ((void*)((char*)(p)       + TWO_SIZE_T_SIZES))
 49.1678 +#define mem2chunk(mem)      ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES))
 49.1679 +/* chunk associated with aligned address A */
 49.1680 +#define align_as_chunk(A)   (mchunkptr)((A) + align_offset(chunk2mem(A)))
 49.1681 +
 49.1682 +/* Bounds on request (not chunk) sizes. */
 49.1683 +#define MAX_REQUEST         ((-MIN_CHUNK_SIZE) << 2)
 49.1684 +#define MIN_REQUEST         (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE)
 49.1685 +
 49.1686 +/* pad request bytes into a usable size */
 49.1687 +#define pad_request(req) \
 49.1688 +   (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
 49.1689 +
 49.1690 +/* pad request, checking for minimum (but not maximum) */
 49.1691 +#define request2size(req) \
 49.1692 +  (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req))
 49.1693 +
 49.1694 +
 49.1695 +/* ------------------ Operations on head and foot fields ----------------- */
 49.1696 +
 49.1697 +/*
 49.1698 +  The head field of a chunk is or'ed with PINUSE_BIT when previous
 49.1699 +  adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in
 49.1700 +  use. If the chunk was obtained with mmap, the prev_foot field has
 49.1701 +  IS_MMAPPED_BIT set, otherwise holding the offset of the base of the
 49.1702 +  mmapped region to the base of the chunk.
 49.1703 +*/
 49.1704 +
 49.1705 +#define PINUSE_BIT          (SIZE_T_ONE)
 49.1706 +#define CINUSE_BIT          (SIZE_T_TWO)
 49.1707 +#define INUSE_BITS          (PINUSE_BIT|CINUSE_BIT)
 49.1708 +
 49.1709 +/* Head value for fenceposts */
 49.1710 +#define FENCEPOST_HEAD      (INUSE_BITS|SIZE_T_SIZE)
 49.1711 +
 49.1712 +/* extraction of fields from head words */
 49.1713 +#define cinuse(p)           ((p)->head & CINUSE_BIT)
 49.1714 +#define pinuse(p)           ((p)->head & PINUSE_BIT)
 49.1715 +#define chunksize(p)        ((p)->head & ~(INUSE_BITS))
 49.1716 +
 49.1717 +#define clear_pinuse(p)     ((p)->head &= ~PINUSE_BIT)
 49.1718 +#define clear_cinuse(p)     ((p)->head &= ~CINUSE_BIT)
 49.1719 +
 49.1720 +/* Treat space at ptr +/- offset as a chunk */
 49.1721 +#define chunk_plus_offset(p, s)  ((mchunkptr)(((char*)(p)) + (s)))
 49.1722 +#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s)))
 49.1723 +
 49.1724 +/* Ptr to next or previous physical malloc_chunk. */
 49.1725 +#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~INUSE_BITS)))
 49.1726 +#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) ))
 49.1727 +
 49.1728 +/* extract next chunk's pinuse bit */
 49.1729 +#define next_pinuse(p)  ((next_chunk(p)->head) & PINUSE_BIT)
 49.1730 +
 49.1731 +/* Get/set size at footer */
 49.1732 +#define get_foot(p, s)  (((mchunkptr)((char*)(p) + (s)))->prev_foot)
 49.1733 +#define set_foot(p, s)  (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s))
 49.1734 +
 49.1735 +/* Set size, pinuse bit, and foot */
 49.1736 +#define set_size_and_pinuse_of_free_chunk(p, s)\
 49.1737 +  ((p)->head = (s|PINUSE_BIT), set_foot(p, s))
 49.1738 +
 49.1739 +/* Set size, pinuse bit, foot, and clear next pinuse */
 49.1740 +#define set_free_with_pinuse(p, s, n)\
 49.1741 +  (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s))
 49.1742 +
 49.1743 +#define is_mmapped(p)\
 49.1744 +  (!((p)->head & PINUSE_BIT) && ((p)->prev_foot & IS_MMAPPED_BIT))
 49.1745 +
 49.1746 +/* Get the internal overhead associated with chunk p */
 49.1747 +#define overhead_for(p)\
 49.1748 + (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD)
 49.1749 +
 49.1750 +/* Return true if malloced space is not necessarily cleared */
 49.1751 +#if MMAP_CLEARS
 49.1752 +#define calloc_must_clear(p) (!is_mmapped(p))
 49.1753 +#else /* MMAP_CLEARS */
 49.1754 +#define calloc_must_clear(p) (1)
 49.1755 +#endif /* MMAP_CLEARS */
 49.1756 +
 49.1757 +/* ---------------------- Overlaid data structures ----------------------- */
 49.1758 +
 49.1759 +/*
 49.1760 +  When chunks are not in use, they are treated as nodes of either
 49.1761 +  lists or trees.
 49.1762 +
 49.1763 +  "Small"  chunks are stored in circular doubly-linked lists, and look
 49.1764 +  like this:
 49.1765 +
 49.1766 +    chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1767 +            |             Size of previous chunk                            |
 49.1768 +            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1769 +    `head:' |             Size of chunk, in bytes                         |P|
 49.1770 +      mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1771 +            |             Forward pointer to next chunk in list             |
 49.1772 +            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1773 +            |             Back pointer to previous chunk in list            |
 49.1774 +            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1775 +            |             Unused space (may be 0 bytes long)                .
 49.1776 +            .                                                               .
 49.1777 +            .                                                               |
 49.1778 +nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1779 +    `foot:' |             Size of chunk, in bytes                           |
 49.1780 +            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1781 +
 49.1782 +  Larger chunks are kept in a form of bitwise digital trees (aka
 49.1783 +  tries) keyed on chunksizes.  Because malloc_tree_chunks are only for
 49.1784 +  free chunks greater than 256 bytes, their size doesn't impose any
 49.1785 +  constraints on user chunk sizes.  Each node looks like:
 49.1786 +
 49.1787 +    chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1788 +            |             Size of previous chunk                            |
 49.1789 +            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1790 +    `head:' |             Size of chunk, in bytes                         |P|
 49.1791 +      mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1792 +            |             Forward pointer to next chunk of same size        |
 49.1793 +            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1794 +            |             Back pointer to previous chunk of same size       |
 49.1795 +            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1796 +            |             Pointer to left child (child[0])                  |
 49.1797 +            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1798 +            |             Pointer to right child (child[1])                 |
 49.1799 +            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1800 +            |             Pointer to parent                                 |
 49.1801 +            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1802 +            |             bin index of this chunk                           |
 49.1803 +            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1804 +            |             Unused space                                      .
 49.1805 +            .                                                               |
 49.1806 +nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1807 +    `foot:' |             Size of chunk, in bytes                           |
 49.1808 +            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 49.1809 +
 49.1810 +  Each tree holding treenodes is a tree of unique chunk sizes.  Chunks
 49.1811 +  of the same size are arranged in a circularly-linked list, with only
 49.1812 +  the oldest chunk (the next to be used, in our FIFO ordering)
 49.1813 +  actually in the tree.  (Tree members are distinguished by a non-null
 49.1814 +  parent pointer.)  If a chunk with the same size an an existing node
 49.1815 +  is inserted, it is linked off the existing node using pointers that
 49.1816 +  work in the same way as fd/bk pointers of small chunks.
 49.1817 +
 49.1818 +  Each tree contains a power of 2 sized range of chunk sizes (the
 49.1819 +  smallest is 0x100 <= x < 0x180), which is is divided in half at each
 49.1820 +  tree level, with the chunks in the smaller half of the range (0x100
 49.1821 +  <= x < 0x140 for the top nose) in the left subtree and the larger
 49.1822 +  half (0x140 <= x < 0x180) in the right subtree.  This is, of course,
 49.1823 +  done by inspecting individual bits.
 49.1824 +
 49.1825 +  Using these rules, each node's left subtree contains all smaller
 49.1826 +  sizes than its right subtree.  However, the node at the root of each
 49.1827 +  subtree has no particular ordering relationship to either.  (The
 49.1828 +  dividing line between the subtree sizes is based on trie relation.)
 49.1829 +  If we remove the last chunk of a given size from the interior of the
 49.1830 +  tree, we need to replace it with a leaf node.  The tree ordering
 49.1831 +  rules permit a node to be replaced by any leaf below it.
 49.1832 +
 49.1833 +  The smallest chunk in a tree (a common operation in a best-fit
 49.1834 +  allocator) can be found by walking a path to the leftmost leaf in
 49.1835 +  the tree.  Unlike a usual binary tree, where we follow left child
 49.1836 +  pointers until we reach a null, here we follow the right child
 49.1837 +  pointer any time the left one is null, until we reach a leaf with
 49.1838 +  both child pointers null. The smallest chunk in the tree will be
 49.1839 +  somewhere along that path.
 49.1840 +
 49.1841 +  The worst case number of steps to add, find, or remove a node is
 49.1842 +  bounded by the number of bits differentiating chunks within
 49.1843 +  bins. Under current bin calculations, this ranges from 6 up to 21
 49.1844 +  (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case
 49.1845 +  is of course much better.
 49.1846 +*/
 49.1847 +
 49.1848 +struct malloc_tree_chunk {
 49.1849 +  /* The first four fields must be compatible with malloc_chunk */
 49.1850 +  size_t                    prev_foot;
 49.1851 +  size_t                    head;
 49.1852 +  struct malloc_tree_chunk* fd;
 49.1853 +  struct malloc_tree_chunk* bk;
 49.1854 +
 49.1855 +  struct malloc_tree_chunk* child[2];
 49.1856 +  struct malloc_tree_chunk* parent;
 49.1857 +  bindex_t                  index;
 49.1858 +};
 49.1859 +
 49.1860 +typedef struct malloc_tree_chunk  tchunk;
 49.1861 +typedef struct malloc_tree_chunk* tchunkptr;
 49.1862 +typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */
 49.1863 +
 49.1864 +/* A little helper macro for trees */
 49.1865 +#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1])
 49.1866 +
 49.1867 +/* ----------------------------- Segments -------------------------------- */
 49.1868 +
 49.1869 +/*
 49.1870 +  Each malloc space may include non-contiguous segments, held in a
 49.1871 +  list headed by an embedded malloc_segment record representing the
 49.1872 +  top-most space. Segments also include flags holding properties of
 49.1873 +  the space. Large chunks that are directly allocated by mmap are not
 49.1874 +  included in this list. They are instead independently created and
 49.1875 +  destroyed without otherwise keeping track of them.
 49.1876 +
 49.1877 +  Segment management mainly comes into play for spaces allocated by
 49.1878 +  MMAP.  Any call to MMAP might or might not return memory that is
 49.1879 +  adjacent to an existing segment.  MORECORE normally contiguously
 49.1880 +  extends the current space, so this space is almost always adjacent,
 49.1881 +  which is simpler and faster to deal with. (This is why MORECORE is
 49.1882 +  used preferentially to MMAP when both are available -- see
 49.1883 +  sys_alloc.)  When allocating using MMAP, we don't use any of the
 49.1884 +  hinting mechanisms (inconsistently) supported in various
 49.1885 +  implementations of unix mmap, or distinguish reserving from
 49.1886 +  committing memory. Instead, we just ask for space, and exploit
 49.1887 +  contiguity when we get it.  It is probably possible to do
 49.1888 +  better than this on some systems, but no general scheme seems
 49.1889 +  to be significantly better.
 49.1890 +
 49.1891 +  Management entails a simpler variant of the consolidation scheme
 49.1892 +  used for chunks to reduce fragmentation -- new adjacent memory is
 49.1893 +  normally prepended or appended to an existing segment. However,
 49.1894 +  there are limitations compared to chunk consolidation that mostly
 49.1895 +  reflect the fact that segment processing is relatively infrequent
 49.1896 +  (occurring only when getting memory from system) and that we
 49.1897 +  don't expect to have huge numbers of segments:
 49.1898 +
 49.1899 +  * Segments are not indexed, so traversal requires linear scans.  (It
 49.1900 +    would be possible to index these, but is not worth the extra
 49.1901 +    overhead and complexity for most programs on most platforms.)
 49.1902 +  * New segments are only appended to old ones when holding top-most
 49.1903 +    memory; if they cannot be prepended to others, they are held in
 49.1904 +    different segments.
 49.1905 +
 49.1906 +  Except for the top-most segment of an mstate, each segment record
 49.1907 +  is kept at the tail of its segment. Segments are added by pushing
 49.1908 +  segment records onto the list headed by &mstate.seg for the
 49.1909 +  containing mstate.
 49.1910 +
 49.1911 +  Segment flags control allocation/merge/deallocation policies:
 49.1912 +  * If EXTERN_BIT set, then we did not allocate this segment,
 49.1913 +    and so should not try to deallocate or merge with others.
 49.1914 +    (This currently holds only for the initial segment passed
 49.1915 +    into create_mspace_with_base.)
 49.1916 +  * If IS_MMAPPED_BIT set, the segment may be merged with
 49.1917 +    other surrounding mmapped segments and trimmed/de-allocated
 49.1918 +    using munmap.
 49.1919 +  * If neither bit is set, then the segment was obtained using
 49.1920 +    MORECORE so can be merged with surrounding MORECORE'd segments
 49.1921 +    and deallocated/trimmed using MORECORE with negative arguments.
 49.1922 +*/
 49.1923 +
 49.1924 +struct malloc_segment {
 49.1925 +  char*        base;             /* base address */
 49.1926 +  size_t       size;             /* allocated size */
 49.1927 +  struct malloc_segment* next;   /* ptr to next segment */
 49.1928 +  flag_t       sflags;           /* mmap and extern flag */
 49.1929 +};
 49.1930 +
 49.1931 +#define is_mmapped_segment(S)  ((S)->sflags & IS_MMAPPED_BIT)
 49.1932 +#define is_extern_segment(S)   ((S)->sflags & EXTERN_BIT)
 49.1933 +
 49.1934 +typedef struct malloc_segment  msegment;
 49.1935 +typedef struct malloc_segment* msegmentptr;
 49.1936 +
 49.1937 +/* ---------------------------- malloc_state ----------------------------- */
 49.1938 +
 49.1939 +/*
 49.1940 +   A malloc_state holds all of the bookkeeping for a space.
 49.1941 +   The main fields are:
 49.1942 +
 49.1943 +  Top
 49.1944 +    The topmost chunk of the currently active segment. Its size is
 49.1945 +    cached in topsize.  The actual size of topmost space is
 49.1946 +    topsize+TOP_FOOT_SIZE, which includes space reserved for adding
 49.1947 +    fenceposts and segment records if necessary when getting more
 49.1948 +    space from the system.  The size at which to autotrim top is
 49.1949 +    cached from mparams in trim_check, except that it is disabled if
 49.1950 +    an autotrim fails.
 49.1951 +
 49.1952 +  Designated victim (dv)
 49.1953 +    This is the preferred chunk for servicing small requests that
 49.1954 +    don't have exact fits.  It is normally the chunk split off most
 49.1955 +    recently to service another small request.  Its size is cached in
 49.1956 +    dvsize. The link fields of this chunk are not maintained since it
 49.1957 +    is not kept in a bin.
 49.1958 +
 49.1959 +  SmallBins
 49.1960 +    An array of bin headers for free chunks.  These bins hold chunks
 49.1961 +    with sizes less than MIN_LARGE_SIZE bytes. Each bin contains
 49.1962 +    chunks of all the same size, spaced 8 bytes apart.  To simplify
 49.1963 +    use in double-linked lists, each bin header acts as a malloc_chunk
 49.1964 +    pointing to the real first node, if it exists (else pointing to
 49.1965 +    itself).  This avoids special-casing for headers.  But to avoid
 49.1966 +    waste, we allocate only the fd/bk pointers of bins, and then use
 49.1967 +    repositioning tricks to treat these as the fields of a chunk.
 49.1968 +
 49.1969 +  TreeBins
 49.1970 +    Treebins are pointers to the roots of trees holding a range of
 49.1971 +    sizes. There are 2 equally spaced treebins for each power of two
 49.1972 +    from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything
 49.1973 +    larger.
 49.1974 +
 49.1975 +  Bin maps
 49.1976 +    There is one bit map for small bins ("smallmap") and one for
 49.1977 +    treebins ("treemap).  Each bin sets its bit when non-empty, and
 49.1978 +    clears the bit when empty.  Bit operations are then used to avoid
 49.1979 +    bin-by-bin searching -- nearly all "search" is done without ever
 49.1980 +    looking at bins that won't be selected.  The bit maps
 49.1981 +    conservatively use 32 bits per map word, even if on 64bit system.
 49.1982 +    For a good description of some of the bit-based techniques used
 49.1983 +    here, see Henry S. Warren Jr's book "Hacker's Delight" (and
 49.1984 +    supplement at http://hackersdelight.org/). Many of these are
 49.1985 +    intended to reduce the branchiness of paths through malloc etc, as
 49.1986 +    well as to reduce the number of memory locations read or written.
 49.1987 +
 49.1988 +  Segments
 49.1989 +    A list of segments headed by an embedded malloc_segment record
 49.1990 +    representing the initial space.
 49.1991 +
 49.1992 +  Address check support
 49.1993 +    The least_addr field is the least address ever obtained from
 49.1994 +    MORECORE or MMAP. Attempted frees and reallocs of any address less
 49.1995 +    than this are trapped (unless INSECURE is defined).
 49.1996 +
 49.1997 +  Magic tag
 49.1998 +    A cross-check field that should always hold same value as mparams.magic.
 49.1999 +
 49.2000 +  Flags
 49.2001 +    Bits recording whether to use MMAP, locks, or contiguous MORECORE
 49.2002 +
 49.2003 +  Statistics
 49.2004 +    Each space keeps track of current and maximum system memory
 49.2005 +    obtained via MORECORE or MMAP.
 49.2006 +
 49.2007 +  Locking
 49.2008 +    If USE_LOCKS is defined, the "mutex" lock is acquired and released
 49.2009 +    around every public call using this mspace.
 49.2010 +*/
 49.2011 +
 49.2012 +/* Bin types, widths and sizes */
 49.2013 +#define NSMALLBINS        (32U)
 49.2014 +#define NTREEBINS         (32U)
 49.2015 +#define SMALLBIN_SHIFT    (3U)
 49.2016 +#define SMALLBIN_WIDTH    (SIZE_T_ONE << SMALLBIN_SHIFT)
 49.2017 +#define TREEBIN_SHIFT     (8U)
 49.2018 +#define MIN_LARGE_SIZE    (SIZE_T_ONE << TREEBIN_SHIFT)
 49.2019 +#define MAX_SMALL_SIZE    (MIN_LARGE_SIZE - SIZE_T_ONE)
 49.2020 +#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)
 49.2021 +
 49.2022 +struct malloc_state {
 49.2023 +  binmap_t   smallmap;
 49.2024 +  binmap_t   treemap;
 49.2025 +  size_t     dvsize;
 49.2026 +  size_t     topsize;
 49.2027 +  char*      least_addr;
 49.2028 +  mchunkptr  dv;
 49.2029 +  mchunkptr  top;
 49.2030 +  size_t     trim_check;
 49.2031 +  size_t     magic;
 49.2032 +  mchunkptr  smallbins[(NSMALLBINS+1)*2];
 49.2033 +  tbinptr    treebins[NTREEBINS];
 49.2034 +  size_t     footprint;
 49.2035 +  size_t     max_footprint;
 49.2036 +  flag_t     mflags;
 49.2037 +#if USE_LOCKS
 49.2038 +  MLOCK_T    mutex;     /* locate lock among fields that rarely change */
 49.2039 +#endif /* USE_LOCKS */
 49.2040 +  msegment   seg;
 49.2041 +};
 49.2042 +
 49.2043 +typedef struct malloc_state*    mstate;
 49.2044 +
 49.2045 +/* ------------- Global malloc_state and malloc_params ------------------- */
 49.2046 +
 49.2047 +/*
 49.2048 +  malloc_params holds global properties, including those that can be
 49.2049 +  dynamically set using mallopt. There is a single instance, mparams,
 49.2050 +  initialized in init_mparams.
 49.2051 +*/
 49.2052 +
 49.2053 +struct malloc_params {
 49.2054 +  size_t magic;
 49.2055 +  size_t page_size;
 49.2056 +  size_t granularity;
 49.2057 +  size_t mmap_threshold;
 49.2058 +  size_t trim_threshold;
 49.2059 +  flag_t default_mflags;
 49.2060 +};
 49.2061 +
 49.2062 +static struct malloc_params mparams;
 49.2063 +
 49.2064 +/* The global malloc_state used for all non-"mspace" calls */
 49.2065 +static struct malloc_state _gm_;
 49.2066 +#define gm                 (&_gm_)
 49.2067 +#define is_global(M)       ((M) == &_gm_)
 49.2068 +#define is_initialized(M)  ((M)->top != 0)
 49.2069 +
 49.2070 +/* -------------------------- system alloc setup ------------------------- */
 49.2071 +
 49.2072 +/* Operations on mflags */
 49.2073 +
 49.2074 +#define use_lock(M)           ((M)->mflags &   USE_LOCK_BIT)
 49.2075 +#define enable_lock(M)        ((M)->mflags |=  USE_LOCK_BIT)
 49.2076 +#define disable_lock(M)       ((M)->mflags &= ~USE_LOCK_BIT)
 49.2077 +
 49.2078 +#define use_mmap(M)           ((M)->mflags &   USE_MMAP_BIT)
 49.2079 +#define enable_mmap(M)        ((M)->mflags |=  USE_MMAP_BIT)
 49.2080 +#define disable_mmap(M)       ((M)->mflags &= ~USE_MMAP_BIT)
 49.2081 +
 49.2082 +#define use_noncontiguous(M)  ((M)->mflags &   USE_NONCONTIGUOUS_BIT)
 49.2083 +#define disable_contiguous(M) ((M)->mflags |=  USE_NONCONTIGUOUS_BIT)
 49.2084 +
 49.2085 +#define set_lock(M,L)\
 49.2086 + ((M)->mflags = (L)?\
 49.2087 +  ((M)->mflags | USE_LOCK_BIT) :\
 49.2088 +  ((M)->mflags & ~USE_LOCK_BIT))
 49.2089 +
 49.2090 +/* page-align a size */
 49.2091 +#define page_align(S)\
 49.2092 + (((S) + (mparams.page_size)) & ~(mparams.page_size - SIZE_T_ONE))
 49.2093 +
 49.2094 +/* granularity-align a size */
 49.2095 +#define granularity_align(S)\
 49.2096 +  (((S) + (mparams.granularity)) & ~(mparams.granularity - SIZE_T_ONE))
 49.2097 +
 49.2098 +#define is_page_aligned(S)\
 49.2099 +   (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0)
 49.2100 +#define is_granularity_aligned(S)\
 49.2101 +   (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0)
 49.2102 +
 49.2103 +/*  True if segment S holds address A */
 49.2104 +#define segment_holds(S, A)\
 49.2105 +  ((char*)(A) >= S->base && (char*)(A) < S->base + S->size)
 49.2106 +
 49.2107 +/* Return segment holding given address */
 49.2108 +static msegmentptr segment_holding(mstate m, char* addr) {
 49.2109 +  msegmentptr sp = &m->seg;
 49.2110 +  for (;;) {
 49.2111 +    if (addr >= sp->base && addr < sp->base + sp->size)
 49.2112 +      return sp;
 49.2113 +    if ((sp = sp->next) == 0)
 49.2114 +      return 0;
 49.2115 +  }
 49.2116 +}
 49.2117 +
 49.2118 +/* Return true if segment contains a segment link */
 49.2119 +static int has_segment_link(mstate m, msegmentptr ss) {
 49.2120 +  msegmentptr sp = &m->seg;
 49.2121 +  for (;;) {
 49.2122 +    if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size)
 49.2123 +      return 1;
 49.2124 +    if ((sp = sp->next) == 0)
 49.2125 +      return 0;
 49.2126 +  }
 49.2127 +}
 49.2128 +
 49.2129 +#ifndef MORECORE_CANNOT_TRIM
 49.2130 +#define should_trim(M,s)  ((s) > (M)->trim_check)
 49.2131 +#else  /* MORECORE_CANNOT_TRIM */
 49.2132 +#define should_trim(M,s)  (0)
 49.2133 +#endif /* MORECORE_CANNOT_TRIM */
 49.2134 +
 49.2135 +/*
 49.2136 +  TOP_FOOT_SIZE is padding at the end of a segment, including space
 49.2137 +  that may be needed to place segment records and fenceposts when new
 49.2138 +  noncontiguous segments are added.
 49.2139 +*/
 49.2140 +#define TOP_FOOT_SIZE\
 49.2141 +  (align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE)
 49.2142 +
 49.2143 +
 49.2144 +/* -------------------------------  Hooks -------------------------------- */
 49.2145 +
 49.2146 +/*
 49.2147 +  PREACTION should be defined to return 0 on success, and nonzero on
 49.2148 +  failure. If you are not using locking, you can redefine these to do
 49.2149 +  anything you like.
 49.2150 +*/
 49.2151 +
 49.2152 +#if USE_LOCKS
 49.2153 +
 49.2154 +/* Ensure locks are initialized */
 49.2155 +#define GLOBALLY_INITIALIZE() (mparams.page_size == 0 && init_mparams())
 49.2156 +
 49.2157 +#define PREACTION(M)  ((GLOBALLY_INITIALIZE() || use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0)
 49.2158 +#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); }
 49.2159 +#else /* USE_LOCKS */
 49.2160 +
 49.2161 +#ifndef PREACTION
 49.2162 +#define PREACTION(M) (0)
 49.2163 +#endif  /* PREACTION */
 49.2164 +
 49.2165 +#ifndef POSTACTION
 49.2166 +#define POSTACTION(M)
 49.2167 +#endif  /* POSTACTION */
 49.2168 +
 49.2169 +#endif /* USE_LOCKS */
 49.2170 +
 49.2171 +/*
 49.2172 +  CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses.
 49.2173 +  USAGE_ERROR_ACTION is triggered on detected bad frees and
 49.2174 +  reallocs. The argument p is an address that might have triggered the
 49.2175 +  fault. It is ignored by the two predefined actions, but might be
 49.2176 +  useful in custom actions that try to help diagnose errors.
 49.2177 +*/
 49.2178 +
 49.2179 +#if PROCEED_ON_ERROR
 49.2180 +
 49.2181 +/* A count of the number of corruption errors causing resets */
 49.2182 +int malloc_corruption_error_count;
 49.2183 +
 49.2184 +/* default corruption action */
 49.2185 +static void reset_on_error(mstate m);
 49.2186 +
 49.2187 +#define CORRUPTION_ERROR_ACTION(m)  reset_on_error(m)
 49.2188 +#define USAGE_ERROR_ACTION(m, p)
 49.2189 +
 49.2190 +#else /* PROCEED_ON_ERROR */
 49.2191 +
 49.2192 +#ifndef CORRUPTION_ERROR_ACTION
 49.2193 +#define CORRUPTION_ERROR_ACTION(m) ABORT
 49.2194 +#endif /* CORRUPTION_ERROR_ACTION */
 49.2195 +
 49.2196 +#ifndef USAGE_ERROR_ACTION
 49.2197 +#define USAGE_ERROR_ACTION(m,p) ABORT
 49.2198 +#endif /* USAGE_ERROR_ACTION */
 49.2199 +
 49.2200 +#endif /* PROCEED_ON_ERROR */
 49.2201 +
 49.2202 +/* -------------------------- Debugging setup ---------------------------- */
 49.2203 +
 49.2204 +#if ! DEBUG
 49.2205 +
 49.2206 +#define check_free_chunk(M,P)
 49.2207 +#define check_inuse_chunk(M,P)
 49.2208 +#define check_malloced_chunk(M,P,N)
 49.2209 +#define check_mmapped_chunk(M,P)
 49.2210 +#define check_malloc_state(M)
 49.2211 +#define check_top_chunk(M,P)
 49.2212 +
 49.2213 +#else /* DEBUG */
 49.2214 +#define check_free_chunk(M,P)       do_check_free_chunk(M,P)
 49.2215 +#define check_inuse_chunk(M,P)      do_check_inuse_chunk(M,P)
 49.2216 +#define check_top_chunk(M,P)        do_check_top_chunk(M,P)
 49.2217 +#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N)
 49.2218 +#define check_mmapped_chunk(M,P)    do_check_mmapped_chunk(M,P)
 49.2219 +#define check_malloc_state(M)       do_check_malloc_state(M)
 49.2220 +
 49.2221 +static void   do_check_any_chunk(mstate m, mchunkptr p);
 49.2222 +static void   do_check_top_chunk(mstate m, mchunkptr p);
 49.2223 +static void   do_check_mmapped_chunk(mstate m, mchunkptr p);
 49.2224 +static void   do_check_inuse_chunk(mstate m, mchunkptr p);
 49.2225 +static void   do_check_free_chunk(mstate m, mchunkptr p);
 49.2226 +static void   do_check_malloced_chunk(mstate m, void* mem, size_t s);
 49.2227 +static void   do_check_tree(mstate m, tchunkptr t);
 49.2228 +static void   do_check_treebin(mstate m, bindex_t i);
 49.2229 +static void   do_check_smallbin(mstate m, bindex_t i);
 49.2230 +static void   do_check_malloc_state(mstate m);
 49.2231 +static int    bin_find(mstate m, mchunkptr x);
 49.2232 +static size_t traverse_and_check(mstate m);
 49.2233 +#endif /* DEBUG */
 49.2234 +
 49.2235 +/* ---------------------------- Indexing Bins ---------------------------- */
 49.2236 +
 49.2237 +#define is_small(s)         (((s) >> SMALLBIN_SHIFT) < NSMALLBINS)
 49.2238 +#define small_index(s)      ((s)  >> SMALLBIN_SHIFT)
 49.2239 +#define small_index2size(i) ((i)  << SMALLBIN_SHIFT)
 49.2240 +#define MIN_SMALL_INDEX     (small_index(MIN_CHUNK_SIZE))
 49.2241 +
 49.2242 +/* addressing by index. See above about smallbin repositioning */
 49.2243 +#define smallbin_at(M, i)   ((sbinptr)((char*)&((M)->smallbins[(i)<<1])))
 49.2244 +#define treebin_at(M,i)     (&((M)->treebins[i]))
 49.2245 +
 49.2246 +/* assign tree index for size S to variable I */
 49.2247 +#if defined(__GNUC__) && defined(i386)
 49.2248 +#define compute_tree_index(S, I)\
 49.2249 +{\
 49.2250 +  size_t X = S >> TREEBIN_SHIFT;\
 49.2251 +  if (X == 0)\
 49.2252 +    I = 0;\
 49.2253 +  else if (X > 0xFFFF)\
 49.2254 +    I = NTREEBINS-1;\
 49.2255 +  else {\
 49.2256 +    unsigned int K;\
 49.2257 +    __asm__("bsrl %1,%0\n\t" : "=r" (K) : "rm"  (X));\
 49.2258 +    I =  (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
 49.2259 +  }\
 49.2260 +}
 49.2261 +#else /* GNUC */
 49.2262 +#define compute_tree_index(S, I)\
 49.2263 +{\
 49.2264 +  size_t X = S >> TREEBIN_SHIFT;\
 49.2265 +  if (X == 0)\
 49.2266 +    I = 0;\
 49.2267 +  else if (X > 0xFFFF)\
 49.2268 +    I = NTREEBINS-1;\
 49.2269 +  else {\
 49.2270 +    unsigned int Y = (unsigned int)X;\
 49.2271 +    unsigned int N = ((Y - 0x100) >> 16) & 8;\
 49.2272 +    unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\
 49.2273 +    N += K;\
 49.2274 +    N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\
 49.2275 +    K = 14 - N + ((Y <<= K) >> 15);\
 49.2276 +    I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\
 49.2277 +  }\
 49.2278 +}
 49.2279 +#endif /* GNUC */
 49.2280 +
 49.2281 +/* Bit representing maximum resolved size in a treebin at i */
 49.2282 +#define bit_for_tree_index(i) \
 49.2283 +   (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2)
 49.2284 +
 49.2285 +/* Shift placing maximum resolved bit in a treebin at i as sign bit */
 49.2286 +#define leftshift_for_tree_index(i) \
 49.2287 +   ((i == NTREEBINS-1)? 0 : \
 49.2288 +    ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2)))
 49.2289 +
 49.2290 +/* The size of the smallest chunk held in bin with index i */
 49.2291 +#define minsize_for_tree_index(i) \
 49.2292 +   ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) |  \
 49.2293 +   (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1)))
 49.2294 +
 49.2295 +
 49.2296 +/* ------------------------ Operations on bin maps ----------------------- */
 49.2297 +
 49.2298 +/* bit corresponding to given index */
 49.2299 +#define idx2bit(i)              ((binmap_t)(1) << (i))
 49.2300 +
 49.2301 +/* Mark/Clear bits with given index */
 49.2302 +#define mark_smallmap(M,i)      ((M)->smallmap |=  idx2bit(i))
 49.2303 +#define clear_smallmap(M,i)     ((M)->smallmap &= ~idx2bit(i))
 49.2304 +#define smallmap_is_marked(M,i) ((M)->smallmap &   idx2bit(i))
 49.2305 +
 49.2306 +#define mark_treemap(M,i)       ((M)->treemap  |=  idx2bit(i))
 49.2307 +#define clear_treemap(M,i)      ((M)->treemap  &= ~idx2bit(i))
 49.2308 +#define treemap_is_marked(M,i)  ((M)->treemap  &   idx2bit(i))
 49.2309 +
 49.2310 +/* index corresponding to given bit */
 49.2311 +
 49.2312 +#if defined(__GNUC__) && defined(i386)
 49.2313 +#define compute_bit2idx(X, I)\
 49.2314 +{\
 49.2315 +  unsigned int J;\
 49.2316 +  __asm__("bsfl %1,%0\n\t" : "=r" (J) : "rm" (X));\
 49.2317 +  I = (bindex_t)J;\
 49.2318 +}
 49.2319 +
 49.2320 +#else /* GNUC */
 49.2321 +#if  USE_BUILTIN_FFS
 49.2322 +#define compute_bit2idx(X, I) I = ffs(X)-1
 49.2323 +
 49.2324 +#else /* USE_BUILTIN_FFS */
 49.2325 +#define compute_bit2idx(X, I)\
 49.2326 +{\
 49.2327 +  unsigned int Y = X - 1;\
 49.2328 +  unsigned int K = Y >> (16-4) & 16;\
 49.2329 +  unsigned int N = K;        Y >>= K;\
 49.2330 +  N += K = Y >> (8-3) &  8;  Y >>= K;\
 49.2331 +  N += K = Y >> (4-2) &  4;  Y >>= K;\
 49.2332 +  N += K = Y >> (2-1) &  2;  Y >>= K;\
 49.2333 +  N += K = Y >> (1-0) &  1;  Y >>= K;\
 49.2334 +  I = (bindex_t)(N + Y);\
 49.2335 +}
 49.2336 +#endif /* USE_BUILTIN_FFS */
 49.2337 +#endif /* GNUC */
 49.2338 +
 49.2339 +/* isolate the least set bit of a bitmap */
 49.2340 +#define least_bit(x)         ((x) & -(x))
 49.2341 +
 49.2342 +/* mask with all bits to left of least bit of x on */
 49.2343 +#define left_bits(x)         ((x<<1) | -(x<<1))
 49.2344 +
 49.2345 +/* mask with all bits to left of or equal to least bit of x on */
 49.2346 +#define same_or_left_bits(x) ((x) | -(x))
 49.2347 +
 49.2348 +
 49.2349 +/* ----------------------- Runtime Check Support ------------------------- */
 49.2350 +
 49.2351 +/*
 49.2352 +  For security, the main invariant is that malloc/free/etc never
 49.2353 +  writes to a static address other than malloc_state, unless static
 49.2354 +  malloc_state itself has been corrupted, which cannot occur via
 49.2355 +  malloc (because of these checks). In essence this means that we
 49.2356 +  believe all pointers, sizes, maps etc held in malloc_state, but
 49.2357 +  check all of those linked or offsetted from other embedded data
 49.2358 +  structures.  These checks are interspersed with main code in a way
 49.2359 +  that tends to minimize their run-time cost.
 49.2360 +
 49.2361 +  When FOOTERS is defined, in addition to range checking, we also
 49.2362 +  verify footer fields of inuse chunks, which can be used guarantee
 49.2363 +  that the mstate controlling malloc/free is intact.  This is a
 49.2364 +  streamlined version of the approach described by William Robertson
 49.2365 +  et al in "Run-time Detection of Heap-based Overflows" LISA'03
 49.2366 +  http://www.usenix.org/events/lisa03/tech/robertson.html The footer
 49.2367 +  of an inuse chunk holds the xor of its mstate and a random seed,
 49.2368 +  that is checked upon calls to free() and realloc().  This is
 49.2369 +  (probablistically) unguessable from outside the program, but can be
 49.2370 +  computed by any code successfully malloc'ing any chunk, so does not
 49.2371 +  itself provide protection against code that has already broken
 49.2372 +  security through some other means.  Unlike Robertson et al, we
 49.2373 +  always dynamically check addresses of all offset chunks (previous,
 49.2374 +  next, etc). This turns out to be cheaper than relying on hashes.
 49.2375 +*/
 49.2376 +
 49.2377 +#if !INSECURE
 49.2378 +/* Check if address a is at least as high as any from MORECORE or MMAP */
 49.2379 +#define ok_address(M, a) ((char*)(a) >= (M)->least_addr)
 49.2380 +/* Check if address of next chunk n is higher than base chunk p */
 49.2381 +#define ok_next(p, n)    ((char*)(p) < (char*)(n))
 49.2382 +/* Check if p has its cinuse bit on */
 49.2383 +#define ok_cinuse(p)     cinuse(p)
 49.2384 +/* Check if p has its pinuse bit on */
 49.2385 +#define ok_pinuse(p)     pinuse(p)
 49.2386 +
 49.2387 +#else /* !INSECURE */
 49.2388 +#define ok_address(M, a) (1)
 49.2389 +#define ok_next(b, n)    (1)
 49.2390 +#define ok_cinuse(p)     (1)
 49.2391 +#define ok_pinuse(p)     (1)
 49.2392 +#endif /* !INSECURE */
 49.2393 +
 49.2394 +#if (FOOTERS && !INSECURE)
 49.2395 +/* Check if (alleged) mstate m has expected magic field */
 49.2396 +#define ok_magic(M)      ((M)->magic == mparams.magic)
 49.2397 +#else  /* (FOOTERS && !INSECURE) */
 49.2398 +#define ok_magic(M)      (1)
 49.2399 +#endif /* (FOOTERS && !INSECURE) */
 49.2400 +
 49.2401 +
 49.2402 +/* In gcc, use __builtin_expect to minimize impact of checks */
 49.2403 +#if !INSECURE
 49.2404 +#if defined(__GNUC__) && __GNUC__ >= 3
 49.2405 +#define RTCHECK(e)  __builtin_expect(e, 1)
 49.2406 +#else /* GNUC */
 49.2407 +#define RTCHECK(e)  (e)
 49.2408 +#endif /* GNUC */
 49.2409 +#else /* !INSECURE */
 49.2410 +#define RTCHECK(e)  (1)
 49.2411 +#endif /* !INSECURE */
 49.2412 +
 49.2413 +/* macros to set up inuse chunks with or without footers */
 49.2414 +
 49.2415 +#if !FOOTERS
 49.2416 +
 49.2417 +#define mark_inuse_foot(M,p,s)
 49.2418 +
 49.2419 +/* Set cinuse bit and pinuse bit of next chunk */
 49.2420 +#define set_inuse(M,p,s)\
 49.2421 +  ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
 49.2422 +  ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
 49.2423 +
 49.2424 +/* Set cinuse and pinuse of this chunk and pinuse of next chunk */
 49.2425 +#define set_inuse_and_pinuse(M,p,s)\
 49.2426 +  ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
 49.2427 +  ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
 49.2428 +
 49.2429 +/* Set size, cinuse and pinuse bit of this chunk */
 49.2430 +#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
 49.2431 +  ((p)->head = (s|PINUSE_BIT|CINUSE_BIT))
 49.2432 +
 49.2433 +#else /* FOOTERS */
 49.2434 +
 49.2435 +/* Set foot of inuse chunk to be xor of mstate and seed */
 49.2436 +#define mark_inuse_foot(M,p,s)\
 49.2437 +  (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic))
 49.2438 +
 49.2439 +#define get_mstate_for(p)\
 49.2440 +  ((mstate)(((mchunkptr)((char*)(p) +\
 49.2441 +    (chunksize(p))))->prev_foot ^ mparams.magic))
 49.2442 +
 49.2443 +#define set_inuse(M,p,s)\
 49.2444 +  ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
 49.2445 +  (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \
 49.2446 +  mark_inuse_foot(M,p,s))
 49.2447 +
 49.2448 +#define set_inuse_and_pinuse(M,p,s)\
 49.2449 +  ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
 49.2450 +  (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\
 49.2451 + mark_inuse_foot(M,p,s))
 49.2452 +
 49.2453 +#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
 49.2454 +  ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
 49.2455 +  mark_inuse_foot(M, p, s))
 49.2456 +
 49.2457 +#endif /* !FOOTERS */
 49.2458 +
 49.2459 +/* ---------------------------- setting mparams -------------------------- */
 49.2460 +
 49.2461 +/* Initialize mparams */
 49.2462 +static int init_mparams(void) {
 49.2463 +  if (mparams.page_size == 0) {
 49.2464 +    size_t s;
 49.2465 +
 49.2466 +    mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
 49.2467 +    mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD;
 49.2468 +#if MORECORE_CONTIGUOUS
 49.2469 +    mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT;
 49.2470 +#else  /* MORECORE_CONTIGUOUS */
 49.2471 +    mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT;
 49.2472 +#endif /* MORECORE_CONTIGUOUS */
 49.2473 +
 49.2474 +#if (FOOTERS && !INSECURE)
 49.2475 +    {
 49.2476 +#if USE_DEV_RANDOM
 49.2477 +      int fd;
 49.2478 +      unsigned char buf[sizeof(size_t)];
 49.2479 +      /* Try to use /dev/urandom, else fall back on using time */
 49.2480 +      if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 &&
 49.2481 +          read(fd, buf, sizeof(buf)) == sizeof(buf)) {
 49.2482 +        s = *((size_t *) buf);
 49.2483 +        close(fd);
 49.2484 +      }
 49.2485 +      else
 49.2486 +#endif /* USE_DEV_RANDOM */
 49.2487 +        s = (size_t)(time(0) ^ (size_t)0x55555555U);
 49.2488 +
 49.2489 +      s |= (size_t)8U;    /* ensure nonzero */
 49.2490 +      s &= ~(size_t)7U;   /* improve chances of fault for bad values */
 49.2491 +
 49.2492 +    }
 49.2493 +#else /* (FOOTERS && !INSECURE) */
 49.2494 +    s = (size_t)0x58585858U;
 49.2495 +#endif /* (FOOTERS && !INSECURE) */
 49.2496 +    ACQUIRE_MAGIC_INIT_LOCK();
 49.2497 +    if (mparams.magic == 0) {
 49.2498 +      mparams.magic = s;
 49.2499 +      /* Set up lock for main malloc area */
 49.2500 +      INITIAL_LOCK(&gm->mutex);
 49.2501 +      gm->mflags = mparams.default_mflags;
 49.2502 +    }
 49.2503 +    RELEASE_MAGIC_INIT_LOCK();
 49.2504 +
 49.2505 +#ifndef WIN32
 49.2506 +    mparams.page_size = malloc_getpagesize;
 49.2507 +    mparams.granularity = ((DEFAULT_GRANULARITY != 0)?
 49.2508 +                           DEFAULT_GRANULARITY : mparams.page_size);
 49.2509 +#else /* WIN32 */
 49.2510 +    {
 49.2511 +      SYSTEM_INFO system_info;
 49.2512 +      GetSystemInfo(&system_info);
 49.2513 +      mparams.page_size = system_info.dwPageSize;
 49.2514 +      mparams.granularity = system_info.dwAllocationGranularity;
 49.2515 +    }
 49.2516 +#endif /* WIN32 */
 49.2517 +
 49.2518 +    /* Sanity-check configuration:
 49.2519 +       size_t must be unsigned and as wide as pointer type.
 49.2520 +       ints must be at least 4 bytes.
 49.2521 +       alignment must be at least 8.
 49.2522 +       Alignment, min chunk size, and page size must all be powers of 2.
 49.2523 +    */
 49.2524 +    if ((sizeof(size_t) != sizeof(char*)) ||
 49.2525 +        (MAX_SIZE_T < MIN_CHUNK_SIZE)  ||
 49.2526 +        (sizeof(int) < 4)  ||
 49.2527 +        (MALLOC_ALIGNMENT < (size_t)8U) ||
 49.2528 +        ((MALLOC_ALIGNMENT    & (MALLOC_ALIGNMENT-SIZE_T_ONE))    != 0) ||
 49.2529 +        ((MCHUNK_SIZE         & (MCHUNK_SIZE-SIZE_T_ONE))         != 0) ||
 49.2530 +        ((mparams.granularity & (mparams.granularity-SIZE_T_ONE)) != 0) ||
 49.2531 +        ((mparams.page_size   & (mparams.page_size-SIZE_T_ONE))   != 0))
 49.2532 +      ABORT;
 49.2533 +  }
 49.2534 +  return 0;
 49.2535 +}
 49.2536 +
 49.2537 +/* support for mallopt */
 49.2538 +static int change_mparam(int param_number, int value) {
 49.2539 +  size_t val = (size_t)value;
 49.2540 +  init_mparams();
 49.2541 +  switch(param_number) {
 49.2542 +  case M_TRIM_THRESHOLD:
 49.2543 +    mparams.trim_threshold = val;
 49.2544 +    return 1;
 49.2545 +  case M_GRANULARITY:
 49.2546 +    if (val >= mparams.page_size && ((val & (val-1)) == 0)) {
 49.2547 +      mparams.granularity = val;
 49.2548 +      return 1;
 49.2549 +    }
 49.2550 +    else
 49.2551 +      return 0;
 49.2552 +  case M_MMAP_THRESHOLD:
 49.2553 +    mparams.mmap_threshold = val;
 49.2554 +    return 1;
 49.2555 +  default:
 49.2556 +    return 0;
 49.2557 +  }
 49.2558 +}
 49.2559 +
 49.2560 +#if DEBUG
 49.2561 +/* ------------------------- Debugging Support --------------------------- */
 49.2562 +
 49.2563 +/* Check properties of any chunk, whether free, inuse, mmapped etc  */
 49.2564 +static void do_check_any_chunk(mstate m, mchunkptr p) {
 49.2565 +  assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
 49.2566 +  assert(ok_address(m, p));
 49.2567 +}
 49.2568 +
 49.2569 +/* Check properties of top chunk */
 49.2570 +static void do_check_top_chunk(mstate m, mchunkptr p) {
 49.2571 +  msegmentptr sp = segment_holding(m, (char*)p);
 49.2572 +  size_t  sz = chunksize(p);
 49.2573 +  assert(sp != 0);
 49.2574 +  assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
 49.2575 +  assert(ok_address(m, p));
 49.2576 +  assert(sz == m->topsize);
 49.2577 +  assert(sz > 0);
 49.2578 +  assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE);
 49.2579 +  assert(pinuse(p));
 49.2580 +  assert(!next_pinuse(p));
 49.2581 +}
 49.2582 +
 49.2583 +/* Check properties of (inuse) mmapped chunks */
 49.2584 +static void do_check_mmapped_chunk(mstate m, mchunkptr p) {
 49.2585 +  size_t  sz = chunksize(p);
 49.2586 +  size_t len = (sz + (p->prev_foot & ~IS_MMAPPED_BIT) + MMAP_FOOT_PAD);
 49.2587 +  assert(is_mmapped(p));
 49.2588 +  assert(use_mmap(m));
 49.2589 +  assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
 49.2590 +  assert(ok_address(m, p));
 49.2591 +  assert(!is_small(sz));
 49.2592 +  assert((len & (mparams.page_size-SIZE_T_ONE)) == 0);
 49.2593 +  assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD);
 49.2594 +  assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0);
 49.2595 +}
 49.2596 +
 49.2597 +/* Check properties of inuse chunks */
 49.2598 +static void do_check_inuse_chunk(mstate m, mchunkptr p) {
 49.2599 +  do_check_any_chunk(m, p);
 49.2600 +  assert(cinuse(p));
 49.2601 +  assert(next_pinuse(p));
 49.2602 +  /* If not pinuse and not mmapped, previous chunk has OK offset */
 49.2603 +  assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p);
 49.2604 +  if (is_mmapped(p))
 49.2605 +    do_check_mmapped_chunk(m, p);
 49.2606 +}
 49.2607 +
 49.2608 +/* Check properties of free chunks */
 49.2609 +static void do_check_free_chunk(mstate m, mchunkptr p) {
 49.2610 +  size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT);
 49.2611 +  mchunkptr next = chunk_plus_offset(p, sz);
 49.2612 +  do_check_any_chunk(m, p);
 49.2613 +  assert(!cinuse(p));
 49.2614 +  assert(!next_pinuse(p));
 49.2615 +  assert (!is_mmapped(p));
 49.2616 +  if (p != m->dv && p != m->top) {
 49.2617 +    if (sz >= MIN_CHUNK_SIZE) {
 49.2618 +      assert((sz & CHUNK_ALIGN_MASK) == 0);
 49.2619 +      assert(is_aligned(chunk2mem(p)));
 49.2620 +      assert(next->prev_foot == sz);
 49.2621 +      assert(pinuse(p));
 49.2622 +      assert (next == m->top || cinuse(next));
 49.2623 +      assert(p->fd->bk == p);
 49.2624 +      assert(p->bk->fd == p);
 49.2625 +    }
 49.2626 +    else  /* markers are always of size SIZE_T_SIZE */
 49.2627 +      assert(sz == SIZE_T_SIZE);
 49.2628 +  }
 49.2629 +}
 49.2630 +
 49.2631 +/* Check properties of malloced chunks at the point they are malloced */
 49.2632 +static void do_check_malloced_chunk(mstate m, void* mem, size_t s) {
 49.2633 +  if (mem != 0) {
 49.2634 +    mchunkptr p = mem2chunk(mem);
 49.2635 +    size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT);
 49.2636 +    do_check_inuse_chunk(m, p);
 49.2637 +    assert((sz & CHUNK_ALIGN_MASK) == 0);
 49.2638 +    assert(sz >= MIN_CHUNK_SIZE);
 49.2639 +    assert(sz >= s);
 49.2640 +    /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */
 49.2641 +    assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE));
 49.2642 +  }
 49.2643 +}
 49.2644 +
 49.2645 +/* Check a tree and its subtrees.  */
 49.2646 +static void do_check_tree(mstate m, tchunkptr t) {
 49.2647 +  tchunkptr head = 0;
 49.2648 +  tchunkptr u = t;
 49.2649 +  bindex_t tindex = t->index;
 49.2650 +  size_t tsize = chunksize(t);
 49.2651 +  bindex_t idx;
 49.2652 +  compute_tree_index(tsize, idx);
 49.2653 +  assert(tindex == idx);
 49.2654 +  assert(tsize >= MIN_LARGE_SIZE);
 49.2655 +  assert(tsize >= minsize_for_tree_index(idx));
 49.2656 +  assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1))));
 49.2657 +
 49.2658 +  do { /* traverse through chain of same-sized nodes */
 49.2659 +    do_check_any_chunk(m, ((mchunkptr)u));
 49.2660 +    assert(u->index == tindex);
 49.2661 +    assert(chunksize(u) == tsize);
 49.2662 +    assert(!cinuse(u));
 49.2663 +    assert(!next_pinuse(u));
 49.2664 +    assert(u->fd->bk == u);
 49.2665 +    assert(u->bk->fd == u);
 49.2666 +    if (u->parent == 0) {
 49.2667 +      assert(u->child[0] == 0);
 49.2668 +      assert(u->child[1] == 0);
 49.2669 +    }
 49.2670 +    else {
 49.2671 +      assert(head == 0); /* only one node on chain has parent */
 49.2672 +      head = u;
 49.2673 +      assert(u->parent != u);
 49.2674 +      assert (u->parent->child[0] == u ||
 49.2675 +              u->parent->child[1] == u ||
 49.2676 +              *((tbinptr*)(u->parent)) == u);
 49.2677 +      if (u->child[0] != 0) {
 49.2678 +        assert(u->child[0]->parent == u);
 49.2679 +        assert(u->child[0] != u);
 49.2680 +        do_check_tree(m, u->child[0]);
 49.2681 +      }
 49.2682 +      if (u->child[1] != 0) {
 49.2683 +        assert(u->child[1]->parent == u);
 49.2684 +        assert(u->child[1] != u);
 49.2685 +        do_check_tree(m, u->child[1]);
 49.2686 +      }
 49.2687 +      if (u->child[0] != 0 && u->child[1] != 0) {
 49.2688 +        assert(chunksize(u->child[0]) < chunksize(u->child[1]));
 49.2689 +      }
 49.2690 +    }
 49.2691 +    u = u->fd;
 49.2692 +  } while (u != t);
 49.2693 +  assert(head != 0);
 49.2694 +}
 49.2695 +
 49.2696 +/*  Check all the chunks in a treebin.  */
 49.2697 +static void do_check_treebin(mstate m, bindex_t i) {
 49.2698 +  tbinptr* tb = treebin_at(m, i);
 49.2699 +  tchunkptr t = *tb;
 49.2700 +  int empty = (m->treemap & (1U << i)) == 0;
 49.2701 +  if (t == 0)
 49.2702 +    assert(empty);
 49.2703 +  if (!empty)
 49.2704 +    do_check_tree(m, t);
 49.2705 +}
 49.2706 +
 49.2707 +/*  Check all the chunks in a smallbin.  */
 49.2708 +static void do_check_smallbin(mstate m, bindex_t i) {
 49.2709 +  sbinptr b = smallbin_at(m, i);
 49.2710 +  mchunkptr p = b->bk;
 49.2711 +  unsigned int empty = (m->smallmap & (1U << i)) == 0;
 49.2712 +  if (p == b)
 49.2713 +    assert(empty);
 49.2714 +  if (!empty) {
 49.2715 +    for (; p != b; p = p->bk) {
 49.2716 +      size_t size = chunksize(p);
 49.2717 +      mchunkptr q;
 49.2718 +      /* each chunk claims to be free */
 49.2719 +      do_check_free_chunk(m, p);
 49.2720 +      /* chunk belongs in bin */
 49.2721 +      assert(small_index(size) == i);
 49.2722 +      assert(p->bk == b || chunksize(p->bk) == chunksize(p));
 49.2723 +      /* chunk is followed by an inuse chunk */
 49.2724 +      q = next_chunk(p);
 49.2725 +      if (q->head != FENCEPOST_HEAD)
 49.2726 +        do_check_inuse_chunk(m, q);
 49.2727 +    }
 49.2728 +  }
 49.2729 +}
 49.2730 +
 49.2731 +/* Find x in a bin. Used in other check functions. */
 49.2732 +static int bin_find(mstate m, mchunkptr x) {
 49.2733 +  size_t size = chunksize(x);
 49.2734 +  if (is_small(size)) {
 49.2735 +    bindex_t sidx = small_index(size);
 49.2736 +    sbinptr b = smallbin_at(m, sidx);
 49.2737 +    if (smallmap_is_marked(m, sidx)) {
 49.2738 +      mchunkptr p = b;
 49.2739 +      do {
 49.2740 +        if (p == x)
 49.2741 +          return 1;
 49.2742 +      } while ((p = p->fd) != b);
 49.2743 +    }
 49.2744 +  }
 49.2745 +  else {
 49.2746 +    bindex_t tidx;
 49.2747 +    compute_tree_index(size, tidx);
 49.2748 +    if (treemap_is_marked(m, tidx)) {
 49.2749 +      tchunkptr t = *treebin_at(m, tidx);
 49.2750 +      size_t sizebits = size << leftshift_for_tree_index(tidx);
 49.2751 +      while (t != 0 && chunksize(t) != size) {
 49.2752 +        t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
 49.2753 +        sizebits <<= 1;
 49.2754 +      }
 49.2755 +      if (t != 0) {
 49.2756 +        tchunkptr u = t;
 49.2757 +        do {
 49.2758 +          if (u == (tchunkptr)x)
 49.2759 +            return 1;
 49.2760 +        } while ((u = u->fd) != t);
 49.2761 +      }
 49.2762 +    }
 49.2763 +  }
 49.2764 +  return 0;
 49.2765 +}
 49.2766 +
 49.2767 +/* Traverse each chunk and check it; return total */
 49.2768 +static size_t traverse_and_check(mstate m) {
 49.2769 +  size_t sum = 0;
 49.2770 +  if (is_initialized(m)) {
 49.2771 +    msegmentptr s = &m->seg;
 49.2772 +    sum += m->topsize + TOP_FOOT_SIZE;
 49.2773 +    while (s != 0) {
 49.2774 +      mchunkptr q = align_as_chunk(s->base);
 49.2775 +      mchunkptr lastq = 0;
 49.2776 +      assert(pinuse(q));
 49.2777 +      while (segment_holds(s, q) &&
 49.2778 +             q != m->top && q->head != FENCEPOST_HEAD) {
 49.2779 +        sum += chunksize(q);
 49.2780 +        if (cinuse(q)) {
 49.2781 +          assert(!bin_find(m, q));
 49.2782 +          do_check_inuse_chunk(m, q);
 49.2783 +        }
 49.2784 +        else {
 49.2785 +          assert(q == m->dv || bin_find(m, q));
 49.2786 +          assert(lastq == 0 || cinuse(lastq)); /* Not 2 consecutive free */
 49.2787 +          do_check_free_chunk(m, q);
 49.2788 +        }
 49.2789 +        lastq = q;
 49.2790 +        q = next_chunk(q);
 49.2791 +      }
 49.2792 +      s = s->next;
 49.2793 +    }
 49.2794 +  }
 49.2795 +  return sum;
 49.2796 +}
 49.2797 +
 49.2798 +/* Check all properties of malloc_state. */
 49.2799 +static void do_check_malloc_state(mstate m) {
 49.2800 +  bindex_t i;
 49.2801 +  size_t total;
 49.2802 +  /* check bins */
 49.2803 +  for (i = 0; i < NSMALLBINS; ++i)
 49.2804 +    do_check_smallbin(m, i);
 49.2805 +  for (i = 0; i < NTREEBINS; ++i)
 49.2806 +    do_check_treebin(m, i);
 49.2807 +
 49.2808 +  if (m->dvsize != 0) { /* check dv chunk */
 49.2809 +    do_check_any_chunk(m, m->dv);
 49.2810 +    assert(m->dvsize == chunksize(m->dv));
 49.2811 +    assert(m->dvsize >= MIN_CHUNK_SIZE);
 49.2812 +    assert(bin_find(m, m->dv) == 0);
 49.2813 +  }
 49.2814 +
 49.2815 +  if (m->top != 0) {   /* check top chunk */
 49.2816 +    do_check_top_chunk(m, m->top);
 49.2817 +    assert(m->topsize == chunksize(m->top));
 49.2818 +    assert(m->topsize > 0);
 49.2819 +    assert(bin_find(m, m->top) == 0);
 49.2820 +  }
 49.2821 +
 49.2822 +  total = traverse_and_check(m);
 49.2823 +  assert(total <= m->footprint);
 49.2824 +  assert(m->footprint <= m->max_footprint);
 49.2825 +}
 49.2826 +#endif /* DEBUG */
 49.2827 +
 49.2828 +/* ----------------------------- statistics ------------------------------ */
 49.2829 +
 49.2830 +#if !NO_MALLINFO
 49.2831 +static struct mallinfo internal_mallinfo(mstate m) {
 49.2832 +  struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
 49.2833 +  if (!PREACTION(m)) {
 49.2834 +    check_malloc_state(m);
 49.2835 +    if (is_initialized(m)) {
 49.2836 +      size_t nfree = SIZE_T_ONE; /* top always free */
 49.2837 +      size_t mfree = m->topsize + TOP_FOOT_SIZE;
 49.2838 +      size_t sum = mfree;
 49.2839 +      msegmentptr s = &m->seg;
 49.2840 +      while (s != 0) {
 49.2841 +        mchunkptr q = align_as_chunk(s->base);
 49.2842 +        while (segment_holds(s, q) &&
 49.2843 +               q != m->top && q->head != FENCEPOST_HEAD) {
 49.2844 +          size_t sz = chunksize(q);
 49.2845 +          sum += sz;
 49.2846 +          if (!cinuse(q)) {
 49.2847 +            mfree += sz;
 49.2848 +            ++nfree;
 49.2849 +          }
 49.2850 +          q = next_chunk(q);
 49.2851 +        }
 49.2852 +        s = s->next;
 49.2853 +      }
 49.2854 +
 49.2855 +      nm.arena    = sum;
 49.2856 +      nm.ordblks  = nfree;
 49.2857 +      nm.hblkhd   = m->footprint - sum;
 49.2858 +      nm.usmblks  = m->max_footprint;
 49.2859 +      nm.uordblks = m->footprint - mfree;
 49.2860 +      nm.fordblks = mfree;
 49.2861 +      nm.keepcost = m->topsize;
 49.2862 +    }
 49.2863 +
 49.2864 +    POSTACTION(m);
 49.2865 +  }
 49.2866 +  return nm;
 49.2867 +}
 49.2868 +#endif /* !NO_MALLINFO */
 49.2869 +
 49.2870 +static void internal_malloc_stats(mstate m) {
 49.2871 +  if (!PREACTION(m)) {
 49.2872 +    size_t maxfp = 0;
 49.2873 +    size_t fp = 0;
 49.2874 +    size_t used = 0;
 49.2875 +    check_malloc_state(m);
 49.2876 +    if (is_initialized(m)) {
 49.2877 +      msegmentptr s = &m->seg;
 49.2878 +      maxfp = m->max_footprint;
 49.2879 +      fp = m->footprint;
 49.2880 +      used = fp - (m->topsize + TOP_FOOT_SIZE);
 49.2881 +
 49.2882 +      while (s != 0) {
 49.2883 +        mchunkptr q = align_as_chunk(s->base);
 49.2884 +        while (segment_holds(s, q) &&
 49.2885 +               q != m->top && q->head != FENCEPOST_HEAD) {
 49.2886 +          if (!cinuse(q))
 49.2887 +            used -= chunksize(q);
 49.2888 +          q = next_chunk(q);
 49.2889 +        }
 49.2890 +        s = s->next;
 49.2891 +      }
 49.2892 +    }
 49.2893 +
 49.2894 +#ifndef LACKS_STDIO_H
 49.2895 +    fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp));
 49.2896 +    fprintf(stderr, "system bytes     = %10lu\n", (unsigned long)(fp));
 49.2897 +    fprintf(stderr, "in use bytes     = %10lu\n", (unsigned long)(used));
 49.2898 +#endif
 49.2899 +
 49.2900 +    POSTACTION(m);
 49.2901 +  }
 49.2902 +}
 49.2903 +
 49.2904 +/* ----------------------- Operations on smallbins ----------------------- */
 49.2905 +
 49.2906 +/*
 49.2907 +  Various forms of linking and unlinking are defined as macros.  Even
 49.2908 +  the ones for trees, which are very long but have very short typical
 49.2909 +  paths.  This is ugly but reduces reliance on inlining support of
 49.2910 +  compilers.
 49.2911 +*/
 49.2912 +
 49.2913 +/* Link a free chunk into a smallbin  */
 49.2914 +#define insert_small_chunk(M, P, S) {\
 49.2915 +  bindex_t I  = small_index(S);\
 49.2916 +  mchunkptr B = smallbin_at(M, I);\
 49.2917 +  mchunkptr F = B;\
 49.2918 +  assert(S >= MIN_CHUNK_SIZE);\
 49.2919 +  if (!smallmap_is_marked(M, I))\
 49.2920 +    mark_smallmap(M, I);\
 49.2921 +  else if (RTCHECK(ok_address(M, B->fd)))\
 49.2922 +    F = B->fd;\
 49.2923 +  else {\
 49.2924 +    CORRUPTION_ERROR_ACTION(M);\
 49.2925 +  }\
 49.2926 +  B->fd = P;\
 49.2927 +  F->bk = P;\
 49.2928 +  P->fd = F;\
 49.2929 +  P->bk = B;\
 49.2930 +}
 49.2931 +
 49.2932 +/* Unlink a chunk from a smallbin  */
 49.2933 +#define unlink_small_chunk(M, P, S) {\
 49.2934 +  mchunkptr F = P->fd;\
 49.2935 +  mchunkptr B = P->bk;\
 49.2936 +  bindex_t I = small_index(S);\
 49.2937 +  assert(P != B);\
 49.2938 +  assert(P != F);\
 49.2939 +  assert(chunksize(P) == small_index2size(I));\
 49.2940 +  if (F == B)\
 49.2941 +    clear_smallmap(M, I);\
 49.2942 +  else if (RTCHECK((F == smallbin_at(M,I) || ok_address(M, F)) &&\
 49.2943 +                   (B == smallbin_at(M,I) || ok_address(M, B)))) {\
 49.2944 +    F->bk = B;\
 49.2945 +    B->fd = F;\
 49.2946 +  }\
 49.2947 +  else {\
 49.2948 +    CORRUPTION_ERROR_ACTION(M);\
 49.2949 +  }\
 49.2950 +}
 49.2951 +
 49.2952 +/* Unlink the first chunk from a smallbin */
 49.2953 +#define unlink_first_small_chunk(M, B, P, I) {\
 49.2954 +  mchunkptr F = P->fd;\
 49.2955 +  assert(P != B);\
 49.2956 +  assert(P != F);\
 49.2957 +  assert(chunksize(P) == small_index2size(I));\
 49.2958 +  if (B == F)\
 49.2959 +    clear_smallmap(M, I);\
 49.2960 +  else if (RTCHECK(ok_address(M, F))) {\
 49.2961 +    B->fd = F;\
 49.2962 +    F->bk = B;\
 49.2963 +  }\
 49.2964 +  else {\
 49.2965 +    CORRUPTION_ERROR_ACTION(M);\
 49.2966 +  }\
 49.2967 +}
 49.2968 +
 49.2969 +/* Replace dv node, binning the old one */
 49.2970 +/* Used only when dvsize known to be small */
 49.2971 +#define replace_dv(M, P, S) {\
 49.2972 +  size_t DVS = M->dvsize;\
 49.2973 +  if (DVS != 0) {\
 49.2974 +    mchunkptr DV = M->dv;\
 49.2975 +    assert(is_small(DVS));\
 49.2976 +    insert_small_chunk(M, DV, DVS);\
 49.2977 +  }\
 49.2978 +  M->dvsize = S;\
 49.2979 +  M->dv = P;\
 49.2980 +}
 49.2981 +
 49.2982 +/* ------------------------- Operations on trees ------------------------- */
 49.2983 +
 49.2984 +/* Insert chunk into tree */
 49.2985 +#define insert_large_chunk(M, X, S) {\
 49.2986 +  tbinptr* H;\
 49.2987 +  bindex_t I;\
 49.2988 +  compute_tree_index(S, I);\
 49.2989 +  H = treebin_at(M, I);\
 49.2990 +  X->index = I;\
 49.2991 +  X->child[0] = X->child[1] = 0;\
 49.2992 +  if (!treemap_is_marked(M, I)) {\
 49.2993 +    mark_treemap(M, I);\
 49.2994 +    *H = X;\
 49.2995 +    X->parent = (tchunkptr)H;\
 49.2996 +    X->fd = X->bk = X;\
 49.2997 +  }\
 49.2998 +  else {\
 49.2999 +    tchunkptr T = *H;\
 49.3000 +    size_t K = S << leftshift_for_tree_index(I);\
 49.3001 +    for (;;) {\
 49.3002 +      if (chunksize(T) != S) {\
 49.3003 +        tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\
 49.3004 +        K <<= 1;\
 49.3005 +        if (*C != 0)\
 49.3006 +          T = *C;\
 49.3007 +        else if (RTCHECK(ok_address(M, C))) {\
 49.3008 +          *C = X;\
 49.3009 +          X->parent = T;\
 49.3010 +          X->fd = X->bk = X;\
 49.3011 +          break;\
 49.3012 +        }\
 49.3013 +        else {\
 49.3014 +          CORRUPTION_ERROR_ACTION(M);\
 49.3015 +          break;\
 49.3016 +        }\
 49.3017 +      }\
 49.3018 +      else {\
 49.3019 +        tchunkptr F = T->fd;\
 49.3020 +        if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\
 49.3021 +          T->fd = F->bk = X;\
 49.3022 +          X->fd = F;\
 49.3023 +          X->bk = T;\
 49.3024 +          X->parent = 0;\
 49.3025 +          break;\
 49.3026 +        }\
 49.3027 +        else {\
 49.3028 +          CORRUPTION_ERROR_ACTION(M);\
 49.3029 +          break;\
 49.3030 +        }\
 49.3031 +      }\
 49.3032 +    }\
 49.3033 +  }\
 49.3034 +}
 49.3035 +
 49.3036 +/*
 49.3037 +  Unlink steps:
 49.3038 +
 49.3039 +  1. If x is a chained node, unlink it from its same-sized fd/bk links
 49.3040 +     and choose its bk node as its replacement.
 49.3041 +  2. If x was the last node of its size, but not a leaf node, it must
 49.3042 +     be replaced with a leaf node (not merely one with an open left or
 49.3043 +     right), to make sure that lefts and rights of descendents
 49.3044 +     correspond properly to bit masks.  We use the rightmost descendent
 49.3045 +     of x.  We could use any other leaf, but this is easy to locate and
 49.3046 +     tends to counteract removal of leftmosts elsewhere, and so keeps
 49.3047 +     paths shorter than minimally guaranteed.  This doesn't loop much
 49.3048 +     because on average a node in a tree is near the bottom.
 49.3049 +  3. If x is the base of a chain (i.e., has parent links) relink
 49.3050 +     x's parent and children to x's replacement (or null if none).
 49.3051 +*/
 49.3052 +
 49.3053 +#define unlink_large_chunk(M, X) {\
 49.3054 +  tchunkptr XP = X->parent;\
 49.3055 +  tchunkptr R;\
 49.3056 +  if (X->bk != X) {\
 49.3057 +    tchunkptr F = X->fd;\
 49.3058 +    R = X->bk;\
 49.3059 +    if (RTCHECK(ok_address(M, F))) {\
 49.3060 +      F->bk = R;\
 49.3061 +      R->fd = F;\
 49.3062 +    }\
 49.3063 +    else {\
 49.3064 +      CORRUPTION_ERROR_ACTION(M);\
 49.3065 +    }\
 49.3066 +  }\
 49.3067 +  else {\
 49.3068 +    tchunkptr* RP;\
 49.3069 +    if (((R = *(RP = &(X->child[1]))) != 0) ||\
 49.3070 +        ((R = *(RP = &(X->child[0]))) != 0)) {\
 49.3071 +      tchunkptr* CP;\
 49.3072 +      while ((*(CP = &(R->child[1])) != 0) ||\
 49.3073 +             (*(CP = &(R->child[0])) != 0)) {\
 49.3074 +        R = *(RP = CP);\
 49.3075 +      }\
 49.3076 +      if (RTCHECK(ok_address(M, RP)))\
 49.3077 +        *RP = 0;\
 49.3078 +      else {\
 49.3079 +        CORRUPTION_ERROR_ACTION(M);\
 49.3080 +      }\
 49.3081 +    }\
 49.3082 +  }\
 49.3083 +  if (XP != 0) {\
 49.3084 +    tbinptr* H = treebin_at(M, X->index);\
 49.3085 +    if (X == *H) {\
 49.3086 +      if ((*H = R) == 0) \
 49.3087 +        clear_treemap(M, X->index);\
 49.3088 +    }\
 49.3089 +    else if (RTCHECK(ok_address(M, XP))) {\
 49.3090 +      if (XP->child[0] == X) \
 49.3091 +        XP->child[0] = R;\
 49.3092 +      else \
 49.3093 +        XP->child[1] = R;\
 49.3094 +    }\
 49.3095 +    else\
 49.3096 +      CORRUPTION_ERROR_ACTION(M);\
 49.3097 +    if (R != 0) {\
 49.3098 +      if (RTCHECK(ok_address(M, R))) {\
 49.3099 +        tchunkptr C0, C1;\
 49.3100 +        R->parent = XP;\
 49.3101 +        if ((C0 = X->child[0]) != 0) {\
 49.3102 +          if (RTCHECK(ok_address(M, C0))) {\
 49.3103 +            R->child[0] = C0;\
 49.3104 +            C0->parent = R;\
 49.3105 +          }\
 49.3106 +          else\
 49.3107 +            CORRUPTION_ERROR_ACTION(M);\
 49.3108 +        }\
 49.3109 +        if ((C1 = X->child[1]) != 0) {\
 49.3110 +          if (RTCHECK(ok_address(M, C1))) {\
 49.3111 +            R->child[1] = C1;\
 49.3112 +            C1->parent = R;\
 49.3113 +          }\
 49.3114 +          else\
 49.3115 +            CORRUPTION_ERROR_ACTION(M);\
 49.3116 +        }\
 49.3117 +      }\
 49.3118 +      else\
 49.3119 +        CORRUPTION_ERROR_ACTION(M);\
 49.3120 +    }\
 49.3121 +  }\
 49.3122 +}
 49.3123 +
 49.3124 +/* Relays to large vs small bin operations */
 49.3125 +
 49.3126 +#define insert_chunk(M, P, S)\
 49.3127 +  if (is_small(S)) insert_small_chunk(M, P, S)\
 49.3128 +  else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); }
 49.3129 +
 49.3130 +#define unlink_chunk(M, P, S)\
 49.3131 +  if (is_small(S)) unlink_small_chunk(M, P, S)\
 49.3132 +  else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); }
 49.3133 +
 49.3134 +
 49.3135 +/* Relays to internal calls to malloc/free from realloc, memalign etc */
 49.3136 +
 49.3137 +#if ONLY_MSPACES
 49.3138 +#define internal_malloc(m, b) mspace_malloc(m, b)
 49.3139 +#define internal_free(m, mem) mspace_free(m,mem);
 49.3140 +#else /* ONLY_MSPACES */
 49.3141 +#if MSPACES
 49.3142 +#define internal_malloc(m, b)\
 49.3143 +   (m == gm)? dlmalloc(b) : mspace_malloc(m, b)
 49.3144 +#define internal_free(m, mem)\
 49.3145 +   if (m == gm) dlfree(mem); else mspace_free(m,mem);
 49.3146 +#else /* MSPACES */
 49.3147 +#define internal_malloc(m, b) dlmalloc(b)
 49.3148 +#define internal_free(m, mem) dlfree(mem)
 49.3149 +#endif /* MSPACES */
 49.3150 +#endif /* ONLY_MSPACES */
 49.3151 +
 49.3152 +/* -----------------------  Direct-mmapping chunks ----------------------- */
 49.3153 +
 49.3154 +/*
 49.3155 +  Directly mmapped chunks are set up with an offset to the start of
 49.3156 +  the mmapped region stored in the prev_foot field of the chunk. This
 49.3157 +  allows reconstruction of the required argument to MUNMAP when freed,
 49.3158 +  and also allows adjustment of the returned chunk to meet alignment
 49.3159 +  requirements (especially in memalign).  There is also enough space
 49.3160 +  allocated to hold a fake next chunk of size SIZE_T_SIZE to maintain
 49.3161 +  the PINUSE bit so frees can be checked.
 49.3162 +*/
 49.3163 +
 49.3164 +/* Malloc using mmap */
 49.3165 +static void* mmap_alloc(mstate m, size_t nb) {
 49.3166 +  size_t mmsize = granularity_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
 49.3167 +  if (mmsize > nb) {     /* Check for wrap around 0 */
 49.3168 +    char* mm = (char*)(DIRECT_MMAP(mmsize));
 49.3169 +    if (mm != CMFAIL) {
 49.3170 +      size_t offset = align_offset(chunk2mem(mm));
 49.3171 +      size_t psize = mmsize - offset - MMAP_FOOT_PAD;
 49.3172 +      mchunkptr p = (mchunkptr)(mm + offset);
 49.3173 +      p->prev_foot = offset | IS_MMAPPED_BIT;
 49.3174 +      (p)->head = (psize|CINUSE_BIT);
 49.3175 +      mark_inuse_foot(m, p, psize);
 49.3176 +      chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;
 49.3177 +      chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0;
 49.3178 +
 49.3179 +      if (mm < m->least_addr)
 49.3180 +        m->least_addr = mm;
 49.3181 +      if ((m->footprint += mmsize) > m->max_footprint)
 49.3182 +        m->max_footprint = m->footprint;
 49.3183 +      assert(is_aligned(chunk2mem(p)));
 49.3184 +      check_mmapped_chunk(m, p);
 49.3185 +      return chunk2mem(p);
 49.3186 +    }
 49.3187 +  }
 49.3188 +  return 0;
 49.3189 +}
 49.3190 +
 49.3191 +/* Realloc using mmap */
 49.3192 +static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb) {
 49.3193 +  size_t oldsize = chunksize(oldp);
 49.3194 +  if (is_small(nb)) /* Can't shrink mmap regions below small size */
 49.3195 +    return 0;
 49.3196 +  /* Keep old chunk if big enough but not too big */
 49.3197 +  if (oldsize >= nb + SIZE_T_SIZE &&
 49.3198 +      (oldsize - nb) <= (mparams.granularity << 1))
 49.3199 +    return oldp;
 49.3200 +  else {
 49.3201 +    size_t offset = oldp->prev_foot & ~IS_MMAPPED_BIT;
 49.3202 +    size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD;
 49.3203 +    size_t newmmsize = granularity_align(nb + SIX_SIZE_T_SIZES +
 49.3204 +                                         CHUNK_ALIGN_MASK);
 49.3205 +    char* cp = (char*)CALL_MREMAP((char*)oldp - offset,
 49.3206 +                                  oldmmsize, newmmsize, 1);
 49.3207 +    if (cp != CMFAIL) {
 49.3208 +      mchunkptr newp = (mchunkptr)(cp + offset);
 49.3209 +      size_t psize = newmmsize - offset - MMAP_FOOT_PAD;
 49.3210 +      newp->head = (psize|CINUSE_BIT);
 49.3211 +      mark_inuse_foot(m, newp, psize);
 49.3212 +      chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD;
 49.3213 +      chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0;
 49.3214 +
 49.3215 +      if (cp < m->least_addr)
 49.3216 +        m->least_addr = cp;
 49.3217 +      if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint)
 49.3218 +        m->max_footprint = m->footprint;
 49.3219 +      check_mmapped_chunk(m, newp);
 49.3220 +      return newp;
 49.3221 +    }
 49.3222 +  }
 49.3223 +  return 0;
 49.3224 +}
 49.3225 +
 49.3226 +/* -------------------------- mspace management -------------------------- */
 49.3227 +
 49.3228 +/* Initialize top chunk and its size */
 49.3229 +static void init_top(mstate m, mchunkptr p, size_t psize) {
 49.3230 +  /* Ensure alignment */
 49.3231 +  size_t offset = align_offset(chunk2mem(p));
 49.3232 +  p = (mchunkptr)((char*)p + offset);
 49.3233 +  psize -= offset;
 49.3234 +
 49.3235 +  m->top = p;
 49.3236 +  m->topsize = psize;
 49.3237 +  p->head = psize | PINUSE_BIT;
 49.3238 +  /* set size of fake trailing chunk holding overhead space only once */
 49.3239 +  chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE;
 49.3240 +  m->trim_check = mparams.trim_threshold; /* reset on each update */
 49.3241 +}
 49.3242 +
 49.3243 +/* Initialize bins for a new mstate that is otherwise zeroed out */
 49.3244 +static void init_bins(mstate m) {
 49.3245 +  /* Establish circular links for smallbins */
 49.3246 +  bindex_t i;
 49.3247 +  for (i = 0; i < NSMALLBINS; ++i) {
 49.3248 +    sbinptr bin = smallbin_at(m,i);
 49.3249 +    bin->fd = bin->bk = bin;
 49.3250 +  }
 49.3251 +}
 49.3252 +
 49.3253 +#if PROCEED_ON_ERROR
 49.3254 +
 49.3255 +/* default corruption action */
 49.3256 +static void reset_on_error(mstate m) {
 49.3257 +  int i;
 49.3258 +  ++malloc_corruption_error_count;
 49.3259 +  /* Reinitialize fields to forget about all memory */
 49.3260 +  m->smallbins = m->treebins = 0;
 49.3261 +  m->dvsize = m->topsize = 0;
 49.3262 +  m->seg.base = 0;
 49.3263 +  m->seg.size = 0;
 49.3264 +  m->seg.next = 0;
 49.3265 +  m->top = m->dv = 0;
 49.3266 +  for (i = 0; i < NTREEBINS; ++i)
 49.3267 +    *treebin_at(m, i) = 0;
 49.3268 +  init_bins(m);
 49.3269 +}
 49.3270 +#endif /* PROCEED_ON_ERROR */
 49.3271 +
 49.3272 +/* Allocate chunk and prepend remainder with chunk in successor base. */
 49.3273 +static void* prepend_alloc(mstate m, char* newbase, char* oldbase,
 49.3274 +                           size_t nb) {
 49.3275 +  mchunkptr p = align_as_chunk(newbase);
 49.3276 +  mchunkptr oldfirst = align_as_chunk(oldbase);
 49.3277 +  size_t psize = (char*)oldfirst - (char*)p;
 49.3278 +  mchunkptr q = chunk_plus_offset(p, nb);
 49.3279 +  size_t qsize = psize - nb;
 49.3280 +  set_size_and_pinuse_of_inuse_chunk(m, p, nb);
 49.3281 +
 49.3282 +  assert((char*)oldfirst > (char*)q);
 49.3283 +  assert(pinuse(oldfirst));
 49.3284 +  assert(qsize >= MIN_CHUNK_SIZE);
 49.3285 +
 49.3286 +  /* consolidate remainder with first chunk of old base */
 49.3287 +  if (oldfirst == m->top) {
 49.3288 +    size_t tsize = m->topsize += qsize;
 49.3289 +    m->top = q;
 49.3290 +    q->head = tsize | PINUSE_BIT;
 49.3291 +    check_top_chunk(m, q);
 49.3292 +  }
 49.3293 +  else if (oldfirst == m->dv) {
 49.3294 +    size_t dsize = m->dvsize += qsize;
 49.3295 +    m->dv = q;
 49.3296 +    set_size_and_pinuse_of_free_chunk(q, dsize);
 49.3297 +  }
 49.3298 +  else {
 49.3299 +    if (!cinuse(oldfirst)) {
 49.3300 +      size_t nsize = chunksize(oldfirst);
 49.3301 +      unlink_chunk(m, oldfirst, nsize);
 49.3302 +      oldfirst = chunk_plus_offset(oldfirst, nsize);
 49.3303 +      qsize += nsize;
 49.3304 +    }
 49.3305 +    set_free_with_pinuse(q, qsize, oldfirst);
 49.3306 +    insert_chunk(m, q, qsize);
 49.3307 +    check_free_chunk(m, q);
 49.3308 +  }
 49.3309 +
 49.3310 +  check_malloced_chunk(m, chunk2mem(p), nb);
 49.3311 +  return chunk2mem(p);
 49.3312 +}
 49.3313 +
 49.3314 +
 49.3315 +/* Add a segment to hold a new noncontiguous region */
 49.3316 +static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) {
 49.3317 +  /* Determine locations and sizes of segment, fenceposts, old top */
 49.3318 +  char* old_top = (char*)m->top;
 49.3319 +  msegmentptr oldsp = segment_holding(m, old_top);
 49.3320 +  char* old_end = oldsp->base + oldsp->size;
 49.3321 +  size_t ssize = pad_request(sizeof(struct malloc_segment));
 49.3322 +  char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
 49.3323 +  size_t offset = align_offset(chunk2mem(rawsp));
 49.3324 +  char* asp = rawsp + offset;
 49.3325 +  char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp;
 49.3326 +  mchunkptr sp = (mchunkptr)csp;
 49.3327 +  msegmentptr ss = (msegmentptr)(chunk2mem(sp));
 49.3328 +  mchunkptr tnext = chunk_plus_offset(sp, ssize);
 49.3329 +  mchunkptr p = tnext;
 49.3330 +  int nfences = 0;
 49.3331 +
 49.3332 +  /* reset top to new space */
 49.3333 +  init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
 49.3334 +
 49.3335 +  /* Set up segment record */
 49.3336 +  assert(is_aligned(ss));
 49.3337 +  set_size_and_pinuse_of_inuse_chunk(m, sp, ssize);
 49.3338 +  *ss = m->seg; /* Push current record */
 49.3339 +  m->seg.base = tbase;
 49.3340 +  m->seg.size = tsize;
 49.3341 +  m->seg.sflags = mmapped;
 49.3342 +  m->seg.next = ss;
 49.3343 +
 49.3344 +  /* Insert trailing fenceposts */
 49.3345 +  for (;;) {
 49.3346 +    mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE);
 49.3347 +    p->head = FENCEPOST_HEAD;
 49.3348 +    ++nfences;
 49.3349 +    if ((char*)(&(nextp->head)) < old_end)
 49.3350 +      p = nextp;
 49.3351 +    else
 49.3352 +      break;
 49.3353 +  }
 49.3354 +  assert(nfences >= 2);
 49.3355 +
 49.3356 +  /* Insert the rest of old top into a bin as an ordinary free chunk */
 49.3357 +  if (csp != old_top) {
 49.3358 +    mchunkptr q = (mchunkptr)old_top;
 49.3359 +    size_t psize = csp - old_top;
 49.3360 +    mchunkptr tn = chunk_plus_offset(q, psize);
 49.3361 +    set_free_with_pinuse(q, psize, tn);
 49.3362 +    insert_chunk(m, q, psize);
 49.3363 +  }
 49.3364 +
 49.3365 +  check_top_chunk(m, m->top);
 49.3366 +}
 49.3367 +
 49.3368 +/* -------------------------- System allocation -------------------------- */
 49.3369 +
 49.3370 +/* Get memory from system using MORECORE or MMAP */
 49.3371 +static void* sys_alloc(mstate m, size_t nb) {
 49.3372 +  char* tbase = CMFAIL;
 49.3373 +  size_t tsize = 0;
 49.3374 +  flag_t mmap_flag = 0;
 49.3375 +
 49.3376 +  init_mparams();
 49.3377 +
 49.3378 +  /* Directly map large chunks */
 49.3379 +  if (use_mmap(m) && nb >= mparams.mmap_threshold) {
 49.3380 +    void* mem = mmap_alloc(m, nb);
 49.3381 +    if (mem != 0)
 49.3382 +      return mem;
 49.3383 +  }
 49.3384 +
 49.3385 +  /*
 49.3386 +    Try getting memory in any of three ways (in most-preferred to
 49.3387 +    least-preferred order):
 49.3388 +    1. A call to MORECORE that can normally contiguously extend memory.
 49.3389 +       (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or
 49.3390 +       or main space is mmapped or a previous contiguous call failed)
 49.3391 +    2. A call to MMAP new space (disabled if not HAVE_MMAP).
 49.3392 +       Note that under the default settings, if MORECORE is unable to
 49.3393 +       fulfill a request, and HAVE_MMAP is true, then mmap is
 49.3394 +       used as a noncontiguous system allocator. This is a useful backup
 49.3395 +       strategy for systems with holes in address spaces -- in this case
 49.3396 +       sbrk cannot contiguously expand the heap, but mmap may be able to
 49.3397 +       find space.
 49.3398 +    3. A call to MORECORE that cannot usually contiguously extend memory.
 49.3399 +       (disabled if not HAVE_MORECORE)
 49.3400 +  */
 49.3401 +
 49.3402 +  if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) {
 49.3403 +    char* br = CMFAIL;
 49.3404 +    msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top);
 49.3405 +    size_t asize = 0;
 49.3406 +    ACQUIRE_MORECORE_LOCK();
 49.3407 +
 49.3408 +    if (ss == 0) {  /* First time through or recovery */
 49.3409 +      char* base = (char*)CALL_MORECORE(0);
 49.3410 +      if (base != CMFAIL) {
 49.3411 +        asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE);
 49.3412 +        /* Adjust to end on a page boundary */
 49.3413 +        if (!is_page_aligned(base))
 49.3414 +          asize += (page_align((size_t)base) - (size_t)base);
 49.3415 +        /* Can't call MORECORE if size is negative when treated as signed */
 49.3416 +        if (asize < HALF_MAX_SIZE_T &&
 49.3417 +            (br = (char*)(CALL_MORECORE(asize))) == base) {
 49.3418 +          tbase = base;
 49.3419 +          tsize = asize;
 49.3420 +        }
 49.3421 +      }
 49.3422 +    }
 49.3423 +    else {
 49.3424 +      /* Subtract out existing available top space from MORECORE request. */
 49.3425 +      asize = granularity_align(nb - m->topsize + TOP_FOOT_SIZE + SIZE_T_ONE);
 49.3426 +      /* Use mem here only if it did continuously extend old space */
 49.3427 +      if (asize < HALF_MAX_SIZE_T &&
 49.3428 +          (br = (char*)(CALL_MORECORE(asize))) == ss->base+ss->size) {
 49.3429 +        tbase = br;
 49.3430 +        tsize = asize;
 49.3431 +      }
 49.3432 +    }
 49.3433 +
 49.3434 +    if (tbase == CMFAIL) {    /* Cope with partial failure */
 49.3435 +      if (br != CMFAIL) {    /* Try to use/extend the space we did get */
 49.3436 +        if (asize < HALF_MAX_SIZE_T &&
 49.3437 +            asize < nb + TOP_FOOT_SIZE + SIZE_T_ONE) {
 49.3438 +          size_t esize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE - asize);
 49.3439 +          if (esize < HALF_MAX_SIZE_T) {
 49.3440 +            char* end = (char*)CALL_MORECORE(esize);
 49.3441 +            if (end != CMFAIL)
 49.3442 +              asize += esize;
 49.3443 +            else {            /* Can't use; try to release */
 49.3444 +              end = (char*)CALL_MORECORE(-asize);
 49.3445 +              br = CMFAIL;
 49.3446 +            }
 49.3447 +          }
 49.3448 +        }
 49.3449 +      }
 49.3450 +      if (br != CMFAIL) {    /* Use the space we did get */
 49.3451 +        tbase = br;
 49.3452 +        tsize = asize;
 49.3453 +      }
 49.3454 +      else
 49.3455 +        disable_contiguous(m); /* Don't try contiguous path in the future */
 49.3456 +    }
 49.3457 +
 49.3458 +    RELEASE_MORECORE_LOCK();
 49.3459 +  }
 49.3460 +
 49.3461 +  if (HAVE_MMAP && tbase == CMFAIL) {  /* Try MMAP */
 49.3462 +    size_t req = nb + TOP_FOOT_SIZE + SIZE_T_ONE;
 49.3463 +    size_t rsize = granularity_align(req);
 49.3464 +    if (rsize > nb) { /* Fail if wraps around zero */
 49.3465 +      char* mp = (char*)(CALL_MMAP(rsize));
 49.3466 +      if (mp != CMFAIL) {
 49.3467 +        tbase = mp;
 49.3468 +        tsize = rsize;
 49.3469 +        mmap_flag = IS_MMAPPED_BIT;
 49.3470 +      }
 49.3471 +    }
 49.3472 +  }
 49.3473 +
 49.3474 +  if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */
 49.3475 +    size_t asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE);
 49.3476 +    if (asize < HALF_MAX_SIZE_T) {
 49.3477 +      char* br = CMFAIL;
 49.3478 +      char* end = CMFAIL;
 49.3479 +      ACQUIRE_MORECORE_LOCK();
 49.3480 +      br = (char*)(CALL_MORECORE(asize));
 49.3481 +      end = (char*)(CALL_MORECORE(0));
 49.3482 +      RELEASE_MORECORE_LOCK();
 49.3483 +      if (br != CMFAIL && end != CMFAIL && br < end) {
 49.3484 +        size_t ssize = end - br;
 49.3485 +        if (ssize > nb + TOP_FOOT_SIZE) {
 49.3486 +          tbase = br;
 49.3487 +          tsize = ssize;
 49.3488 +        }
 49.3489 +      }
 49.3490 +    }
 49.3491 +  }
 49.3492 +
 49.3493 +  if (tbase != CMFAIL) {
 49.3494 +
 49.3495 +    if ((m->footprint += tsize) > m->max_footprint)
 49.3496 +      m->max_footprint = m->footprint;
 49.3497 +
 49.3498 +    if (!is_initialized(m)) { /* first-time initialization */
 49.3499 +      m->seg.base = m->least_addr = tbase;
 49.3500 +      m->seg.size = tsize;
 49.3501 +      m->seg.sflags = mmap_flag;
 49.3502 +      m->magic = mparams.magic;
 49.3503 +      init_bins(m);
 49.3504 +      if (is_global(m)) 
 49.3505 +        init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
 49.3506 +      else {
 49.3507 +        /* Offset top by embedded malloc_state */
 49.3508 +        mchunkptr mn = next_chunk(mem2chunk(m));
 49.3509 +        init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE);
 49.3510 +      }
 49.3511 +    }
 49.3512 +
 49.3513 +    else {
 49.3514 +      /* Try to merge with an existing segment */
 49.3515 +      msegmentptr sp = &m->seg;
 49.3516 +      while (sp != 0 && tbase != sp->base + sp->size)
 49.3517 +        sp = sp->next;
 49.3518 +      if (sp != 0 &&
 49.3519 +          !is_extern_segment(sp) &&
 49.3520 +          (sp->sflags & IS_MMAPPED_BIT) == mmap_flag &&
 49.3521 +          segment_holds(sp, m->top)) { /* append */
 49.3522 +        sp->size += tsize;
 49.3523 +        init_top(m, m->top, m->topsize + tsize);
 49.3524 +      }
 49.3525 +      else {
 49.3526 +        if (tbase < m->least_addr)
 49.3527 +          m->least_addr = tbase;
 49.3528 +        sp = &m->seg;
 49.3529 +        while (sp != 0 && sp->base != tbase + tsize)
 49.3530 +          sp = sp->next;
 49.3531 +        if (sp != 0 &&
 49.3532 +            !is_extern_segment(sp) &&
 49.3533 +            (sp->sflags & IS_MMAPPED_BIT) == mmap_flag) {
 49.3534 +          char* oldbase = sp->base;
 49.3535 +          sp->base = tbase;
 49.3536 +          sp->size += tsize;
 49.3537 +          return prepend_alloc(m, tbase, oldbase, nb);
 49.3538 +        }
 49.3539 +        else
 49.3540 +          add_segment(m, tbase, tsize, mmap_flag);
 49.3541 +      }
 49.3542 +    }
 49.3543 +
 49.3544 +    if (nb < m->topsize) { /* Allocate from new or extended top space */
 49.3545 +      size_t rsize = m->topsize -= nb;
 49.3546 +      mchunkptr p = m->top;
 49.3547 +      mchunkptr r = m->top = chunk_plus_offset(p, nb);
 49.3548 +      r->head = rsize | PINUSE_BIT;
 49.3549 +      set_size_and_pinuse_of_inuse_chunk(m, p, nb);
 49.3550 +      check_top_chunk(m, m->top);
 49.3551 +      check_malloced_chunk(m, chunk2mem(p), nb);
 49.3552 +      return chunk2mem(p);
 49.3553 +    }
 49.3554 +  }
 49.3555 +
 49.3556 +  MALLOC_FAILURE_ACTION;
 49.3557 +  return 0;
 49.3558 +}
 49.3559 +
 49.3560 +/* -----------------------  system deallocation -------------------------- */
 49.3561 +
 49.3562 +/* Unmap and unlink any mmapped segments that don't contain used chunks */
 49.3563 +static size_t release_unused_segments(mstate m) {
 49.3564 +  size_t released = 0;
 49.3565 +  msegmentptr pred = &m->seg;
 49.3566 +  msegmentptr sp = pred->next;
 49.3567 +  while (sp != 0) {
 49.3568 +    char* base = sp->base;
 49.3569 +    size_t size = sp->size;
 49.3570 +    msegmentptr next = sp->next;
 49.3571 +    if (is_mmapped_segment(sp) && !is_extern_segment(sp)) {
 49.3572 +      mchunkptr p = align_as_chunk(base);
 49.3573 +      size_t psize = chunksize(p);
 49.3574 +      /* Can unmap if first chunk holds entire segment and not pinned */
 49.3575 +      if (!cinuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) {
 49.3576 +        tchunkptr tp = (tchunkptr)p;
 49.3577 +        assert(segment_holds(sp, (char*)sp));
 49.3578 +        if (p == m->dv) {
 49.3579 +          m->dv = 0;
 49.3580 +          m->dvsize = 0;
 49.3581 +        }
 49.3582 +        else {
 49.3583 +          unlink_large_chunk(m, tp);
 49.3584 +        }
 49.3585 +        if (CALL_MUNMAP(base, size) == 0) {
 49.3586 +          released += size;
 49.3587 +          m->footprint -= size;
 49.3588 +          /* unlink obsoleted record */
 49.3589 +          sp = pred;
 49.3590 +          sp->next = next;
 49.3591 +        }
 49.3592 +        else { /* back out if cannot unmap */
 49.3593 +          insert_large_chunk(m, tp, psize);
 49.3594 +        }
 49.3595 +      }
 49.3596 +    }
 49.3597 +    pred = sp;
 49.3598 +    sp = next;
 49.3599 +  }
 49.3600 +  return released;
 49.3601 +}
 49.3602 +
 49.3603 +static int sys_trim(mstate m, size_t pad) {
 49.3604 +  size_t released = 0;
 49.3605 +  if (pad < MAX_REQUEST && is_initialized(m)) {
 49.3606 +    pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */
 49.3607 +
 49.3608 +    if (m->topsize > pad) {
 49.3609 +      /* Shrink top space in granularity-size units, keeping at least one */
 49.3610 +      size_t unit = mparams.granularity;
 49.3611 +      size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit -
 49.3612 +                      SIZE_T_ONE) * unit;
 49.3613 +      msegmentptr sp = segment_holding(m, (char*)m->top);
 49.3614 +
 49.3615 +      if (!is_extern_segment(sp)) {
 49.3616 +        if (is_mmapped_segment(sp)) {
 49.3617 +          if (HAVE_MMAP &&
 49.3618 +              sp->size >= extra &&
 49.3619 +              !has_segment_link(m, sp)) { /* can't shrink if pinned */
 49.3620 +            size_t newsize = sp->size - extra;
 49.3621 +            /* Prefer mremap, fall back to munmap */
 49.3622 +            if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) ||
 49.3623 +                (CALL_MUNMAP(sp->base + newsize, extra) == 0)) {
 49.3624 +              released = extra;
 49.3625 +            }
 49.3626 +          }
 49.3627 +        }
 49.3628 +        else if (HAVE_MORECORE) {
 49.3629 +          if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */
 49.3630 +            extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit;
 49.3631 +          ACQUIRE_MORECORE_LOCK();
 49.3632 +          {
 49.3633 +            /* Make sure end of memory is where we last set it. */
 49.3634 +            char* old_br = (char*)(CALL_MORECORE(0));
 49.3635 +            if (old_br == sp->base + sp->size) {
 49.3636 +              char* rel_br = (char*)(CALL_MORECORE(-extra));
 49.3637 +              char* new_br = (char*)(CALL_MORECORE(0));
 49.3638 +              if (rel_br != CMFAIL && new_br < old_br)
 49.3639 +                released = old_br - new_br;
 49.3640 +            }
 49.3641 +          }
 49.3642 +          RELEASE_MORECORE_LOCK();
 49.3643 +        }
 49.3644 +      }
 49.3645 +
 49.3646 +      if (released != 0) {
 49.3647 +        sp->size -= released;
 49.3648 +        m->footprint -= released;
 49.3649 +        init_top(m, m->top, m->topsize - released);
 49.3650 +        check_top_chunk(m, m->top);
 49.3651 +      }
 49.3652 +    }
 49.3653 +
 49.3654 +    /* Unmap any unused mmapped segments */
 49.3655 +    if (HAVE_MMAP) 
 49.3656 +      released += release_unused_segments(m);
 49.3657 +
 49.3658 +    /* On failure, disable autotrim to avoid repeated failed future calls */
 49.3659 +    if (released == 0)
 49.3660 +      m->trim_check = MAX_SIZE_T;
 49.3661 +  }
 49.3662 +
 49.3663 +  return (released != 0)? 1 : 0;
 49.3664 +}
 49.3665 +
 49.3666 +/* ---------------------------- malloc support --------------------------- */
 49.3667 +
 49.3668 +/* allocate a large request from the best fitting chunk in a treebin */
 49.3669 +static void* tmalloc_large(mstate m, size_t nb) {
 49.3670 +  tchunkptr v = 0;
 49.3671 +  size_t rsize = -nb; /* Unsigned negation */
 49.3672 +  tchunkptr t;
 49.3673 +  bindex_t idx;
 49.3674 +  compute_tree_index(nb, idx);
 49.3675 +
 49.3676 +  if ((t = *treebin_at(m, idx)) != 0) {
 49.3677 +    /* Traverse tree for this bin looking for node with size == nb */
 49.3678 +    size_t sizebits = nb << leftshift_for_tree_index(idx);
 49.3679 +    tchunkptr rst = 0;  /* The deepest untaken right subtree */
 49.3680 +    for (;;) {
 49.3681 +      tchunkptr rt;
 49.3682 +      size_t trem = chunksize(t) - nb;
 49.3683 +      if (trem < rsize) {
 49.3684 +        v = t;
 49.3685 +        if ((rsize = trem) == 0)
 49.3686 +          break;
 49.3687 +      }
 49.3688 +      rt = t->child[1];
 49.3689 +      t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
 49.3690 +      if (rt != 0 && rt != t)
 49.3691 +        rst = rt;
 49.3692 +      if (t == 0) {
 49.3693 +        t = rst; /* set t to least subtree holding sizes > nb */
 49.3694 +        break;
 49.3695 +      }
 49.3696 +      sizebits <<= 1;
 49.3697 +    }
 49.3698 +  }
 49.3699 +
 49.3700 +  if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */
 49.3701 +    binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap;
 49.3702 +    if (leftbits != 0) {
 49.3703 +      bindex_t i;
 49.3704 +      binmap_t leastbit = least_bit(leftbits);
 49.3705 +      compute_bit2idx(leastbit, i);
 49.3706 +      t = *treebin_at(m, i);
 49.3707 +    }
 49.3708 +  }
 49.3709 +
 49.3710 +  while (t != 0) { /* find smallest of tree or subtree */
 49.3711 +    size_t trem = chunksize(t) - nb;
 49.3712 +    if (trem < rsize) {
 49.3713 +      rsize = trem;
 49.3714 +      v = t;
 49.3715 +    }
 49.3716 +    t = leftmost_child(t);
 49.3717 +  }
 49.3718 +
 49.3719 +  /*  If dv is a better fit, return 0 so malloc will use it */
 49.3720 +  if (v != 0 && rsize < (size_t)(m->dvsize - nb)) {
 49.3721 +    if (RTCHECK(ok_address(m, v))) { /* split */
 49.3722 +      mchunkptr r = chunk_plus_offset(v, nb);
 49.3723 +      assert(chunksize(v) == rsize + nb);
 49.3724 +      if (RTCHECK(ok_next(v, r))) {
 49.3725 +        unlink_large_chunk(m, v);
 49.3726 +        if (rsize < MIN_CHUNK_SIZE)
 49.3727 +          set_inuse_and_pinuse(m, v, (rsize + nb));
 49.3728 +        else {
 49.3729 +          set_size_and_pinuse_of_inuse_chunk(m, v, nb);
 49.3730 +          set_size_and_pinuse_of_free_chunk(r, rsize);
 49.3731 +          insert_chunk(m, r, rsize);
 49.3732 +        }
 49.3733 +        return chunk2mem(v);
 49.3734 +      }
 49.3735 +    }
 49.3736 +    CORRUPTION_ERROR_ACTION(m);
 49.3737 +  }
 49.3738 +  return 0;
 49.3739 +}
 49.3740 +
 49.3741 +/* allocate a small request from the best fitting chunk in a treebin */
 49.3742 +static void* tmalloc_small(mstate m, size_t nb) {
 49.3743 +  tchunkptr t, v;
 49.3744 +  size_t rsize;
 49.3745 +  bindex_t i;
 49.3746 +  binmap_t leastbit = least_bit(m->treemap);
 49.3747 +  compute_bit2idx(leastbit, i);
 49.3748 +
 49.3749 +  v = t = *treebin_at(m, i);
 49.3750 +  rsize = chunksize(t) - nb;
 49.3751 +
 49.3752 +  while ((t = leftmost_child(t)) != 0) {
 49.3753 +    size_t trem = chunksize(t) - nb;
 49.3754 +    if (trem < rsize) {
 49.3755 +      rsize = trem;
 49.3756 +      v = t;
 49.3757 +    }
 49.3758 +  }
 49.3759 +
 49.3760 +  if (RTCHECK(ok_address(m, v))) {
 49.3761 +    mchunkptr r = chunk_plus_offset(v, nb);
 49.3762 +    assert(chunksize(v) == rsize + nb);
 49.3763 +    if (RTCHECK(ok_next(v, r))) {
 49.3764 +      unlink_large_chunk(m, v);
 49.3765 +      if (rsize < MIN_CHUNK_SIZE)
 49.3766 +        set_inuse_and_pinuse(m, v, (rsize + nb));
 49.3767 +      else {
 49.3768 +        set_size_and_pinuse_of_inuse_chunk(m, v, nb);
 49.3769 +        set_size_and_pinuse_of_free_chunk(r, rsize);
 49.3770 +        replace_dv(m, r, rsize);
 49.3771 +      }
 49.3772 +      return chunk2mem(v);
 49.3773 +    }
 49.3774 +  }
 49.3775 +
 49.3776 +  CORRUPTION_ERROR_ACTION(m);
 49.3777 +  return 0;
 49.3778 +}
 49.3779 +
 49.3780 +/* --------------------------- realloc support --------------------------- */
 49.3781 +
 49.3782 +static void* internal_realloc(mstate m, void* oldmem, size_t bytes) {
 49.3783 +  if (bytes >= MAX_REQUEST) {
 49.3784 +    MALLOC_FAILURE_ACTION;
 49.3785 +    return 0;
 49.3786 +  }
 49.3787 +  if (!PREACTION(m)) {
 49.3788 +    mchunkptr oldp = mem2chunk(oldmem);
 49.3789 +    size_t oldsize = chunksize(oldp);
 49.3790 +    mchunkptr next = chunk_plus_offset(oldp, oldsize);
 49.3791 +    mchunkptr newp = 0;
 49.3792 +    void* extra = 0;
 49.3793 +
 49.3794 +    /* Try to either shrink or extend into top. Else malloc-copy-free */
 49.3795 +
 49.3796 +    if (RTCHECK(ok_address(m, oldp) && ok_cinuse(oldp) &&
 49.3797 +                ok_next(oldp, next) && ok_pinuse(next))) {
 49.3798 +      size_t nb = request2size(bytes);
 49.3799 +      if (is_mmapped(oldp))
 49.3800 +        newp = mmap_resize(m, oldp, nb);
 49.3801 +      else if (oldsize >= nb) { /* already big enough */
 49.3802 +        size_t rsize = oldsize - nb;
 49.3803 +        newp = oldp;
 49.3804 +        if (rsize >= MIN_CHUNK_SIZE) {
 49.3805 +          mchunkptr remainder = chunk_plus_offset(newp, nb);
 49.3806 +          set_inuse(m, newp, nb);
 49.3807 +          set_inuse(m, remainder, rsize);
 49.3808 +          extra = chunk2mem(remainder);
 49.3809 +        }
 49.3810 +      }
 49.3811 +      else if (next == m->top && oldsize + m->topsize > nb) {
 49.3812 +        /* Expand into top */
 49.3813 +        size_t newsize = oldsize + m->topsize;
 49.3814 +        size_t newtopsize = newsize - nb;
 49.3815 +        mchunkptr newtop = chunk_plus_offset(oldp, nb);
 49.3816 +        set_inuse(m, oldp, nb);
 49.3817 +        newtop->head = newtopsize |PINUSE_BIT;
 49.3818 +        m->top = newtop;
 49.3819 +        m->topsize = newtopsize;
 49.3820 +        newp = oldp;
 49.3821 +      }
 49.3822 +    }
 49.3823 +    else {
 49.3824 +      USAGE_ERROR_ACTION(m, oldmem);
 49.3825 +      POSTACTION(m);
 49.3826 +      return 0;
 49.3827 +    }
 49.3828 +
 49.3829 +    POSTACTION(m);
 49.3830 +
 49.3831 +    if (newp != 0) {
 49.3832 +      if (extra != 0) {
 49.3833 +        internal_free(m, extra);
 49.3834 +      }
 49.3835 +      check_inuse_chunk(m, newp);
 49.3836 +      return chunk2mem(newp);
 49.3837 +    }
 49.3838 +    else {
 49.3839 +      void* newmem = internal_malloc(m, bytes);
 49.3840 +      if (newmem != 0) {
 49.3841 +        size_t oc = oldsize - overhead_for(oldp);
 49.3842 +        memcpy(newmem, oldmem, (oc < bytes)? oc : bytes);
 49.3843 +        internal_free(m, oldmem);
 49.3844 +      }
 49.3845 +      return newmem;
 49.3846 +    }
 49.3847 +  }
 49.3848 +  return 0;
 49.3849 +}
 49.3850 +
 49.3851 +/* --------------------------- memalign support -------------------------- */
 49.3852 +
 49.3853 +static void* internal_memalign(mstate m, size_t alignment, size_t bytes) {
 49.3854 +  if (alignment <= MALLOC_ALIGNMENT)    /* Can just use malloc */
 49.3855 +    return internal_malloc(m, bytes);
 49.3856 +  if (alignment <  MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */
 49.3857 +    alignment = MIN_CHUNK_SIZE;
 49.3858 +  if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */
 49.3859 +    size_t a = MALLOC_ALIGNMENT << 1;
 49.3860 +    while (a < alignment) a <<= 1;
 49.3861 +    alignment = a;
 49.3862 +  }
 49.3863 +  
 49.3864 +  if (bytes >= MAX_REQUEST - alignment) {
 49.3865 +    if (m != 0)  { /* Test isn't needed but avoids compiler warning */
 49.3866 +      MALLOC_FAILURE_ACTION;
 49.3867 +    }
 49.3868 +  }
 49.3869 +  else {
 49.3870 +    size_t nb = request2size(bytes);
 49.3871 +    size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD;
 49.3872 +    char* mem = (char*)internal_malloc(m, req);
 49.3873 +    if (mem != 0) {
 49.3874 +      void* leader = 0;
 49.3875 +      void* trailer = 0;
 49.3876 +      mchunkptr p = mem2chunk(mem);
 49.3877 +
 49.3878 +      if (PREACTION(m)) return 0;
 49.3879 +      if ((((size_t)(mem)) % alignment) != 0) { /* misaligned */
 49.3880 +        /*
 49.3881 +          Find an aligned spot inside chunk.  Since we need to give
 49.3882 +          back leading space in a chunk of at least MIN_CHUNK_SIZE, if
 49.3883 +          the first calculation places us at a spot with less than
 49.3884 +          MIN_CHUNK_SIZE leader, we can move to the next aligned spot.
 49.3885 +          We've allocated enough total room so that this is always
 49.3886 +          possible.
 49.3887 +        */
 49.3888 +        char* br = (char*)mem2chunk((size_t)(((size_t)(mem +
 49.3889 +                                                       alignment -
 49.3890 +                                                       SIZE_T_ONE)) &
 49.3891 +                                             -alignment));
 49.3892 +        char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)?
 49.3893 +          br : br+alignment;
 49.3894 +        mchunkptr newp = (mchunkptr)pos;
 49.3895 +        size_t leadsize = pos - (char*)(p);
 49.3896 +        size_t newsize = chunksize(p) - leadsize;
 49.3897 +
 49.3898 +        if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */
 49.3899 +          newp->prev_foot = p->prev_foot + leadsize;
 49.3900 +          newp->head = (newsize|CINUSE_BIT);
 49.3901 +        }
 49.3902 +        else { /* Otherwise, give back leader, use the rest */
 49.3903 +          set_inuse(m, newp, newsize);
 49.3904 +          set_inuse(m, p, leadsize);
 49.3905 +          leader = chunk2mem(p);
 49.3906 +        }
 49.3907 +        p = newp;
 49.3908 +      }
 49.3909 +
 49.3910 +      /* Give back spare room at the end */
 49.3911 +      if (!is_mmapped(p)) {
 49.3912 +        size_t size = chunksize(p);
 49.3913 +        if (size > nb + MIN_CHUNK_SIZE) {
 49.3914 +          size_t remainder_size = size - nb;
 49.3915 +          mchunkptr remainder = chunk_plus_offset(p, nb);
 49.3916 +          set_inuse(m, p, nb);
 49.3917 +          set_inuse(m, remainder, remainder_size);
 49.3918 +          trailer = chunk2mem(remainder);
 49.3919 +        }
 49.3920 +      }
 49.3921 +
 49.3922 +      assert (chunksize(p) >= nb);
 49.3923 +      assert((((size_t)(chunk2mem(p))) % alignment) == 0);
 49.3924 +      check_inuse_chunk(m, p);
 49.3925 +      POSTACTION(m);
 49.3926 +      if (leader != 0) {
 49.3927 +        internal_free(m, leader);
 49.3928 +      }
 49.3929 +      if (trailer != 0) {
 49.3930 +        internal_free(m, trailer);
 49.3931 +      }
 49.3932 +      return chunk2mem(p);
 49.3933 +    }
 49.3934 +  }
 49.3935 +  return 0;
 49.3936 +}
 49.3937 +
 49.3938 +/* ------------------------ comalloc/coalloc support --------------------- */
 49.3939 +
 49.3940 +static void** ialloc(mstate m,
 49.3941 +                     size_t n_elements,
 49.3942 +                     size_t* sizes,
 49.3943 +                     int opts,
 49.3944 +                     void* chunks[]) {
 49.3945 +  /*
 49.3946 +    This provides common support for independent_X routines, handling
 49.3947 +    all of the combinations that can result.
 49.3948 +
 49.3949 +    The opts arg has:
 49.3950 +    bit 0 set if all elements are same size (using sizes[0])
 49.3951 +    bit 1 set if elements should be zeroed
 49.3952 +  */
 49.3953 +
 49.3954 +  size_t    element_size;   /* chunksize of each element, if all same */
 49.3955 +  size_t    contents_size;  /* total size of elements */
 49.3956 +  size_t    array_size;     /* request size of pointer array */
 49.3957 +  void*     mem;            /* malloced aggregate space */
 49.3958 +  mchunkptr p;              /* corresponding chunk */
 49.3959 +  size_t    remainder_size; /* remaining bytes while splitting */
 49.3960 +  void**    marray;         /* either "chunks" or malloced ptr array */
 49.3961 +  mchunkptr array_chunk;    /* chunk for malloced ptr array */
 49.3962 +  flag_t    was_enabled;    /* to disable mmap */
 49.3963 +  size_t    size;
 49.3964 +  size_t    i;
 49.3965 +
 49.3966 +  /* compute array length, if needed */
 49.3967 +  if (chunks != 0) {
 49.3968 +    if (n_elements == 0)
 49.3969 +      return chunks; /* nothing to do */
 49.3970 +    marray = chunks;
 49.3971 +    array_size = 0;
 49.3972 +  }
 49.3973 +  else {
 49.3974 +    /* if empty req, must still return chunk representing empty array */
 49.3975 +    if (n_elements == 0)
 49.3976 +      return (void**)internal_malloc(m, 0);
 49.3977 +    marray = 0;
 49.3978 +    array_size = request2size(n_elements * (sizeof(void*)));
 49.3979 +  }
 49.3980 +
 49.3981 +  /* compute total element size */
 49.3982 +  if (opts & 0x1) { /* all-same-size */
 49.3983 +    element_size = request2size(*sizes);
 49.3984 +    contents_size = n_elements * element_size;
 49.3985 +  }
 49.3986 +  else { /* add up all the sizes */
 49.3987 +    element_size = 0;
 49.3988 +    contents_size = 0;
 49.3989 +    for (i = 0; i != n_elements; ++i)
 49.3990 +      contents_size += request2size(sizes[i]);
 49.3991 +  }
 49.3992 +
 49.3993 +  size = contents_size + array_size;
 49.3994 +
 49.3995 +  /*
 49.3996 +     Allocate the aggregate chunk.  First disable direct-mmapping so
 49.3997 +     malloc won't use it, since we would not be able to later
 49.3998 +     free/realloc space internal to a segregated mmap region.
 49.3999 +  */
 49.4000 +  was_enabled = use_mmap(m);
 49.4001 +  disable_mmap(m);
 49.4002 +  mem = internal_malloc(m, size - CHUNK_OVERHEAD);
 49.4003 +  if (was_enabled)
 49.4004 +    enable_mmap(m);
 49.4005 +  if (mem == 0)
 49.4006 +    return 0;
 49.4007 +
 49.4008 +  if (PREACTION(m)) return 0;
 49.4009 +  p = mem2chunk(mem);
 49.4010 +  remainder_size = chunksize(p);
 49.4011 +
 49.4012 +  assert(!is_mmapped(p));
 49.4013 +
 49.4014 +  if (opts & 0x2) {       /* optionally clear the elements */
 49.4015 +    memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size);
 49.4016 +  }
 49.4017 +
 49.4018 +  /* If not provided, allocate the pointer array as final part of chunk */
 49.4019 +  if (marray == 0) {
 49.4020 +    size_t  array_chunk_size;
 49.4021 +    array_chunk = chunk_plus_offset(p, contents_size);
 49.4022 +    array_chunk_size = remainder_size - contents_size;
 49.4023 +    marray = (void**) (chunk2mem(array_chunk));
 49.4024 +    set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size);
 49.4025 +    remainder_size = contents_size;
 49.4026 +  }
 49.4027 +
 49.4028 +  /* split out elements */
 49.4029 +  for (i = 0; ; ++i) {
 49.4030 +    marray[i] = chunk2mem(p);
 49.4031 +    if (i != n_elements-1) {
 49.4032 +      if (element_size != 0)
 49.4033 +        size = element_size;
 49.4034 +      else
 49.4035 +        size = request2size(sizes[i]);
 49.4036 +      remainder_size -= size;
 49.4037 +      set_size_and_pinuse_of_inuse_chunk(m, p, size);
 49.4038 +      p = chunk_plus_offset(p, size);
 49.4039 +    }
 49.4040 +    else { /* the final element absorbs any overallocation slop */
 49.4041 +      set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size);
 49.4042 +      break;
 49.4043 +    }
 49.4044 +  }
 49.4045 +
 49.4046 +#if DEBUG
 49.4047 +  if (marray != chunks) {
 49.4048 +    /* final element must have exactly exhausted chunk */
 49.4049 +    if (element_size != 0) {
 49.4050 +      assert(remainder_size == element_size);
 49.4051 +    }
 49.4052 +    else {
 49.4053 +      assert(remainder_size == request2size(sizes[i]));
 49.4054 +    }
 49.4055 +    check_inuse_chunk(m, mem2chunk(marray));
 49.4056 +  }
 49.4057 +  for (i = 0; i != n_elements; ++i)
 49.4058 +    check_inuse_chunk(m, mem2chunk(marray[i]));
 49.4059 +
 49.4060 +#endif /* DEBUG */
 49.4061 +
 49.4062 +  POSTACTION(m);
 49.4063 +  return marray;
 49.4064 +}
 49.4065 +
 49.4066 +
 49.4067 +/* -------------------------- public routines ---------------------------- */
 49.4068 +
 49.4069 +#if !ONLY_MSPACES
 49.4070 +
 49.4071 +void* dlmalloc(size_t bytes) {
 49.4072 +  /*
 49.4073 +     Basic algorithm:
 49.4074 +     If a small request (< 256 bytes minus per-chunk overhead):
 49.4075 +       1. If one exists, use a remainderless chunk in associated smallbin.
 49.4076 +          (Remainderless means that there are too few excess bytes to
 49.4077 +          represent as a chunk.)
 49.4078 +       2. If it is big enough, use the dv chunk, which is normally the
 49.4079 +          chunk adjacent to the one used for the most recent small request.
 49.4080 +       3. If one exists, split the smallest available chunk in a bin,
 49.4081 +          saving remainder in dv.
 49.4082 +       4. If it is big enough, use the top chunk.
 49.4083 +       5. If available, get memory from system and use it
 49.4084 +     Otherwise, for a large request:
 49.4085 +       1. Find the smallest available binned chunk that fits, and use it
 49.4086 +          if it is better fitting than dv chunk, splitting if necessary.
 49.4087 +       2. If better fitting than any binned chunk, use the dv chunk.
 49.4088 +       3. If it is big enough, use the top chunk.
 49.4089 +       4. If request size >= mmap threshold, try to directly mmap this chunk.
 49.4090 +       5. If available, get memory from system and use it
 49.4091 +
 49.4092 +     The ugly goto's here ensure that postaction occurs along all paths.
 49.4093 +  */
 49.4094 +
 49.4095 +  if (!PREACTION(gm)) {
 49.4096 +    void* mem;
 49.4097 +    size_t nb;
 49.4098 +    if (bytes <= MAX_SMALL_REQUEST) {
 49.4099 +      bindex_t idx;
 49.4100 +      binmap_t smallbits;
 49.4101 +      nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
 49.4102 +      idx = small_index(nb);
 49.4103 +      smallbits = gm->smallmap >> idx;
 49.4104 +
 49.4105 +      if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
 49.4106 +        mchunkptr b, p;
 49.4107 +        idx += ~smallbits & 1;       /* Uses next bin if idx empty */
 49.4108 +        b = smallbin_at(gm, idx);
 49.4109 +        p = b->fd;
 49.4110 +        assert(chunksize(p) == small_index2size(idx));
 49.4111 +        unlink_first_small_chunk(gm, b, p, idx);
 49.4112 +        set_inuse_and_pinuse(gm, p, small_index2size(idx));
 49.4113 +        mem = chunk2mem(p);
 49.4114 +        check_malloced_chunk(gm, mem, nb);
 49.4115 +        goto postaction;
 49.4116 +      }
 49.4117 +
 49.4118 +      else if (nb > gm->dvsize) {
 49.4119 +        if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
 49.4120 +          mchunkptr b, p, r;
 49.4121 +          size_t rsize;
 49.4122 +          bindex_t i;
 49.4123 +          binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
 49.4124 +          binmap_t leastbit = least_bit(leftbits);
 49.4125 +          compute_bit2idx(leastbit, i);
 49.4126 +          b = smallbin_at(gm, i);
 49.4127 +          p = b->fd;
 49.4128 +          assert(chunksize(p) == small_index2size(i));
 49.4129 +          unlink_first_small_chunk(gm, b, p, i);
 49.4130 +          rsize = small_index2size(i) - nb;
 49.4131 +          /* Fit here cannot be remainderless if 4byte sizes */
 49.4132 +          if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
 49.4133 +            set_inuse_and_pinuse(gm, p, small_index2size(i));
 49.4134 +          else {
 49.4135 +            set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
 49.4136 +            r = chunk_plus_offset(p, nb);
 49.4137 +            set_size_and_pinuse_of_free_chunk(r, rsize);
 49.4138 +            replace_dv(gm, r, rsize);
 49.4139 +          }
 49.4140 +          mem = chunk2mem(p);
 49.4141 +          check_malloced_chunk(gm, mem, nb);
 49.4142 +          goto postaction;
 49.4143 +        }
 49.4144 +
 49.4145 +        else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) {
 49.4146 +          check_malloced_chunk(gm, mem, nb);
 49.4147 +          goto postaction;
 49.4148 +        }
 49.4149 +      }
 49.4150 +    }
 49.4151 +    else if (bytes >= MAX_REQUEST)
 49.4152 +      nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
 49.4153 +    else {
 49.4154 +      nb = pad_request(bytes);
 49.4155 +      if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) {
 49.4156 +        check_malloced_chunk(gm, mem, nb);
 49.4157 +        goto postaction;
 49.4158 +      }
 49.4159 +    }
 49.4160 +
 49.4161 +    if (nb <= gm->dvsize) {
 49.4162 +      size_t rsize = gm->dvsize - nb;
 49.4163 +      mchunkptr p = gm->dv;
 49.4164 +      if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
 49.4165 +        mchunkptr r = gm->dv = chunk_plus_offset(p, nb);
 49.4166 +        gm->dvsize = rsize;
 49.4167 +        set_size_and_pinuse_of_free_chunk(r, rsize);
 49.4168 +        set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
 49.4169 +      }
 49.4170 +      else { /* exhaust dv */
 49.4171 +        size_t dvs = gm->dvsize;
 49.4172 +        gm->dvsize = 0;
 49.4173 +        gm->dv = 0;
 49.4174 +        set_inuse_and_pinuse(gm, p, dvs);
 49.4175 +      }
 49.4176 +      mem = chunk2mem(p);
 49.4177 +      check_malloced_chunk(gm, mem, nb);
 49.4178 +      goto postaction;
 49.4179 +    }
 49.4180 +
 49.4181 +    else if (nb < gm->topsize) { /* Split top */
 49.4182 +      size_t rsize = gm->topsize -= nb;
 49.4183 +      mchunkptr p = gm->top;
 49.4184 +      mchunkptr r = gm->top = chunk_plus_offset(p, nb);
 49.4185 +      r->head = rsize | PINUSE_BIT;
 49.4186 +      set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
 49.4187 +      mem = chunk2mem(p);
 49.4188 +      check_top_chunk(gm, gm->top);
 49.4189 +      check_malloced_chunk(gm, mem, nb);
 49.4190 +      goto postaction;
 49.4191 +    }
 49.4192 +
 49.4193 +    mem = sys_alloc(gm, nb);
 49.4194 +
 49.4195 +  postaction:
 49.4196 +    POSTACTION(gm);
 49.4197 +    return mem;
 49.4198 +  }
 49.4199 +
 49.4200 +  return 0;
 49.4201 +}
 49.4202 +
 49.4203 +void dlfree(void* mem) {
 49.4204 +  /*
 49.4205 +     Consolidate freed chunks with preceeding or succeeding bordering
 49.4206 +     free chunks, if they exist, and then place in a bin.  Intermixed
 49.4207 +     with special cases for top, dv, mmapped chunks, and usage errors.
 49.4208 +  */
 49.4209 +
 49.4210 +  if (mem != 0) {
 49.4211 +    mchunkptr p  = mem2chunk(mem);
 49.4212 +#if FOOTERS
 49.4213 +    mstate fm = get_mstate_for(p);
 49.4214 +    if (!ok_magic(fm)) {
 49.4215 +      USAGE_ERROR_ACTION(fm, p);
 49.4216 +      return;
 49.4217 +    }
 49.4218 +#else /* FOOTERS */
 49.4219 +#define fm gm
 49.4220 +#endif /* FOOTERS */
 49.4221 +    if (!PREACTION(fm)) {
 49.4222 +      check_inuse_chunk(fm, p);
 49.4223 +      if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) {
 49.4224 +        size_t psize = chunksize(p);
 49.4225 +        mchunkptr next = chunk_plus_offset(p, psize);
 49.4226 +        if (!pinuse(p)) {
 49.4227 +          size_t prevsize = p->prev_foot;
 49.4228 +          if ((prevsize & IS_MMAPPED_BIT) != 0) {
 49.4229 +            prevsize &= ~IS_MMAPPED_BIT;
 49.4230 +            psize += prevsize + MMAP_FOOT_PAD;
 49.4231 +            if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
 49.4232 +              fm->footprint -= psize;
 49.4233 +            goto postaction;
 49.4234 +          }
 49.4235 +          else {
 49.4236 +            mchunkptr prev = chunk_minus_offset(p, prevsize);
 49.4237 +            psize += prevsize;
 49.4238 +            p = prev;
 49.4239 +            if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
 49.4240 +              if (p != fm->dv) {
 49.4241 +                unlink_chunk(fm, p, prevsize);
 49.4242 +              }
 49.4243 +              else if ((next->head & INUSE_BITS) == INUSE_BITS) {
 49.4244 +                fm->dvsize = psize;
 49.4245 +                set_free_with_pinuse(p, psize, next);
 49.4246 +                goto postaction;
 49.4247 +              }
 49.4248 +            }
 49.4249 +            else
 49.4250 +              goto erroraction;
 49.4251 +          }
 49.4252 +        }
 49.4253 +
 49.4254 +        if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
 49.4255 +          if (!cinuse(next)) {  /* consolidate forward */
 49.4256 +            if (next == fm->top) {
 49.4257 +              size_t tsize = fm->topsize += psize;
 49.4258 +              fm->top = p;
 49.4259 +              p->head = tsize | PINUSE_BIT;
 49.4260 +              if (p == fm->dv) {
 49.4261 +                fm->dv = 0;
 49.4262 +                fm->dvsize = 0;
 49.4263 +              }
 49.4264 +              if (should_trim(fm, tsize))
 49.4265 +                sys_trim(fm, 0);
 49.4266 +              goto postaction;
 49.4267 +            }
 49.4268 +            else if (next == fm->dv) {
 49.4269 +              size_t dsize = fm->dvsize += psize;
 49.4270 +              fm->dv = p;
 49.4271 +              set_size_and_pinuse_of_free_chunk(p, dsize);
 49.4272 +              goto postaction;
 49.4273 +            }
 49.4274 +            else {
 49.4275 +              size_t nsize = chunksize(next);
 49.4276 +              psize += nsize;
 49.4277 +              unlink_chunk(fm, next, nsize);
 49.4278 +              set_size_and_pinuse_of_free_chunk(p, psize);
 49.4279 +              if (p == fm->dv) {
 49.4280 +                fm->dvsize = psize;
 49.4281 +                goto postaction;
 49.4282 +              }
 49.4283 +            }
 49.4284 +          }
 49.4285 +          else
 49.4286 +            set_free_with_pinuse(p, psize, next);
 49.4287 +          insert_chunk(fm, p, psize);
 49.4288 +          check_free_chunk(fm, p);
 49.4289 +          goto postaction;
 49.4290 +        }
 49.4291 +      }
 49.4292 +    erroraction:
 49.4293 +      USAGE_ERROR_ACTION(fm, p);
 49.4294 +    postaction:
 49.4295 +      POSTACTION(fm);
 49.4296 +    }
 49.4297 +  }
 49.4298 +#if !FOOTERS
 49.4299 +#undef fm
 49.4300 +#endif /* FOOTERS */
 49.4301 +}
 49.4302 +
 49.4303 +void* dlcalloc(size_t n_elements, size_t elem_size) {
 49.4304 +  void* mem;
 49.4305 +  size_t req = 0;
 49.4306 +  if (n_elements != 0) {
 49.4307 +    req = n_elements * elem_size;
 49.4308 +    if (((n_elements | elem_size) & ~(size_t)0xffff) &&
 49.4309 +        (req / n_elements != elem_size))
 49.4310 +      req = MAX_SIZE_T; /* force downstream failure on overflow */
 49.4311 +  }
 49.4312 +  mem = dlmalloc(req);
 49.4313 +  if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
 49.4314 +    memset(mem, 0, req);
 49.4315 +  return mem;
 49.4316 +}
 49.4317 +
 49.4318 +void* dlrealloc(void* oldmem, size_t bytes) {
 49.4319 +  if (oldmem == 0)
 49.4320 +    return dlmalloc(bytes);
 49.4321 +#ifdef REALLOC_ZERO_BYTES_FREES
 49.4322 +  if (bytes == 0) {
 49.4323 +    dlfree(oldmem);
 49.4324 +    return 0;
 49.4325 +  }
 49.4326 +#endif /* REALLOC_ZERO_BYTES_FREES */
 49.4327 +  else {
 49.4328 +#if ! FOOTERS
 49.4329 +    mstate m = gm;
 49.4330 +#else /* FOOTERS */
 49.4331 +    mstate m = get_mstate_for(mem2chunk(oldmem));
 49.4332 +    if (!ok_magic(m)) {
 49.4333 +      USAGE_ERROR_ACTION(m, oldmem);
 49.4334 +      return 0;
 49.4335 +    }
 49.4336 +#endif /* FOOTERS */
 49.4337 +    return internal_realloc(m, oldmem, bytes);
 49.4338 +  }
 49.4339 +}
 49.4340 +
 49.4341 +void* dlmemalign(size_t alignment, size_t bytes) {
 49.4342 +  return internal_memalign(gm, alignment, bytes);
 49.4343 +}
 49.4344 +
 49.4345 +void** dlindependent_calloc(size_t n_elements, size_t elem_size,
 49.4346 +                                 void* chunks[]) {
 49.4347 +  size_t sz = elem_size; /* serves as 1-element array */
 49.4348 +  return ialloc(gm, n_elements, &sz, 3, chunks);
 49.4349 +}
 49.4350 +
 49.4351 +void** dlindependent_comalloc(size_t n_elements, size_t sizes[],
 49.4352 +                                   void* chunks[]) {
 49.4353 +  return ialloc(gm, n_elements, sizes, 0, chunks);
 49.4354 +}
 49.4355 +
 49.4356 +void* dlvalloc(size_t bytes) {
 49.4357 +  size_t pagesz;
 49.4358 +  init_mparams();
 49.4359 +  pagesz = mparams.page_size;
 49.4360 +  return dlmemalign(pagesz, bytes);
 49.4361 +}
 49.4362 +
 49.4363 +void* dlpvalloc(size_t bytes) {
 49.4364 +  size_t pagesz;
 49.4365 +  init_mparams();
 49.4366 +  pagesz = mparams.page_size;
 49.4367 +  return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE));
 49.4368 +}
 49.4369 +
 49.4370 +int dlmalloc_trim(size_t pad) {
 49.4371 +  int result = 0;
 49.4372 +  if (!PREACTION(gm)) {
 49.4373 +    result = sys_trim(gm, pad);
 49.4374 +    POSTACTION(gm);
 49.4375 +  }
 49.4376 +  return result;
 49.4377 +}
 49.4378 +
 49.4379 +size_t dlmalloc_footprint(void) {
 49.4380 +  return gm->footprint;
 49.4381 +}
 49.4382 +
 49.4383 +size_t dlmalloc_max_footprint(void) {
 49.4384 +  return gm->max_footprint;
 49.4385 +}
 49.4386 +
 49.4387 +#if !NO_MALLINFO
 49.4388 +struct mallinfo dlmallinfo(void) {
 49.4389 +  return internal_mallinfo(gm);
 49.4390 +}
 49.4391 +#endif /* NO_MALLINFO */
 49.4392 +
 49.4393 +void dlmalloc_stats() {
 49.4394 +  internal_malloc_stats(gm);
 49.4395 +}
 49.4396 +
 49.4397 +size_t dlmalloc_usable_size(void* mem) {
 49.4398 +  if (mem != 0) {
 49.4399 +    mchunkptr p = mem2chunk(mem);
 49.4400 +    if (cinuse(p))
 49.4401 +      return chunksize(p) - overhead_for(p);
 49.4402 +  }
 49.4403 +  return 0;
 49.4404 +}
 49.4405 +
 49.4406 +int dlmallopt(int param_number, int value) {
 49.4407 +  return change_mparam(param_number, value);
 49.4408 +}
 49.4409 +
 49.4410 +#endif /* !ONLY_MSPACES */
 49.4411 +
 49.4412 +/* ----------------------------- user mspaces ---------------------------- */
 49.4413 +
 49.4414 +#if MSPACES
 49.4415 +
 49.4416 +static mstate init_user_mstate(char* tbase, size_t tsize) {
 49.4417 +  size_t msize = pad_request(sizeof(struct malloc_state));
 49.4418 +  mchunkptr mn;
 49.4419 +  mchunkptr msp = align_as_chunk(tbase);
 49.4420 +  mstate m = (mstate)(chunk2mem(msp));
 49.4421 +  memset(m, 0, msize);
 49.4422 +  INITIAL_LOCK(&m->mutex);
 49.4423 +  msp->head = (msize|PINUSE_BIT|CINUSE_BIT);
 49.4424 +  m->seg.base = m->least_addr = tbase;
 49.4425 +  m->seg.size = m->footprint = m->max_footprint = tsize;
 49.4426 +  m->magic = mparams.magic;
 49.4427 +  m->mflags = mparams.default_mflags;
 49.4428 +  disable_contiguous(m);
 49.4429 +  init_bins(m);
 49.4430 +  mn = next_chunk(mem2chunk(m));
 49.4431 +  init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE);
 49.4432 +  check_top_chunk(m, m->top);
 49.4433 +  return m;
 49.4434 +}
 49.4435 +
 49.4436 +mspace create_mspace(size_t capacity, int locked) {
 49.4437 +  mstate m = 0;
 49.4438 +  size_t msize = pad_request(sizeof(struct malloc_state));
 49.4439 +  init_mparams(); /* Ensure pagesize etc initialized */
 49.4440 +
 49.4441 +  if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
 49.4442 +    size_t rs = ((capacity == 0)? mparams.granularity :
 49.4443 +                 (capacity + TOP_FOOT_SIZE + msize));
 49.4444 +    size_t tsize = granularity_align(rs);
 49.4445 +    char* tbase = (char*)(CALL_MMAP(tsize));
 49.4446 +    if (tbase != CMFAIL) {
 49.4447 +      m = init_user_mstate(tbase, tsize);
 49.4448 +      m->seg.sflags = IS_MMAPPED_BIT;
 49.4449 +      set_lock(m, locked);
 49.4450 +    }
 49.4451 +  }
 49.4452 +  return (mspace)m;
 49.4453 +}
 49.4454 +
 49.4455 +mspace create_mspace_with_base(void* base, size_t capacity, int locked) {
 49.4456 +  mstate m = 0;
 49.4457 +  size_t msize = pad_request(sizeof(struct malloc_state));
 49.4458 +  init_mparams(); /* Ensure pagesize etc initialized */
 49.4459 +
 49.4460 +  if (capacity > msize + TOP_FOOT_SIZE &&
 49.4461 +      capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
 49.4462 +    m = init_user_mstate((char*)base, capacity);
 49.4463 +    m->seg.sflags = EXTERN_BIT;
 49.4464 +    set_lock(m, locked);
 49.4465 +  }
 49.4466 +  return (mspace)m;
 49.4467 +}
 49.4468 +
 49.4469 +size_t destroy_mspace(mspace msp) {
 49.4470 +  size_t freed = 0;
 49.4471 +  mstate ms = (mstate)msp;
 49.4472 +  if (ok_magic(ms)) {
 49.4473 +    msegmentptr sp = &ms->seg;
 49.4474 +    while (sp != 0) {
 49.4475 +      char* base = sp->base;
 49.4476 +      size_t size = sp->size;
 49.4477 +      flag_t flag = sp->sflags;
 49.4478 +      sp = sp->next;
 49.4479 +      if ((flag & IS_MMAPPED_BIT) && !(flag & EXTERN_BIT) &&
 49.4480 +          CALL_MUNMAP(base, size) == 0)
 49.4481 +        freed += size;
 49.4482 +    }
 49.4483 +  }
 49.4484 +  else {
 49.4485 +    USAGE_ERROR_ACTION(ms,ms);
 49.4486 +  }
 49.4487 +  return freed;
 49.4488 +}
 49.4489 +
 49.4490 +/*
 49.4491 +  mspace versions of routines are near-clones of the global
 49.4492 +  versions. This is not so nice but better than the alternatives.
 49.4493 +*/
 49.4494 +
 49.4495 +
 49.4496 +void* mspace_malloc(mspace msp, size_t bytes) {
 49.4497 +  mstate ms = (mstate)msp;
 49.4498 +  if (!ok_magic(ms)) {
 49.4499 +    USAGE_ERROR_ACTION(ms,ms);
 49.4500 +    return 0;
 49.4501 +  }
 49.4502 +  if (!PREACTION(ms)) {
 49.4503 +    void* mem;
 49.4504 +    size_t nb;
 49.4505 +    if (bytes <= MAX_SMALL_REQUEST) {
 49.4506 +      bindex_t idx;
 49.4507 +      binmap_t smallbits;
 49.4508 +      nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
 49.4509 +      idx = small_index(nb);
 49.4510 +      smallbits = ms->smallmap >> idx;
 49.4511 +
 49.4512 +      if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
 49.4513 +        mchunkptr b, p;
 49.4514 +        idx += ~smallbits & 1;       /* Uses next bin if idx empty */
 49.4515 +        b = smallbin_at(ms, idx);
 49.4516 +        p = b->fd;
 49.4517 +        assert(chunksize(p) == small_index2size(idx));
 49.4518 +        unlink_first_small_chunk(ms, b, p, idx);
 49.4519 +        set_inuse_and_pinuse(ms, p, small_index2size(idx));
 49.4520 +        mem = chunk2mem(p);
 49.4521 +        check_malloced_chunk(ms, mem, nb);
 49.4522 +        goto postaction;
 49.4523 +      }
 49.4524 +
 49.4525 +      else if (nb > ms->dvsize) {
 49.4526 +        if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
 49.4527 +          mchunkptr b, p, r;
 49.4528 +          size_t rsize;
 49.4529 +          bindex_t i;
 49.4530 +          binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
 49.4531 +          binmap_t leastbit = least_bit(leftbits);
 49.4532 +          compute_bit2idx(leastbit, i);
 49.4533 +          b = smallbin_at(ms, i);
 49.4534 +          p = b->fd;
 49.4535 +          assert(chunksize(p) == small_index2size(i));
 49.4536 +          unlink_first_small_chunk(ms, b, p, i);
 49.4537 +          rsize = small_index2size(i) - nb;
 49.4538 +          /* Fit here cannot be remainderless if 4byte sizes */
 49.4539 +          if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
 49.4540 +            set_inuse_and_pinuse(ms, p, small_index2size(i));
 49.4541 +          else {
 49.4542 +            set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
 49.4543 +            r = chunk_plus_offset(p, nb);
 49.4544 +            set_size_and_pinuse_of_free_chunk(r, rsize);
 49.4545 +            replace_dv(ms, r, rsize);
 49.4546 +          }
 49.4547 +          mem = chunk2mem(p);
 49.4548 +          check_malloced_chunk(ms, mem, nb);
 49.4549 +          goto postaction;
 49.4550 +        }
 49.4551 +
 49.4552 +        else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) {
 49.4553 +          check_malloced_chunk(ms, mem, nb);
 49.4554 +          goto postaction;
 49.4555 +        }
 49.4556 +      }
 49.4557 +    }
 49.4558 +    else if (bytes >= MAX_REQUEST)
 49.4559 +      nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
 49.4560 +    else {
 49.4561 +      nb = pad_request(bytes);
 49.4562 +      if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) {
 49.4563 +        check_malloced_chunk(ms, mem, nb);
 49.4564 +        goto postaction;
 49.4565 +      }
 49.4566 +    }
 49.4567 +
 49.4568 +    if (nb <= ms->dvsize) {
 49.4569 +      size_t rsize = ms->dvsize - nb;
 49.4570 +      mchunkptr p = ms->dv;
 49.4571 +      if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
 49.4572 +        mchunkptr r = ms->dv = chunk_plus_offset(p, nb);
 49.4573 +        ms->dvsize = rsize;
 49.4574 +        set_size_and_pinuse_of_free_chunk(r, rsize);
 49.4575 +        set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
 49.4576 +      }
 49.4577 +      else { /* exhaust dv */
 49.4578 +        size_t dvs = ms->dvsize;
 49.4579 +        ms->dvsize = 0;
 49.4580 +        ms->dv = 0;
 49.4581 +        set_inuse_and_pinuse(ms, p, dvs);
 49.4582 +      }
 49.4583 +      mem = chunk2mem(p);
 49.4584 +      check_malloced_chunk(ms, mem, nb);
 49.4585 +      goto postaction;
 49.4586 +    }
 49.4587 +
 49.4588 +    else if (nb < ms->topsize) { /* Split top */
 49.4589 +      size_t rsize = ms->topsize -= nb;
 49.4590 +      mchunkptr p = ms->top;
 49.4591 +      mchunkptr r = ms->top = chunk_plus_offset(p, nb);
 49.4592 +      r->head = rsize | PINUSE_BIT;
 49.4593 +      set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
 49.4594 +      mem = chunk2mem(p);
 49.4595 +      check_top_chunk(ms, ms->top);
 49.4596 +      check_malloced_chunk(ms, mem, nb);
 49.4597 +      goto postaction;
 49.4598 +    }
 49.4599 +
 49.4600 +    mem = sys_alloc(ms, nb);
 49.4601 +
 49.4602 +  postaction:
 49.4603 +    POSTACTION(ms);
 49.4604 +    return mem;
 49.4605 +  }
 49.4606 +
 49.4607 +  return 0;
 49.4608 +}
 49.4609 +
 49.4610 +void mspace_free(mspace msp, void* mem) {
 49.4611 +  if (mem != 0) {
 49.4612 +    mchunkptr p  = mem2chunk(mem);
 49.4613 +#if FOOTERS
 49.4614 +    mstate fm = get_mstate_for(p);
 49.4615 +#else /* FOOTERS */
 49.4616 +    mstate fm = (mstate)msp;
 49.4617 +#endif /* FOOTERS */
 49.4618 +    if (!ok_magic(fm)) {
 49.4619 +      USAGE_ERROR_ACTION(fm, p);
 49.4620 +      return;
 49.4621 +    }
 49.4622 +    if (!PREACTION(fm)) {
 49.4623 +      check_inuse_chunk(fm, p);
 49.4624 +      if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) {
 49.4625 +        size_t psize = chunksize(p);
 49.4626 +        mchunkptr next = chunk_plus_offset(p, psize);
 49.4627 +        if (!pinuse(p)) {
 49.4628 +          size_t prevsize = p->prev_foot;
 49.4629 +          if ((prevsize & IS_MMAPPED_BIT) != 0) {
 49.4630 +            prevsize &= ~IS_MMAPPED_BIT;
 49.4631 +            psize += prevsize + MMAP_FOOT_PAD;
 49.4632 +            if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
 49.4633 +              fm->footprint -= psize;
 49.4634 +            goto postaction;
 49.4635 +          }
 49.4636 +          else {
 49.4637 +            mchunkptr prev = chunk_minus_offset(p, prevsize);
 49.4638 +            psize += prevsize;
 49.4639 +            p = prev;
 49.4640 +            if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
 49.4641 +              if (p != fm->dv) {
 49.4642 +                unlink_chunk(fm, p, prevsize);
 49.4643 +              }
 49.4644 +              else if ((next->head & INUSE_BITS) == INUSE_BITS) {
 49.4645 +                fm->dvsize = psize;
 49.4646 +                set_free_with_pinuse(p, psize, next);
 49.4647 +                goto postaction;
 49.4648 +              }
 49.4649 +            }
 49.4650 +            else
 49.4651 +              goto erroraction;
 49.4652 +          }
 49.4653 +        }
 49.4654 +
 49.4655 +        if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
 49.4656 +          if (!cinuse(next)) {  /* consolidate forward */
 49.4657 +            if (next == fm->top) {
 49.4658 +              size_t tsize = fm->topsize += psize;
 49.4659 +              fm->top = p;
 49.4660 +              p->head = tsize | PINUSE_BIT;
 49.4661 +              if (p == fm->dv) {
 49.4662 +                fm->dv = 0;
 49.4663 +                fm->dvsize = 0;
 49.4664 +              }
 49.4665 +              if (should_trim(fm, tsize))
 49.4666 +                sys_trim(fm, 0);
 49.4667 +              goto postaction;
 49.4668 +            }
 49.4669 +            else if (next == fm->dv) {
 49.4670 +              size_t dsize = fm->dvsize += psize;
 49.4671 +              fm->dv = p;
 49.4672 +              set_size_and_pinuse_of_free_chunk(p, dsize);
 49.4673 +              goto postaction;
 49.4674 +            }
 49.4675 +            else {
 49.4676 +              size_t nsize = chunksize(next);
 49.4677 +              psize += nsize;
 49.4678 +              unlink_chunk(fm, next, nsize);
 49.4679 +              set_size_and_pinuse_of_free_chunk(p, psize);
 49.4680 +              if (p == fm->dv) {
 49.4681 +                fm->dvsize = psize;
 49.4682 +                goto postaction;
 49.4683 +              }
 49.4684 +            }
 49.4685 +          }
 49.4686 +          else
 49.4687 +            set_free_with_pinuse(p, psize, next);
 49.4688 +          insert_chunk(fm, p, psize);
 49.4689 +          check_free_chunk(fm, p);
 49.4690 +          goto postaction;
 49.4691 +        }
 49.4692 +      }
 49.4693 +    erroraction:
 49.4694 +      USAGE_ERROR_ACTION(fm, p);
 49.4695 +    postaction:
 49.4696 +      POSTACTION(fm);
 49.4697 +    }
 49.4698 +  }
 49.4699 +}
 49.4700 +
 49.4701 +void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) {
 49.4702 +  void* mem;
 49.4703 +  size_t req = 0;
 49.4704 +  mstate ms = (mstate)msp;
 49.4705 +  if (!ok_magic(ms)) {
 49.4706 +    USAGE_ERROR_ACTION(ms,ms);
 49.4707 +    return 0;
 49.4708 +  }
 49.4709 +  if (n_elements != 0) {
 49.4710 +    req = n_elements * elem_size;
 49.4711 +    if (((n_elements | elem_size) & ~(size_t)0xffff) &&
 49.4712 +        (req / n_elements != elem_size))
 49.4713 +      req = MAX_SIZE_T; /* force downstream failure on overflow */
 49.4714 +  }
 49.4715 +  mem = internal_malloc(ms, req);
 49.4716 +  if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
 49.4717 +    memset(mem, 0, req);
 49.4718 +  return mem;
 49.4719 +}
 49.4720 +
 49.4721 +void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) {
 49.4722 +  if (oldmem == 0)
 49.4723 +    return mspace_malloc(msp, bytes);
 49.4724 +#ifdef REALLOC_ZERO_BYTES_FREES
 49.4725 +  if (bytes == 0) {
 49.4726 +    mspace_free(msp, oldmem);
 49.4727 +    return 0;
 49.4728 +  }
 49.4729 +#endif /* REALLOC_ZERO_BYTES_FREES */
 49.4730 +  else {
 49.4731 +#if FOOTERS
 49.4732 +    mchunkptr p  = mem2chunk(oldmem);
 49.4733 +    mstate ms = get_mstate_for(p);
 49.4734 +#else /* FOOTERS */
 49.4735 +    mstate ms = (mstate)msp;
 49.4736 +#endif /* FOOTERS */
 49.4737 +    if (!ok_magic(ms)) {
 49.4738 +      USAGE_ERROR_ACTION(ms,ms);
 49.4739 +      return 0;
 49.4740 +    }
 49.4741 +    return internal_realloc(ms, oldmem, bytes);
 49.4742 +  }
 49.4743 +}
 49.4744 +
 49.4745 +void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) {
 49.4746 +  mstate ms = (mstate)msp;
 49.4747 +  if (!ok_magic(ms)) {
 49.4748 +    USAGE_ERROR_ACTION(ms,ms);
 49.4749 +    return 0;
 49.4750 +  }
 49.4751 +  return internal_memalign(ms, alignment, bytes);
 49.4752 +}
 49.4753 +
 49.4754 +void** mspace_independent_calloc(mspace msp, size_t n_elements,
 49.4755 +                                 size_t elem_size, void* chunks[]) {
 49.4756 +  size_t sz = elem_size; /* serves as 1-element array */
 49.4757 +  mstate ms = (mstate)msp;
 49.4758 +  if (!ok_magic(ms)) {
 49.4759 +    USAGE_ERROR_ACTION(ms,ms);
 49.4760 +    return 0;
 49.4761 +  }
 49.4762 +  return ialloc(ms, n_elements, &sz, 3, chunks);
 49.4763 +}
 49.4764 +
 49.4765 +void** mspace_independent_comalloc(mspace msp, size_t n_elements,
 49.4766 +                                   size_t sizes[], void* chunks[]) {
 49.4767 +  mstate ms = (mstate)msp;
 49.4768 +  if (!ok_magic(ms)) {
 49.4769 +    USAGE_ERROR_ACTION(ms,ms);
 49.4770 +    return 0;
 49.4771 +  }
 49.4772 +  return ialloc(ms, n_elements, sizes, 0, chunks);
 49.4773 +}
 49.4774 +
 49.4775 +int mspace_trim(mspace msp, size_t pad) {
 49.4776 +  int result = 0;
 49.4777 +  mstate ms = (mstate)msp;
 49.4778 +  if (ok_magic(ms)) {
 49.4779 +    if (!PREACTION(ms)) {
 49.4780 +      result = sys_trim(ms, pad);
 49.4781 +      POSTACTION(ms);
 49.4782 +    }
 49.4783 +  }
 49.4784 +  else {
 49.4785 +    USAGE_ERROR_ACTION(ms,ms);
 49.4786 +  }
 49.4787 +  return result;
 49.4788 +}
 49.4789 +
 49.4790 +void mspace_malloc_stats(mspace msp) {
 49.4791 +  mstate ms = (mstate)msp;
 49.4792 +  if (ok_magic(ms)) {
 49.4793 +    internal_malloc_stats(ms);
 49.4794 +  }
 49.4795 +  else {
 49.4796 +    USAGE_ERROR_ACTION(ms,ms);
 49.4797 +  }
 49.4798 +}
 49.4799 +
 49.4800 +size_t mspace_footprint(mspace msp) {
 49.4801 +  size_t result;
 49.4802 +  mstate ms = (mstate)msp;
 49.4803 +  if (ok_magic(ms)) {
 49.4804 +    result = ms->footprint;
 49.4805 +  }
 49.4806 +  USAGE_ERROR_ACTION(ms,ms);
 49.4807 +  return result;
 49.4808 +}
 49.4809 +
 49.4810 +
 49.4811 +size_t mspace_max_footprint(mspace msp) {
 49.4812 +  size_t result;
 49.4813 +  mstate ms = (mstate)msp;
 49.4814 +  if (ok_magic(ms)) {
 49.4815 +    result = ms->max_footprint;
 49.4816 +  }
 49.4817 +  USAGE_ERROR_ACTION(ms,ms);
 49.4818 +  return result;
 49.4819 +}
 49.4820 +
 49.4821 +
 49.4822 +#if !NO_MALLINFO
 49.4823 +struct mallinfo mspace_mallinfo(mspace msp) {
 49.4824 +  mstate ms = (mstate)msp;
 49.4825 +  if (!ok_magic(ms)) {
 49.4826 +    USAGE_ERROR_ACTION(ms,ms);
 49.4827 +  }
 49.4828 +  return internal_mallinfo(ms);
 49.4829 +}
 49.4830 +#endif /* NO_MALLINFO */
 49.4831 +
 49.4832 +int mspace_mallopt(int param_number, int value) {
 49.4833 +  return change_mparam(param_number, value);
 49.4834 +}
 49.4835 +
 49.4836 +#endif /* MSPACES */
 49.4837 +
 49.4838 +/* -------------------- Alternative MORECORE functions ------------------- */
 49.4839 +
 49.4840 +/*
 49.4841 +  Guidelines for creating a custom version of MORECORE:
 49.4842 +
 49.4843 +  * For best performance, MORECORE should allocate in multiples of pagesize.
 49.4844 +  * MORECORE may allocate more memory than requested. (Or even less,
 49.4845 +      but this will usually result in a malloc failure.)
 49.4846 +  * MORECORE must not allocate memory when given argument zero, but
 49.4847 +      instead return one past the end address of memory from previous
 49.4848 +      nonzero call.
 49.4849 +  * For best performance, consecutive calls to MORECORE with positive
 49.4850 +      arguments should return increasing addresses, indicating that
 49.4851 +      space has been contiguously extended.
 49.4852 +  * Even though consecutive calls to MORECORE need not return contiguous
 49.4853 +      addresses, it must be OK for malloc'ed chunks to span multiple
 49.4854 +      regions in those cases where they do happen to be contiguous.
 49.4855 +  * MORECORE need not handle negative arguments -- it may instead
 49.4856 +      just return MFAIL when given negative arguments.
 49.4857 +      Negative arguments are always multiples of pagesize. MORECORE
 49.4858 +      must not misinterpret negative args as large positive unsigned
 49.4859 +      args. You can suppress all such calls from even occurring by defining
 49.4860 +      MORECORE_CANNOT_TRIM,
 49.4861 +
 49.4862 +  As an example alternative MORECORE, here is a custom allocator
 49.4863 +  kindly contributed for pre-OSX macOS.  It uses virtually but not
 49.4864 +  necessarily physically contiguous non-paged memory (locked in,
 49.4865 +  present and won't get swapped out).  You can use it by uncommenting
 49.4866 +  this section, adding some #includes, and setting up the appropriate
 49.4867 +  defines above:
 49.4868 +
 49.4869 +      #define MORECORE osMoreCore
 49.4870 +
 49.4871 +  There is also a shutdown routine that should somehow be called for
 49.4872 +  cleanup upon program exit.
 49.4873 +
 49.4874 +  #define MAX_POOL_ENTRIES 100
 49.4875 +  #define MINIMUM_MORECORE_SIZE  (64 * 1024U)
 49.4876 +  static int next_os_pool;
 49.4877 +  void *our_os_pools[MAX_POOL_ENTRIES];
 49.4878 +
 49.4879 +  void *osMoreCore(int size)
 49.4880 +  {
 49.4881 +    void *ptr = 0;
 49.4882 +    static void *sbrk_top = 0;
 49.4883 +
 49.4884 +    if (size > 0)
 49.4885 +    {
 49.4886 +      if (size < MINIMUM_MORECORE_SIZE)
 49.4887 +         size = MINIMUM_MORECORE_SIZE;
 49.4888 +      if (CurrentExecutionLevel() == kTaskLevel)
 49.4889 +         ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
 49.4890 +      if (ptr == 0)
 49.4891 +      {
 49.4892 +        return (void *) MFAIL;
 49.4893 +      }
 49.4894 +      // save ptrs so they can be freed during cleanup
 49.4895 +      our_os_pools[next_os_pool] = ptr;
 49.4896 +      next_os_pool++;
 49.4897 +      ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
 49.4898 +      sbrk_top = (char *) ptr + size;
 49.4899 +      return ptr;
 49.4900 +    }
 49.4901 +    else if (size < 0)
 49.4902 +    {
 49.4903 +      // we don't currently support shrink behavior
 49.4904 +      return (void *) MFAIL;
 49.4905 +    }
 49.4906 +    else
 49.4907 +    {
 49.4908 +      return sbrk_top;
 49.4909 +    }
 49.4910 +  }
 49.4911 +
 49.4912 +  // cleanup any allocated memory pools
 49.4913 +  // called as last thing before shutting down driver
 49.4914 +
 49.4915 +  void osCleanupMem(void)
 49.4916 +  {
 49.4917 +    void **ptr;
 49.4918 +
 49.4919 +    for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
 49.4920 +      if (*ptr)
 49.4921 +      {
 49.4922 +         PoolDeallocate(*ptr);
 49.4923 +         *ptr = 0;
 49.4924 +      }
 49.4925 +  }
 49.4926 +
 49.4927 +*/
 49.4928 +
 49.4929 +
 49.4930 +/* -----------------------------------------------------------------------
 49.4931 +History:
 49.4932 +    V2.8.3 Thu Sep 22 11:16:32 2005  Doug Lea  (dl at gee)
 49.4933 +      * Add max_footprint functions
 49.4934 +      * Ensure all appropriate literals are size_t
 49.4935 +      * Fix conditional compilation problem for some #define settings
 49.4936 +      * Avoid concatenating segments with the one provided
 49.4937 +        in create_mspace_with_base
 49.4938 +      * Rename some variables to avoid compiler shadowing warnings
 49.4939 +      * Use explicit lock initialization.
 49.4940 +      * Better handling of sbrk interference.
 49.4941 +      * Simplify and fix segment insertion, trimming and mspace_destroy
 49.4942 +      * Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x
 49.4943 +      * Thanks especially to Dennis Flanagan for help on these.
 49.4944 +
 49.4945 +    V2.8.2 Sun Jun 12 16:01:10 2005  Doug Lea  (dl at gee)
 49.4946 +      * Fix memalign brace error.
 49.4947 +
 49.4948 +    V2.8.1 Wed Jun  8 16:11:46 2005  Doug Lea  (dl at gee)
 49.4949 +      * Fix improper #endif nesting in C++
 49.4950 +      * Add explicit casts needed for C++
 49.4951 +
 49.4952 +    V2.8.0 Mon May 30 14:09:02 2005  Doug Lea  (dl at gee)
 49.4953 +      * Use trees for large bins
 49.4954 +      * Support mspaces
 49.4955 +      * Use segments to unify sbrk-based and mmap-based system allocation,
 49.4956 +        removing need for emulation on most platforms without sbrk.
 49.4957 +      * Default safety checks
 49.4958 +      * Optional footer checks. Thanks to William Robertson for the idea.
 49.4959 +      * Internal code refactoring
 49.4960 +      * Incorporate suggestions and platform-specific changes.
 49.4961 +        Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas,
 49.4962 +        Aaron Bachmann,  Emery Berger, and others.
 49.4963 +      * Speed up non-fastbin processing enough to remove fastbins.
 49.4964 +      * Remove useless cfree() to avoid conflicts with other apps.
 49.4965 +      * Remove internal memcpy, memset. Compilers handle builtins better.
 49.4966 +      * Remove some options that no one ever used and rename others.
 49.4967 +
 49.4968 +    V2.7.2 Sat Aug 17 09:07:30 2002  Doug Lea  (dl at gee)
 49.4969 +      * Fix malloc_state bitmap array misdeclaration
 49.4970 +
 49.4971 +    V2.7.1 Thu Jul 25 10:58:03 2002  Doug Lea  (dl at gee)
 49.4972 +      * Allow tuning of FIRST_SORTED_BIN_SIZE
 49.4973 +      * Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte.
 49.4974 +      * Better detection and support for non-contiguousness of MORECORE.
 49.4975 +        Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger
 49.4976 +      * Bypass most of malloc if no frees. Thanks To Emery Berger.
 49.4977 +      * Fix freeing of old top non-contiguous chunk im sysmalloc.
 49.4978 +      * Raised default trim and map thresholds to 256K.
 49.4979 +      * Fix mmap-related #defines. Thanks to Lubos Lunak.
 49.4980 +      * Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield.
 49.4981 +      * Branch-free bin calculation
 49.4982 +      * Default trim and mmap thresholds now 256K.
 49.4983 +
 49.4984 +    V2.7.0 Sun Mar 11 14:14:06 2001  Doug Lea  (dl at gee)
 49.4985 +      * Introduce independent_comalloc and independent_calloc.
 49.4986 +        Thanks to Michael Pachos for motivation and help.
 49.4987 +      * Make optional .h file available
 49.4988 +      * Allow > 2GB requests on 32bit systems.
 49.4989 +      * new WIN32 sbrk, mmap, munmap, lock code from <Walter@GeNeSys-e.de>.
 49.4990 +        Thanks also to Andreas Mueller <a.mueller at paradatec.de>,
 49.4991 +        and Anonymous.
 49.4992 +      * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for
 49.4993 +        helping test this.)
 49.4994 +      * memalign: check alignment arg
 49.4995 +      * realloc: don't try to shift chunks backwards, since this
 49.4996 +        leads to  more fragmentation in some programs and doesn't
 49.4997 +        seem to help in any others.
 49.4998 +      * Collect all cases in malloc requiring system memory into sysmalloc
 49.4999 +      * Use mmap as backup to sbrk
 49.5000 +      * Place all internal state in malloc_state
 49.5001 +      * Introduce fastbins (although similar to 2.5.1)
 49.5002 +      * Many minor tunings and cosmetic improvements
 49.5003 +      * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK
 49.5004 +      * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS
 49.5005 +        Thanks to Tony E. Bennett <tbennett@nvidia.com> and others.
 49.5006 +      * Include errno.h to support default failure action.
 49.5007 +
 49.5008 +    V2.6.6 Sun Dec  5 07:42:19 1999  Doug Lea  (dl at gee)
 49.5009 +      * return null for negative arguments
 49.5010 +      * Added Several WIN32 cleanups from Martin C. Fong <mcfong at yahoo.com>
 49.5011 +         * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
 49.5012 +          (e.g. WIN32 platforms)
 49.5013 +         * Cleanup header file inclusion for WIN32 platforms
 49.5014 +         * Cleanup code to avoid Microsoft Visual C++ compiler complaints
 49.5015 +         * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
 49.5016 +           memory allocation routines
 49.5017 +         * Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
 49.5018 +         * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
 49.5019 +           usage of 'assert' in non-WIN32 code
 49.5020 +         * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
 49.5021 +           avoid infinite loop
 49.5022 +      * Always call 'fREe()' rather than 'free()'
 49.5023 +
 49.5024 +    V2.6.5 Wed Jun 17 15:57:31 1998  Doug Lea  (dl at gee)
 49.5025 +      * Fixed ordering problem with boundary-stamping
 49.5026 +
 49.5027 +    V2.6.3 Sun May 19 08:17:58 1996  Doug Lea  (dl at gee)
 49.5028 +      * Added pvalloc, as recommended by H.J. Liu
 49.5029 +      * Added 64bit pointer support mainly from Wolfram Gloger
 49.5030 +      * Added anonymously donated WIN32 sbrk emulation
 49.5031 +      * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
 49.5032 +      * malloc_extend_top: fix mask error that caused wastage after
 49.5033 +        foreign sbrks
 49.5034 +      * Add linux mremap support code from HJ Liu
 49.5035 +
 49.5036 +    V2.6.2 Tue Dec  5 06:52:55 1995  Doug Lea  (dl at gee)
 49.5037 +      * Integrated most documentation with the code.
 49.5038 +      * Add support for mmap, with help from
 49.5039 +        Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
 49.5040 +      * Use last_remainder in more cases.
 49.5041 +      * Pack bins using idea from  colin@nyx10.cs.du.edu
 49.5042 +      * Use ordered bins instead of best-fit threshhold
 49.5043 +      * Eliminate block-local decls to simplify tracing and debugging.
 49.5044 +      * Support another case of realloc via move into top
 49.5045 +      * Fix error occuring when initial sbrk_base not word-aligned.
 49.5046 +      * Rely on page size for units instead of SBRK_UNIT to
 49.5047 +        avoid surprises about sbrk alignment conventions.
 49.5048 +      * Add mallinfo, mallopt. Thanks to Raymond Nijssen
 49.5049 +        (raymond@es.ele.tue.nl) for the suggestion.
 49.5050 +      * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
 49.5051 +      * More precautions for cases where other routines call sbrk,
 49.5052 +        courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
 49.5053 +      * Added macros etc., allowing use in linux libc from
 49.5054 +        H.J. Lu (hjl@gnu.ai.mit.edu)
 49.5055 +      * Inverted this history list
 49.5056 +
 49.5057 +    V2.6.1 Sat Dec  2 14:10:57 1995  Doug Lea  (dl at gee)
 49.5058 +      * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
 49.5059 +      * Removed all preallocation code since under current scheme
 49.5060 +        the work required to undo bad preallocations exceeds
 49.5061 +        the work saved in good cases for most test programs.
 49.5062 +      * No longer use return list or unconsolidated bins since
 49.5063 +        no scheme using them consistently outperforms those that don't
 49.5064 +        given above changes.
 49.5065 +      * Use best fit for very large chunks to prevent some worst-cases.
 49.5066 +      * Added some support for debugging
 49.5067 +
 49.5068 +    V2.6.0 Sat Nov  4 07:05:23 1995  Doug Lea  (dl at gee)
 49.5069 +      * Removed footers when chunks are in use. Thanks to
 49.5070 +        Paul Wilson (wilson@cs.texas.edu) for the suggestion.
 49.5071 +
 49.5072 +    V2.5.4 Wed Nov  1 07:54:51 1995  Doug Lea  (dl at gee)
 49.5073 +      * Added malloc_trim, with help from Wolfram Gloger
 49.5074 +        (wmglo@Dent.MED.Uni-Muenchen.DE).
 49.5075 +
 49.5076 +    V2.5.3 Tue Apr 26 10:16:01 1994  Doug Lea  (dl at g)
 49.5077 +
 49.5078 +    V2.5.2 Tue Apr  5 16:20:40 1994  Doug Lea  (dl at g)
 49.5079 +      * realloc: try to expand in both directions
 49.5080 +      * malloc: swap order of clean-bin strategy;
 49.5081 +      * realloc: only conditionally expand backwards
 49.5082 +      * Try not to scavenge used bins
 49.5083 +      * Use bin counts as a guide to preallocation
 49.5084 +      * Occasionally bin return list chunks in first scan
 49.5085 +      * Add a few optimizations from colin@nyx10.cs.du.edu
 49.5086 +
 49.5087 +    V2.5.1 Sat Aug 14 15:40:43 1993  Doug Lea  (dl at g)
 49.5088 +      * faster bin computation & slightly different binning
 49.5089 +      * merged all consolidations to one part of malloc proper
 49.5090 +         (eliminating old malloc_find_space & malloc_clean_bin)
 49.5091 +      * Scan 2 returns chunks (not just 1)
 49.5092 +      * Propagate failure in realloc if malloc returns 0
 49.5093 +      * Add stuff to allow compilation on non-ANSI compilers
 49.5094 +          from kpv@research.att.com
 49.5095 +
 49.5096 +    V2.5 Sat Aug  7 07:41:59 1993  Doug Lea  (dl at g.oswego.edu)
 49.5097 +      * removed potential for odd address access in prev_chunk
 49.5098 +      * removed dependency on getpagesize.h
 49.5099 +      * misc cosmetics and a bit more internal documentation
 49.5100 +      * anticosmetics: mangled names in macros to evade debugger strangeness
 49.5101 +      * tested on sparc, hp-700, dec-mips, rs6000
 49.5102 +          with gcc & native cc (hp, dec only) allowing
 49.5103 +          Detlefs & Zorn comparison study (in SIGPLAN Notices.)
 49.5104 +
 49.5105 +    Trial version Fri Aug 28 13:14:29 1992  Doug Lea  (dl at g.oswego.edu)
 49.5106 +      * Based loosely on libg++-1.2X malloc. (It retains some of the overall
 49.5107 +         structure of old version,  but most details differ.)
 49.5108 + 
 49.5109 +*/
 49.5110 +
 49.5111 +#endif /* !HAVE_MALLOC */
 49.5112 \ No newline at end of file
    50.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    50.2 +++ b/src/stdlib/SDL_qsort.c	Mon Feb 06 08:28:51 2006 +0000
    50.3 @@ -0,0 +1,418 @@
    50.4 +/* qsort.c
    50.5 + * (c) 1998 Gareth McCaughan
    50.6 + *
    50.7 + * This is a drop-in replacement for the C library's |qsort()| routine.
    50.8 + *
    50.9 + * Features:
   50.10 + *   - Median-of-three pivoting (and more)
   50.11 + *   - Truncation and final polishing by a single insertion sort
   50.12 + *   - Early truncation when no swaps needed in pivoting step
   50.13 + *   - Explicit recursion, guaranteed not to overflow
   50.14 + *   - A few little wrinkles stolen from the GNU |qsort()|.
   50.15 + *   - separate code for non-aligned / aligned / word-size objects
   50.16 + *
   50.17 + * This code may be reproduced freely provided
   50.18 + *   - this file is retained unaltered apart from minor
   50.19 + *     changes for portability and efficiency
   50.20 + *   - no changes are made to this comment
   50.21 + *   - any changes that *are* made are clearly flagged
   50.22 + *   - the _ID string below is altered by inserting, after
   50.23 + *     the date, the string " altered" followed at your option
   50.24 + *     by other material. (Exceptions: you may change the name
   50.25 + *     of the exported routine without changing the ID string.
   50.26 + *     You may change the values of the macros TRUNC_* and
   50.27 + *     PIVOT_THRESHOLD without changing the ID string, provided
   50.28 + *     they remain constants with TRUNC_nonaligned, TRUNC_aligned
   50.29 + *     and TRUNC_words/WORD_BYTES between 8 and 24, and
   50.30 + *     PIVOT_THRESHOLD between 32 and 200.)
   50.31 + *
   50.32 + * You may use it in anything you like; you may make money
   50.33 + * out of it; you may distribute it in object form or as
   50.34 + * part of an executable without including source code;
   50.35 + * you don't have to credit me. (But it would be nice if
   50.36 + * you did.)
   50.37 + *
   50.38 + * If you find problems with this code, or find ways of
   50.39 + * making it significantly faster, please let me know!
   50.40 + * My e-mail address, valid as of early 1998 and certainly
   50.41 + * OK for at least the next 18 months, is
   50.42 + *    gjm11@dpmms.cam.ac.uk
   50.43 + * Thanks!
   50.44 + *
   50.45 + * Gareth McCaughan   Peterhouse   Cambridge   1998
   50.46 + */
   50.47 +
   50.48 +/*
   50.49 +#include <assert.h>
   50.50 +#include <stdlib.h>
   50.51 +#include <string.h>
   50.52 +*/
   50.53 +#define assert(X)
   50.54 +#include "SDL_stdlib.h"
   50.55 +#include "SDL_string.h"
   50.56 +
   50.57 +#ifndef HAVE_QSORT
   50.58 +
   50.59 +static char _ID[]="<qsort.c gjm 1.12 1998-03-19>";
   50.60 +
   50.61 +/* How many bytes are there per word? (Must be a power of 2,
   50.62 + * and must in fact equal sizeof(int).)
   50.63 + */
   50.64 +#define WORD_BYTES sizeof(int)
   50.65 +
   50.66 +/* How big does our stack need to be? Answer: one entry per
   50.67 + * bit in a |size_t|.
   50.68 + */
   50.69 +#define STACK_SIZE (8*sizeof(size_t))
   50.70 +
   50.71 +/* Different situations have slightly different requirements,
   50.72 + * and we make life epsilon easier by using different truncation
   50.73 + * points for the three different cases.
   50.74 + * So far, I have tuned TRUNC_words and guessed that the same
   50.75 + * value might work well for the other two cases. Of course
   50.76 + * what works well on my machine might work badly on yours.
   50.77 + */
   50.78 +#define TRUNC_nonaligned	12
   50.79 +#define TRUNC_aligned		12
   50.80 +#define TRUNC_words		12*WORD_BYTES	/* nb different meaning */
   50.81 +
   50.82 +/* We use a simple pivoting algorithm for shortish sub-arrays
   50.83 + * and a more complicated one for larger ones. The threshold
   50.84 + * is PIVOT_THRESHOLD.
   50.85 + */
   50.86 +#define PIVOT_THRESHOLD 40
   50.87 +
   50.88 +typedef struct { char * first; char * last; } stack_entry;
   50.89 +#define pushLeft {stack[stacktop].first=ffirst;stack[stacktop++].last=last;}
   50.90 +#define pushRight {stack[stacktop].first=first;stack[stacktop++].last=llast;}
   50.91 +#define doLeft {first=ffirst;llast=last;continue;}
   50.92 +#define doRight {ffirst=first;last=llast;continue;}
   50.93 +#define pop {if (--stacktop<0) break;\
   50.94 +  first=ffirst=stack[stacktop].first;\
   50.95 +  last=llast=stack[stacktop].last;\
   50.96 +  continue;}
   50.97 +
   50.98 +/* Some comments on the implementation.
   50.99 + * 1. When we finish partitioning the array into "low"
  50.100 + *    and "high", we forget entirely about short subarrays,
  50.101 + *    because they'll be done later by insertion sort.
  50.102 + *    Doing lots of little insertion sorts might be a win
  50.103 + *    on large datasets for locality-of-reference reasons,
  50.104 + *    but it makes the code much nastier and increases
  50.105 + *    bookkeeping overhead.
  50.106 + * 2. We always save the shorter and get to work on the
  50.107 + *    longer. This guarantees that every time we push
  50.108 + *    an item onto the stack its size is <= 1/2 of that
  50.109 + *    of its parent; so the stack can't need more than
  50.110 + *    log_2(max-array-size) entries.
  50.111 + * 3. We choose a pivot by looking at the first, last
  50.112 + *    and middle elements. We arrange them into order
  50.113 + *    because it's easy to do that in conjunction with
  50.114 + *    choosing the pivot, and it makes things a little
  50.115 + *    easier in the partitioning step. Anyway, the pivot
  50.116 + *    is the middle of these three. It's still possible
  50.117 + *    to construct datasets where the algorithm takes
  50.