[syslinux:elflink] elflink: merge these files

syslinux-bot for Feng Tang feng.tang at intel.com
Thu Aug 12 21:03:49 PDT 2010


Commit-ID:  fe87f81f3ba8dc1828965fe2cd113dbdfd2248bf
Gitweb:     http://syslinux.zytor.com/commit/fe87f81f3ba8dc1828965fe2cd113dbdfd2248bf
Author:     Feng Tang <feng.tang at intel.com>
AuthorDate: Mon, 12 Jul 2010 15:45:05 +0800
Committer:  Feng Tang <feng.tang at intel.com>
CommitDate: Tue, 20 Jul 2010 11:10:04 +0800

elflink: merge these files

   com32/include/sys/times.h
   com32/include/syslinux/config.h
   com32/include/syslinux/pmapi.h
   com32/include/unistd.h
   com32/include/zconf.h
   com32/include/zlib.h
   dos/Makefile
   dos/errno.h
   dos/string.h
   dos/syslinux.c
   dosutil/eltorito.asm
   dosutil/mdiskchk.c
   dosutil/mdiskchk.com
   extlinux/Makefile
   extlinux/fat.h
   extlinux/main.c
   libfat/libfat.h
   libfat/open.c
   libinstaller/Makefile
   libinstaller/setadv.c
   libinstaller/syslinux.h
   libinstaller/syslxcom.c
   libinstaller/syslxcom.h
   libinstaller/syslxint.h
   libinstaller/syslxmod.c
   libinstaller/syslxopt.c
   libinstaller/syslxopt.h
   linux/Makefile
   linux/syslinux.c


---
 com32/include/sys/times.h       |    4 +-
 com32/include/syslinux/config.h |   11 +
 com32/include/syslinux/pmapi.h  |    9 +
 com32/include/unistd.h          |    3 +
 com32/include/zconf.h           |  281 ++++++---
 com32/include/zlib.h            | 1293 ++++++++++++++++++++++++++-------------
 dos/Makefile                    |    6 +-
 dos/errno.h                     |   35 ++
 dos/string.h                    |    1 +
 dos/syslinux.c                  |   12 +-
 dosutil/eltorito.asm            |   15 +-
 dosutil/mdiskchk.c              |  254 +++++++-
 dosutil/mdiskchk.com            |  Bin 7273 -> 8106 bytes
 extlinux/Makefile               |    6 +-
 extlinux/fat.h                  |   57 +--
 extlinux/main.c                 |  278 ++++------
 libfat/libfat.h                 |    2 +-
 libfat/open.c                   |    6 +-
 libinstaller/Makefile           |    7 -
 libinstaller/setadv.c           |  131 +----
 libinstaller/syslinux.h         |   11 +-
 libinstaller/syslxcom.c         |  120 +++-
 libinstaller/syslxcom.h         |    4 +-
 libinstaller/syslxint.h         |  142 ++++-
 libinstaller/syslxmod.c         |  327 ++++-------
 libinstaller/syslxopt.c         |  104 +++-
 libinstaller/syslxopt.h         |   12 +-
 linux/Makefile                  |    6 +-
 linux/syslinux.c                |   78 +--
 man/extlinux.1                  |    5 +
 man/syslinux.1                  |   12 +-
 mbr/checksize.pl                |    2 +-
 mbr/gptmbr.S                    |   65 ++-
 mbr/isohdpfx.S                  |    8 +-
 memdisk/Makefile                |    2 +-
 memdisk/acpi.h                  |    3 +-
 memdisk/eltorito.h              |   29 +-
 memdisk/memdisk.inc             |   15 +-
 memdisk/setup.c                 |  219 ++-----
 mtools/Makefile                 |    2 +
 mtools/syslinux.c               |   67 ++-
 utils/Makefile                  |    9 +-
 utils/isohybrid.c               |    8 +-
 win32/Makefile                  |   20 +-
 win32/syslinux.c                |   22 +-
 45 files changed, 2180 insertions(+), 1523 deletions(-)

diff --git a/com32/include/sys/times.h b/com32/include/sys/times.h
index 961c7b6..9047006 100644
--- a/com32/include/sys/times.h
+++ b/com32/include/sys/times.h
@@ -11,10 +11,10 @@ struct tms {
     /* Empty */
 };
 
-#define HZ		18	/* Piddly resolution... */
+#define HZ		1000
 #define CLK_TCK		HZ
 
-typedef uint16_t clock_t;
+typedef uint32_t clock_t;
 
 clock_t times(struct tms *);
 
diff --git a/com32/include/syslinux/config.h b/com32/include/syslinux/config.h
index 868b0f1..79a4750 100644
--- a/com32/include/syslinux/config.h
+++ b/com32/include/syslinux/config.h
@@ -54,6 +54,14 @@ struct syslinux_version {
     const char *copyright_string;
 };
 
+struct syslinux_ipinfo {
+    uint32_t ipver;
+    uint32_t myip;
+    uint32_t serverip;
+    uint32_t gateway;
+    uint32_t netmask;
+};
+
 extern __nocommon struct syslinux_version __syslinux_version;
 static inline const struct syslinux_version *syslinux_version(void)
 {
@@ -104,6 +112,7 @@ union syslinux_derivative_info {
 	uint32_t _eflags;
 	const void *ptab_ptr;
 	const uint32_t *esdi_ptr;
+	const uint64_t *partoffset;
     } disk;			/* syslinux/extlinux */
     struct {
 	uint16_t _gs, _fs, _es, _ds;
@@ -116,6 +125,7 @@ union syslinux_derivative_info {
 	uint32_t _eflags;
 	const void *pxenvptr;
 	const void *stack;
+	const struct syslinux_ipinfo *ipinfo;
     } pxe;			/* pxelinux */
     struct {
 	uint16_t _gs, _fs, _es, _ds;
@@ -129,6 +139,7 @@ union syslinux_derivative_info {
 	uint32_t _eflags;
 	const void *spec_packet;
 	const uint32_t *esdi_ptr;
+	const uint64_t *partoffset;
     } iso;			/* isolinux */
 };
 
diff --git a/com32/include/syslinux/pmapi.h b/com32/include/syslinux/pmapi.h
index f583dea..fa39018 100644
--- a/com32/include/syslinux/pmapi.h
+++ b/com32/include/syslinux/pmapi.h
@@ -52,6 +52,8 @@ struct com32_filedata {
 };
 
 struct com32_pmapi {
+    size_t __pmapi_size;
+
     void *(*lmalloc)(size_t);
     void (*lfree)(void *);
 
@@ -65,6 +67,13 @@ struct com32_pmapi {
 
     void (*idle)(void);
     void (*reset_idle)(void);
+
+    int (*chdir)(const char *);
+    char *(*getcwd)(char *, size_t);
+
+    /* Should be "const volatile", but gcc miscompiles that sometimes */
+    volatile uint32_t *jiffies;
+    volatile uint32_t *ms_timer;
 };
 
 #endif /* _SYSLINUX_PMAPI_H */
diff --git a/com32/include/unistd.h b/com32/include/unistd.h
index c0b52d6..fc514f1 100644
--- a/com32/include/unistd.h
+++ b/com32/include/unistd.h
@@ -25,6 +25,9 @@ __extern int getscreensize(int, int *, int *);
 __extern char *getcwd(char *, int);
 __extern int chdir(const char *);
 
+__extern unsigned int sleep(unsigned int);
+__extern unsigned int msleep(unsigned int);
+
 /* Standard file descriptor numbers. */
 #define STDIN_FILENO	0
 #define STDOUT_FILENO	1
diff --git a/com32/include/zconf.h b/com32/include/zconf.h
index 031f08d..02ce56c 100644
--- a/com32/include/zconf.h
+++ b/com32/include/zconf.h
@@ -1,53 +1,134 @@
 /* zconf.h -- configuration of the zlib compression library
- * Copyright (C) 1995-2003 Jean-loup Gailly.
+ * Copyright (C) 1995-2010 Jean-loup Gailly.
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
+/* @(#) $Id$ */
+
 #ifndef ZCONF_H
 #define ZCONF_H
 
 /*
  * If you *really* need a unique prefix for all types and library functions,
  * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
+ * Even better than compiling with -DZ_PREFIX would be to use configure to set
+ * this permanently in zconf.h using "./configure --zprefix".
  */
-#ifdef Z_PREFIX
-#  define deflateInit_  z_deflateInit_
-#  define deflate       z_deflate
-#  define deflateEnd    z_deflateEnd
-#  define inflateInit_  z_inflateInit_
-#  define inflate       z_inflate
-#  define inflateEnd    z_inflateEnd
-#  define deflateInit2_ z_deflateInit2_
-#  define deflateSetDictionary z_deflateSetDictionary
-#  define deflateCopy   z_deflateCopy
-#  define deflateReset  z_deflateReset
-#  define deflatePrime  z_deflatePrime
-#  define deflateParams z_deflateParams
-#  define deflateBound  z_deflateBound
-#  define inflateInit2_ z_inflateInit2_
-#  define inflateSetDictionary z_inflateSetDictionary
-#  define inflateSync   z_inflateSync
-#  define inflateSyncPoint z_inflateSyncPoint
-#  define inflateCopy   z_inflateCopy
-#  define inflateReset  z_inflateReset
-#  define compress      z_compress
-#  define compress2     z_compress2
-#  define compressBound z_compressBound
-#  define uncompress    z_uncompress
-#  define adler32       z_adler32
-#  define crc32         z_crc32
-#  define get_crc_table z_get_crc_table
-
-#  define Byte          z_Byte
-#  define uInt          z_uInt
-#  define uLong         z_uLong
-#  define Bytef         z_Bytef
-#  define charf         z_charf
-#  define intf          z_intf
-#  define uIntf         z_uIntf
-#  define uLongf        z_uLongf
-#  define voidpf        z_voidpf
-#  define voidp         z_voidp
+#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */
+
+/* all linked symbols */
+#  define _dist_code            z__dist_code
+#  define _length_code          z__length_code
+#  define _tr_align             z__tr_align
+#  define _tr_flush_block       z__tr_flush_block
+#  define _tr_init              z__tr_init
+#  define _tr_stored_block      z__tr_stored_block
+#  define _tr_tally             z__tr_tally
+#  define adler32               z_adler32
+#  define adler32_combine       z_adler32_combine
+#  define adler32_combine64     z_adler32_combine64
+#  define compress              z_compress
+#  define compress2             z_compress2
+#  define compressBound         z_compressBound
+#  define crc32                 z_crc32
+#  define crc32_combine         z_crc32_combine
+#  define crc32_combine64       z_crc32_combine64
+#  define deflate               z_deflate
+#  define deflateBound          z_deflateBound
+#  define deflateCopy           z_deflateCopy
+#  define deflateEnd            z_deflateEnd
+#  define deflateInit2_         z_deflateInit2_
+#  define deflateInit_          z_deflateInit_
+#  define deflateParams         z_deflateParams
+#  define deflatePrime          z_deflatePrime
+#  define deflateReset          z_deflateReset
+#  define deflateSetDictionary  z_deflateSetDictionary
+#  define deflateSetHeader      z_deflateSetHeader
+#  define deflateTune           z_deflateTune
+#  define deflate_copyright     z_deflate_copyright
+#  define get_crc_table         z_get_crc_table
+#  define gz_error              z_gz_error
+#  define gz_intmax             z_gz_intmax
+#  define gz_strwinerror        z_gz_strwinerror
+#  define gzbuffer              z_gzbuffer
+#  define gzclearerr            z_gzclearerr
+#  define gzclose               z_gzclose
+#  define gzclose_r             z_gzclose_r
+#  define gzclose_w             z_gzclose_w
+#  define gzdirect              z_gzdirect
+#  define gzdopen               z_gzdopen
+#  define gzeof                 z_gzeof
+#  define gzerror               z_gzerror
+#  define gzflush               z_gzflush
+#  define gzgetc                z_gzgetc
+#  define gzgets                z_gzgets
+#  define gzoffset              z_gzoffset
+#  define gzoffset64            z_gzoffset64
+#  define gzopen                z_gzopen
+#  define gzopen64              z_gzopen64
+#  define gzprintf              z_gzprintf
+#  define gzputc                z_gzputc
+#  define gzputs                z_gzputs
+#  define gzread                z_gzread
+#  define gzrewind              z_gzrewind
+#  define gzseek                z_gzseek
+#  define gzseek64              z_gzseek64
+#  define gzsetparams           z_gzsetparams
+#  define gztell                z_gztell
+#  define gztell64              z_gztell64
+#  define gzungetc              z_gzungetc
+#  define gzwrite               z_gzwrite
+#  define inflate               z_inflate
+#  define inflateBack           z_inflateBack
+#  define inflateBackEnd        z_inflateBackEnd
+#  define inflateBackInit_      z_inflateBackInit_
+#  define inflateCopy           z_inflateCopy
+#  define inflateEnd            z_inflateEnd
+#  define inflateGetHeader      z_inflateGetHeader
+#  define inflateInit2_         z_inflateInit2_
+#  define inflateInit_          z_inflateInit_
+#  define inflateMark           z_inflateMark
+#  define inflatePrime          z_inflatePrime
+#  define inflateReset          z_inflateReset
+#  define inflateReset2         z_inflateReset2
+#  define inflateSetDictionary  z_inflateSetDictionary
+#  define inflateSync           z_inflateSync
+#  define inflateSyncPoint      z_inflateSyncPoint
+#  define inflateUndermine      z_inflateUndermine
+#  define inflate_copyright     z_inflate_copyright
+#  define inflate_fast          z_inflate_fast
+#  define inflate_table         z_inflate_table
+#  define uncompress            z_uncompress
+#  define zError                z_zError
+#  define zcalloc               z_zcalloc
+#  define zcfree                z_zcfree
+#  define zlibCompileFlags      z_zlibCompileFlags
+#  define zlibVersion           z_zlibVersion
+
+/* all zlib typedefs in zlib.h and zconf.h */
+#  define Byte                  z_Byte
+#  define Bytef                 z_Bytef
+#  define alloc_func            z_alloc_func
+#  define charf                 z_charf
+#  define free_func             z_free_func
+#  define gzFile                z_gzFile
+#  define gz_header             z_gz_header
+#  define gz_headerp            z_gz_headerp
+#  define in_func               z_in_func
+#  define intf                  z_intf
+#  define out_func              z_out_func
+#  define uInt                  z_uInt
+#  define uIntf                 z_uIntf
+#  define uLong                 z_uLong
+#  define uLongf                z_uLongf
+#  define voidp                 z_voidp
+#  define voidpc                z_voidpc
+#  define voidpf                z_voidpf
+
+/* all zlib structs in zlib.h and zconf.h */
+#  define gz_header_s           z_gz_header_s
+#  define internal_state        z_internal_state
+
 #endif
 
 #if defined(__MSDOS__) && !defined(MSDOS)
@@ -59,8 +140,10 @@
 #if defined(_WINDOWS) && !defined(WINDOWS)
 #  define WINDOWS
 #endif
-#if (defined(_WIN32) || defined(__WIN32__)) && !defined(WIN32)
-#  define WIN32
+#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
+#  ifndef WIN32
+#    define WIN32
+#  endif
 #endif
 #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
 #  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
@@ -104,13 +187,13 @@
 #  define STDC
 #endif
 
-#if defined(__OS400__) && !defined(STDC)	/* iSeries (formerly AS/400). */
+#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */
 #  define STDC
 #endif
 
 #ifndef STDC
-#  ifndef const			/* cannot use !defined(STDC) && !defined(const) on Mac */
-#    define const		/* note: need a more gentle solution here */
+#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
+#    define const       /* note: need a more gentle solution here */
 #  endif
 #endif
 
@@ -134,7 +217,7 @@
  * gzip.)
  */
 #ifndef MAX_WBITS
-#  define MAX_WBITS   15	/* 32K LZ77 window */
+#  define MAX_WBITS   15 /* 32K LZ77 window */
 #endif
 
 /* The memory requirements for deflate are (in bytes):
@@ -150,9 +233,9 @@
  for small objects.
 */
 
-			/* Type declarations */
+                        /* Type declarations */
 
-#ifndef OF			/* function prototypes */
+#ifndef OF /* function prototypes */
 #  ifdef STDC
 #    define OF(args)  args
 #  else
@@ -199,7 +282,7 @@
 #        define ZEXTERN extern __declspec(dllimport)
 #      endif
 #    endif
-#  endif /* ZLIB_DLL */
+#  endif  /* ZLIB_DLL */
    /* If building or using zlib with the WINAPI/WINAPIV calling convention,
     * define ZLIB_WINAPI.
     * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
@@ -247,75 +330,99 @@
 #endif
 
 #if !defined(__MACTYPES__)
-typedef unsigned char Byte;	/* 8 bits */
+typedef unsigned char  Byte;  /* 8 bits */
 #endif
-typedef unsigned int uInt;	/* 16 bits or more */
-typedef unsigned long uLong;	/* 32 bits or more */
+typedef unsigned int   uInt;  /* 16 bits or more */
+typedef unsigned long  uLong; /* 32 bits or more */
 
 #ifdef SMALL_MEDIUM
    /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
 #  define Bytef Byte FAR
 #else
-typedef Byte FAR Bytef;
+   typedef Byte  FAR Bytef;
 #endif
-typedef char FAR charf;
-typedef int FAR intf;
-typedef uInt FAR uIntf;
+typedef char  FAR charf;
+typedef int   FAR intf;
+typedef uInt  FAR uIntf;
 typedef uLong FAR uLongf;
 
 #ifdef STDC
-typedef void const *voidpc;
-typedef void FAR *voidpf;
-typedef void *voidp;
+   typedef void const *voidpc;
+   typedef void FAR   *voidpf;
+   typedef void       *voidp;
 #else
-typedef Byte const *voidpc;
-typedef Byte FAR *voidpf;
-typedef Byte *voidp;
+   typedef Byte const *voidpc;
+   typedef Byte FAR   *voidpf;
+   typedef Byte       *voidp;
+#endif
+
+#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */
+#  define Z_HAVE_UNISTD_H
+#endif
+
+#ifdef STDC
+#  include <sys/types.h>    /* for off_t */
 #endif
 
-#if 0				/* HAVE_UNISTD_H -- this line is updated by ./configure */
-#  include <sys/types.h>	/* for off_t */
-#  include <unistd.h>		/* for SEEK_* and off_t */
+/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
+ * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
+ * though the former does not conform to the LFS document), but considering
+ * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
+ * equivalently requesting no 64-bit operations
+ */
+#if -_LARGEFILE64_SOURCE - -1 == 1
+#  undef _LARGEFILE64_SOURCE
+#endif
+
+#if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE)
+#  include <unistd.h>       /* for SEEK_* and off_t */
 #  ifdef VMS
-#    include <unixio.h>		/* for off_t */
+#    include <unixio.h>     /* for off_t */
+#  endif
+#  ifndef z_off_t
+#    define z_off_t off_t
 #  endif
-#  define z_off_t  off_t
 #endif
+
 #ifndef SEEK_SET
-#  define SEEK_SET        0	/* Seek from beginning of file.  */
-#  define SEEK_CUR        1	/* Seek from current position.  */
-#  define SEEK_END        2	/* Set file pointer to EOF plus "offset" */
+#  define SEEK_SET        0       /* Seek from beginning of file.  */
+#  define SEEK_CUR        1       /* Seek from current position.  */
+#  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
 #endif
+
 #ifndef z_off_t
-#  define  z_off_t long
+#  define z_off_t long
+#endif
+
+#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
+#  define z_off64_t off64_t
+#else
+#  define z_off64_t z_off_t
 #endif
 
 #if defined(__OS400__)
-#define NO_vsnprintf
+#  define NO_vsnprintf
 #endif
 
 #if defined(__MVS__)
 #  define NO_vsnprintf
-#  ifdef FAR
-#    undef FAR
-#  endif
 #endif
 
 /* MVS linker does not support external names larger than 8 bytes */
 #if defined(__MVS__)
-#   pragma map(deflateInit_,"DEIN")
-#   pragma map(deflateInit2_,"DEIN2")
-#   pragma map(deflateEnd,"DEEND")
-#   pragma map(deflateBound,"DEBND")
-#   pragma map(inflateInit_,"ININ")
-#   pragma map(inflateInit2_,"ININ2")
-#   pragma map(inflateEnd,"INEND")
-#   pragma map(inflateSync,"INSY")
-#   pragma map(inflateSetDictionary,"INSEDI")
-#   pragma map(compressBound,"CMBND")
-#   pragma map(inflate_table,"INTABL")
-#   pragma map(inflate_fast,"INFA")
-#   pragma map(inflate_copyright,"INCOPY")
+  #pragma map(deflateInit_,"DEIN")
+  #pragma map(deflateInit2_,"DEIN2")
+  #pragma map(deflateEnd,"DEEND")
+  #pragma map(deflateBound,"DEBND")
+  #pragma map(inflateInit_,"ININ")
+  #pragma map(inflateInit2_,"ININ2")
+  #pragma map(inflateEnd,"INEND")
+  #pragma map(inflateSync,"INSY")
+  #pragma map(inflateSetDictionary,"INSEDI")
+  #pragma map(compressBound,"CMBND")
+  #pragma map(inflate_table,"INTABL")
+  #pragma map(inflate_fast,"INFA")
+  #pragma map(inflate_copyright,"INCOPY")
 #endif
 
 #endif /* ZCONF_H */
diff --git a/com32/include/zlib.h b/com32/include/zlib.h
index 92edf96..bfbba83 100644
--- a/com32/include/zlib.h
+++ b/com32/include/zlib.h
@@ -1,7 +1,7 @@
 /* zlib.h -- interface of the 'zlib' general purpose compression library
-  version 1.2.1, November 17th, 2003
+  version 1.2.5, April 19th, 2010
 
-  Copyright (C) 1995-2003 Jean-loup Gailly and Mark Adler
+  Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -37,43 +37,44 @@
 extern "C" {
 #endif
 
-#define ZLIB_VERSION "1.2.1"
-#define ZLIB_VERNUM 0x1210
+#define ZLIB_VERSION "1.2.5"
+#define ZLIB_VERNUM 0x1250
+#define ZLIB_VER_MAJOR 1
+#define ZLIB_VER_MINOR 2
+#define ZLIB_VER_REVISION 5
+#define ZLIB_VER_SUBREVISION 0
 
 /*
-     The 'zlib' compression library provides in-memory compression and
-  decompression functions, including integrity checks of the uncompressed
-  data.  This version of the library supports only one compression method
-  (deflation) but other algorithms will be added later and will have the same
-  stream interface.
-
-     Compression can be done in a single step if the buffers are large
-  enough (for example if an input file is mmap'ed), or can be done by
-  repeated calls of the compression function.  In the latter case, the
-  application must provide more input and/or consume the output
+    The 'zlib' compression library provides in-memory compression and
+  decompression functions, including integrity checks of the uncompressed data.
+  This version of the library supports only one compression method (deflation)
+  but other algorithms will be added later and will have the same stream
+  interface.
+
+    Compression can be done in a single step if the buffers are large enough,
+  or can be done by repeated calls of the compression function.  In the latter
+  case, the application must provide more input and/or consume the output
   (providing more output space) before each call.
 
-     The compressed data format used by the in-memory functions is the zlib
-  format, which is a zlib wrapper documented in RFC 1950, wrapped around a
-  deflate stream, which is itself documented in RFC 1951.
+    The compressed data format used by default by the in-memory functions is
+  the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
+  around a deflate stream, which is itself documented in RFC 1951.
 
-     The library also supports reading and writing files in gzip (.gz) format
+    The library also supports reading and writing files in gzip (.gz) format
   with an interface similar to that of stdio using the functions that start
   with "gz".  The gzip format is different from the zlib format.  gzip is a
   gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
 
-     The zlib format was designed to be compact and fast for use in memory
+    This library can optionally read and write gzip streams in memory as well.
+
+    The zlib format was designed to be compact and fast for use in memory
   and on communications channels.  The gzip format was designed for single-
   file compression on file systems, has a larger header than zlib to maintain
   directory information, and uses a different, slower check method than zlib.
 
-     This library does not provide any functions to write gzip files in memory.
-  However such functions could be easily written using zlib's deflate function,
-  the documentation in the gzip RFC, and the examples in gzio.c.
-
-     The library does not install any signal handler. The decoder checks
-  the consistency of the compressed data, so the library should never
-  crash even in case of corrupted input.
+    The library does not install any signal handler.  The decoder checks
+  the consistency of the compressed data, so the library should never crash
+  even in case of corrupted input.
 */
 
 typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
@@ -97,7 +98,7 @@ typedef struct z_stream_s {
     free_func  zfree;   /* used to free the internal state */
     voidpf     opaque;  /* private data object passed to zalloc and zfree */
 
-    int     data_type;  /* best guess about the data type: ascii or binary */
+    int     data_type;  /* best guess about the data type: binary or text */
     uLong   adler;      /* adler32 value of the uncompressed data */
     uLong   reserved;   /* reserved for future use */
 } z_stream;
@@ -105,45 +106,68 @@ typedef struct z_stream_s {
 typedef z_stream FAR *z_streamp;
 
 /*
-   The application must update next_in and avail_in when avail_in has
-   dropped to zero. It must update next_out and avail_out when avail_out
-   has dropped to zero. The application must initialize zalloc, zfree and
-   opaque before calling the init function. All other fields are set by the
-   compression library and must not be updated by the application.
+     gzip header information passed to and from zlib routines.  See RFC 1952
+  for more details on the meanings of these fields.
+*/
+typedef struct gz_header_s {
+    int     text;       /* true if compressed data believed to be text */
+    uLong   time;       /* modification time */
+    int     xflags;     /* extra flags (not used when writing a gzip file) */
+    int     os;         /* operating system */
+    Bytef   *extra;     /* pointer to extra field or Z_NULL if none */
+    uInt    extra_len;  /* extra field length (valid if extra != Z_NULL) */
+    uInt    extra_max;  /* space at extra (only when reading header) */
+    Bytef   *name;      /* pointer to zero-terminated file name or Z_NULL */
+    uInt    name_max;   /* space at name (only when reading header) */
+    Bytef   *comment;   /* pointer to zero-terminated comment or Z_NULL */
+    uInt    comm_max;   /* space at comment (only when reading header) */
+    int     hcrc;       /* true if there was or will be a header crc */
+    int     done;       /* true when done reading gzip header (not used
+                           when writing a gzip file) */
+} gz_header;
+
+typedef gz_header FAR *gz_headerp;
 
-   The opaque value provided by the application will be passed as the first
-   parameter for calls of zalloc and zfree. This can be useful for custom
-   memory management. The compression library attaches no meaning to the
+/*
+     The application must update next_in and avail_in when avail_in has dropped
+   to zero.  It must update next_out and avail_out when avail_out has dropped
+   to zero.  The application must initialize zalloc, zfree and opaque before
+   calling the init function.  All other fields are set by the compression
+   library and must not be updated by the application.
+
+     The opaque value provided by the application will be passed as the first
+   parameter for calls of zalloc and zfree.  This can be useful for custom
+   memory management.  The compression library attaches no meaning to the
    opaque value.
 
-   zalloc must return Z_NULL if there is not enough memory for the object.
+     zalloc must return Z_NULL if there is not enough memory for the object.
    If zlib is used in a multi-threaded application, zalloc and zfree must be
    thread safe.
 
-   On 16-bit systems, the functions zalloc and zfree must be able to allocate
-   exactly 65536 bytes, but will not be required to allocate more than this
-   if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
-   pointers returned by zalloc for objects of exactly 65536 bytes *must*
-   have their offset normalized to zero. The default allocation function
-   provided by this library ensures this (see zutil.c). To reduce memory
-   requirements and avoid any allocation of 64K objects, at the expense of
-   compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
-
-   The fields total_in and total_out can be used for statistics or
-   progress reports. After compression, total_in holds the total size of
-   the uncompressed data and may be saved for use in the decompressor
-   (particularly if the decompressor wants to decompress everything in
-   a single step).
+     On 16-bit systems, the functions zalloc and zfree must be able to allocate
+   exactly 65536 bytes, but will not be required to allocate more than this if
+   the symbol MAXSEG_64K is defined (see zconf.h).  WARNING: On MSDOS, pointers
+   returned by zalloc for objects of exactly 65536 bytes *must* have their
+   offset normalized to zero.  The default allocation function provided by this
+   library ensures this (see zutil.c).  To reduce memory requirements and avoid
+   any allocation of 64K objects, at the expense of compression ratio, compile
+   the library with -DMAX_WBITS=14 (see zconf.h).
+
+     The fields total_in and total_out can be used for statistics or progress
+   reports.  After compression, total_in holds the total size of the
+   uncompressed data and may be saved for use in the decompressor (particularly
+   if the decompressor wants to decompress everything in a single step).
 */
 
                         /* constants */
 
 #define Z_NO_FLUSH      0
-#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
+#define Z_PARTIAL_FLUSH 1
 #define Z_SYNC_FLUSH    2
 #define Z_FULL_FLUSH    3
 #define Z_FINISH        4
 #define Z_BLOCK         5
+#define Z_TREES         6
 /* Allowed flush values; see deflate() and inflate() below for details */
 
 #define Z_OK            0
@@ -155,8 +179,8 @@ typedef z_stream FAR *z_streamp;
 #define Z_MEM_ERROR    (-4)
 #define Z_BUF_ERROR    (-5)
 #define Z_VERSION_ERROR (-6)
-/* Return codes for the compression/decompression functions. Negative
- * values are errors, positive values are used for special but normal events.
+/* Return codes for the compression/decompression functions. Negative values
+ * are errors, positive values are used for special but normal events.
  */
 
 #define Z_NO_COMPRESSION         0
@@ -168,11 +192,13 @@ typedef z_stream FAR *z_streamp;
 #define Z_FILTERED            1
 #define Z_HUFFMAN_ONLY        2
 #define Z_RLE                 3
+#define Z_FIXED               4
 #define Z_DEFAULT_STRATEGY    0
 /* compression strategy; see deflateInit2() below for details */
 
 #define Z_BINARY   0
-#define Z_ASCII    1
+#define Z_TEXT     1
+#define Z_ASCII    Z_TEXT   /* for compatibility with 1.2.2 and earlier */
 #define Z_UNKNOWN  2
 /* Possible values of the data_type field (though see inflate()) */
 
@@ -184,115 +210,140 @@ typedef z_stream FAR *z_streamp;
 #define zlib_version zlibVersion()
 /* for compatibility with versions < 1.0.2 */
 
+
                         /* basic functions */
 
 ZEXTERN const char * ZEXPORT zlibVersion OF((void));
 /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
-   If the first character differs, the library code actually used is
-   not compatible with the zlib.h header file used by the application.
-   This check is automatically made by deflateInit and inflateInit.
+   If the first character differs, the library code actually used is not
+   compatible with the zlib.h header file used by the application.  This check
+   is automatically made by deflateInit and inflateInit.
  */
 
 /*
 ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
 
-     Initializes the internal stream state for compression. The fields
-   zalloc, zfree and opaque must be initialized before by the caller.
-   If zalloc and zfree are set to Z_NULL, deflateInit updates them to
-   use default allocation functions.
+     Initializes the internal stream state for compression.  The fields
+   zalloc, zfree and opaque must be initialized before by the caller.  If
+   zalloc and zfree are set to Z_NULL, deflateInit updates them to use default
+   allocation functions.
 
      The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
-   1 gives best speed, 9 gives best compression, 0 gives no compression at
-   all (the input data is simply copied a block at a time).
-   Z_DEFAULT_COMPRESSION requests a default compromise between speed and
-   compression (currently equivalent to level 6).
+   1 gives best speed, 9 gives best compression, 0 gives no compression at all
+   (the input data is simply copied a block at a time).  Z_DEFAULT_COMPRESSION
+   requests a default compromise between speed and compression (currently
+   equivalent to level 6).
 
-     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
-   enough memory, Z_STREAM_ERROR if level is not a valid compression level,
+     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_STREAM_ERROR if level is not a valid compression level, or
    Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
-   with the version assumed by the caller (ZLIB_VERSION).
-   msg is set to null if there is no error message.  deflateInit does not
-   perform any compression: this will be done by deflate().
+   with the version assumed by the caller (ZLIB_VERSION).  msg is set to null
+   if there is no error message.  deflateInit does not perform any compression:
+   this will be done by deflate().
 */
 
 
 ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
 /*
     deflate compresses as much data as possible, and stops when the input
-  buffer becomes empty or the output buffer becomes full. It may introduce some
-  output latency (reading input without producing any output) except when
+  buffer becomes empty or the output buffer becomes full.  It may introduce
+  some output latency (reading input without producing any output) except when
   forced to flush.
 
-    The detailed semantics are as follows. deflate performs one or both of the
+    The detailed semantics are as follows.  deflate performs one or both of the
   following actions:
 
   - Compress more input starting at next_in and update next_in and avail_in
-    accordingly. If not all input can be processed (because there is not
+    accordingly.  If not all input can be processed (because there is not
     enough room in the output buffer), next_in and avail_in are updated and
     processing will resume at this point for the next call of deflate().
 
   - Provide more output starting at next_out and update next_out and avail_out
-    accordingly. This action is forced if the parameter flush is non zero.
+    accordingly.  This action is forced if the parameter flush is non zero.
     Forcing flush frequently degrades the compression ratio, so this parameter
-    should be set only when necessary (in interactive applications).
-    Some output may be provided even if flush is not set.
-
-  Before the call of deflate(), the application should ensure that at least
-  one of the actions is possible, by providing more input and/or consuming
-  more output, and updating avail_in or avail_out accordingly; avail_out
-  should never be zero before the call. The application can consume the
-  compressed output when it wants, for example when the output buffer is full
-  (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
-  and with zero avail_out, it must be called again after making room in the
-  output buffer because there might be more output pending.
+    should be set only when necessary (in interactive applications).  Some
+    output may be provided even if flush is not set.
+
+    Before the call of deflate(), the application should ensure that at least
+  one of the actions is possible, by providing more input and/or consuming more
+  output, and updating avail_in or avail_out accordingly; avail_out should
+  never be zero before the call.  The application can consume the compressed
+  output when it wants, for example when the output buffer is full (avail_out
+  == 0), or after each call of deflate().  If deflate returns Z_OK and with
+  zero avail_out, it must be called again after making room in the output
+  buffer because there might be more output pending.
+
+    Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
+  decide how much data to accumulate before producing output, in order to
+  maximize compression.
 
     If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
   flushed to the output buffer and the output is aligned on a byte boundary, so
-  that the decompressor can get all input data available so far. (In particular
-  avail_in is zero after the call if enough output space has been provided
-  before the call.)  Flushing may degrade compression for some compression
-  algorithms and so it should be used only when necessary.
+  that the decompressor can get all input data available so far.  (In
+  particular avail_in is zero after the call if enough output space has been
+  provided before the call.) Flushing may degrade compression for some
+  compression algorithms and so it should be used only when necessary.  This
+  completes the current deflate block and follows it with an empty stored block
+  that is three bits plus filler bits to the next byte, followed by four bytes
+  (00 00 ff ff).
+
+    If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the
+  output buffer, but the output is not aligned to a byte boundary.  All of the
+  input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.
+  This completes the current deflate block and follows it with an empty fixed
+  codes block that is 10 bits long.  This assures that enough bytes are output
+  in order for the decompressor to finish the block before the empty fixed code
+  block.
+
+    If flush is set to Z_BLOCK, a deflate block is completed and emitted, as
+  for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to
+  seven bits of the current block are held to be written as the next byte after
+  the next deflate block is completed.  In this case, the decompressor may not
+  be provided enough bits at this point in order to complete decompression of
+  the data provided so far to the compressor.  It may need to wait for the next
+  block to be emitted.  This is for advanced applications that need to control
+  the emission of deflate blocks.
 
     If flush is set to Z_FULL_FLUSH, all output is flushed as with
   Z_SYNC_FLUSH, and the compression state is reset so that decompression can
   restart from this point if previous compressed data has been damaged or if
-  random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
-  the compression.
+  random access is desired.  Using Z_FULL_FLUSH too often can seriously degrade
+  compression.
 
     If deflate returns with avail_out == 0, this function must be called again
   with the same value of the flush parameter and more output space (updated
   avail_out), until the flush is complete (deflate returns with non-zero
-  avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
+  avail_out).  In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
   avail_out is greater than six to avoid repeated flush markers due to
   avail_out == 0 on return.
 
     If the parameter flush is set to Z_FINISH, pending input is processed,
-  pending output is flushed and deflate returns with Z_STREAM_END if there
-  was enough output space; if deflate returns with Z_OK, this function must be
+  pending output is flushed and deflate returns with Z_STREAM_END if there was
+  enough output space; if deflate returns with Z_OK, this function must be
   called again with Z_FINISH and more output space (updated avail_out) but no
-  more input data, until it returns with Z_STREAM_END or an error. After
-  deflate has returned Z_STREAM_END, the only possible operations on the
-  stream are deflateReset or deflateEnd.
+  more input data, until it returns with Z_STREAM_END or an error.  After
+  deflate has returned Z_STREAM_END, the only possible operations on the stream
+  are deflateReset or deflateEnd.
 
     Z_FINISH can be used immediately after deflateInit if all the compression
-  is to be done in a single step. In this case, avail_out must be at least
-  the value returned by deflateBound (see below). If deflate does not return
+  is to be done in a single step.  In this case, avail_out must be at least the
+  value returned by deflateBound (see below).  If deflate does not return
   Z_STREAM_END, then it must be called again as described above.
 
     deflate() sets strm->adler to the adler32 checksum of all input read
   so far (that is, total_in bytes).
 
-    deflate() may update data_type if it can make a good guess about
-  the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
-  binary. This field is only for information purposes and does not affect
-  the compression algorithm in any manner.
+    deflate() may update strm->data_type if it can make a good guess about
+  the input data type (Z_BINARY or Z_TEXT).  In doubt, the data is considered
+  binary.  This field is only for information purposes and does not affect the
+  compression algorithm in any manner.
 
     deflate() returns Z_OK if some progress has been made (more input
   processed or more output produced), Z_STREAM_END if all input has been
   consumed and all output has been produced (only when flush is set to
   Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
-  if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
-  (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
+  if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible
+  (for example avail_in or avail_out was zero).  Note that Z_BUF_ERROR is not
   fatal, and deflate() can be called again with more input and more output
   space to continue compressing.
 */
@@ -301,13 +352,13 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
 ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
 /*
      All dynamically allocated data structures for this stream are freed.
-   This function discards any unprocessed input and does not flush any
-   pending output.
+   This function discards any unprocessed input and does not flush any pending
+   output.
 
      deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
    stream state was inconsistent, Z_DATA_ERROR if the stream was freed
-   prematurely (some input or output was discarded). In the error case,
-   msg may be set but then points to a static string (which must not be
+   prematurely (some input or output was discarded).  In the error case, msg
+   may be set but then points to a static string (which must not be
    deallocated).
 */
 
@@ -315,10 +366,10 @@ ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
 /*
 ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
 
-     Initializes the internal stream state for decompression. The fields
+     Initializes the internal stream state for decompression.  The fields
    next_in, avail_in, zalloc, zfree and opaque must be initialized before by
-   the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
-   value depends on the compression method), inflateInit determines the
+   the caller.  If next_in is not Z_NULL and avail_in is large enough (the
+   exact value depends on the compression method), inflateInit determines the
    compression method from the zlib header and allocates all data structures
    accordingly; otherwise the allocation will be deferred to the first call of
    inflate.  If zalloc and zfree are set to Z_NULL, inflateInit updates them to
@@ -326,95 +377,108 @@ ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
 
      inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
    memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
-   version assumed by the caller.  msg is set to null if there is no error
-   message. inflateInit does not perform any decompression apart from reading
-   the zlib header if present: this will be done by inflate().  (So next_in and
-   avail_in may be modified, but next_out and avail_out are unchanged.)
+   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
+   invalid, such as a null pointer to the structure.  msg is set to null if
+   there is no error message.  inflateInit does not perform any decompression
+   apart from possibly reading the zlib header if present: actual decompression
+   will be done by inflate().  (So next_in and avail_in may be modified, but
+   next_out and avail_out are unused and unchanged.) The current implementation
+   of inflateInit() does not process any header information -- that is deferred
+   until inflate() is called.
 */
 
 
 ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
 /*
     inflate decompresses as much data as possible, and stops when the input
-  buffer becomes empty or the output buffer becomes full. It may introduce
+  buffer becomes empty or the output buffer becomes full.  It may introduce
   some output latency (reading input without producing any output) except when
   forced to flush.
 
-  The detailed semantics are as follows. inflate performs one or both of the
+  The detailed semantics are as follows.  inflate performs one or both of the
   following actions:
 
   - Decompress more input starting at next_in and update next_in and avail_in
-    accordingly. If not all input can be processed (because there is not
-    enough room in the output buffer), next_in is updated and processing
-    will resume at this point for the next call of inflate().
+    accordingly.  If not all input can be processed (because there is not
+    enough room in the output buffer), next_in is updated and processing will
+    resume at this point for the next call of inflate().
 
   - Provide more output starting at next_out and update next_out and avail_out
-    accordingly.  inflate() provides as much output as possible, until there
-    is no more input data or no more space in the output buffer (see below
-    about the flush parameter).
-
-  Before the call of inflate(), the application should ensure that at least
-  one of the actions is possible, by providing more input and/or consuming
-  more output, and updating the next_* and avail_* values accordingly.
-  The application can consume the uncompressed output when it wants, for
-  example when the output buffer is full (avail_out == 0), or after each
-  call of inflate(). If inflate returns Z_OK and with zero avail_out, it
-  must be called again after making room in the output buffer because there
-  might be more output pending.
-
-    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
-  Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
-  output as possible to the output buffer. Z_BLOCK requests that inflate() stop
-  if and when it get to the next deflate block boundary. When decoding the zlib
-  or gzip format, this will cause inflate() to return immediately after the
-  header and before the first block. When doing a raw inflate, inflate() will
-  go ahead and process the first block, and will return when it gets to the end
-  of that block, or when it runs out of data.
+    accordingly.  inflate() provides as much output as possible, until there is
+    no more input data or no more space in the output buffer (see below about
+    the flush parameter).
+
+    Before the call of inflate(), the application should ensure that at least
+  one of the actions is possible, by providing more input and/or consuming more
+  output, and updating the next_* and avail_* values accordingly.  The
+  application can consume the uncompressed output when it wants, for example
+  when the output buffer is full (avail_out == 0), or after each call of
+  inflate().  If inflate returns Z_OK and with zero avail_out, it must be
+  called again after making room in the output buffer because there might be
+  more output pending.
+
+    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,
+  Z_BLOCK, or Z_TREES.  Z_SYNC_FLUSH requests that inflate() flush as much
+  output as possible to the output buffer.  Z_BLOCK requests that inflate()
+  stop if and when it gets to the next deflate block boundary.  When decoding
+  the zlib or gzip format, this will cause inflate() to return immediately
+  after the header and before the first block.  When doing a raw inflate,
+  inflate() will go ahead and process the first block, and will return when it
+  gets to the end of that block, or when it runs out of data.
 
     The Z_BLOCK option assists in appending to or combining deflate streams.
   Also to assist in this, on return inflate() will set strm->data_type to the
-  number of unused bits in the last byte taken from strm->next_in, plus 64
-  if inflate() is currently decoding the last block in the deflate stream,
-  plus 128 if inflate() returned immediately after decoding an end-of-block
-  code or decoding the complete header up to just before the first byte of the
-  deflate stream. The end-of-block will not be indicated until all of the
-  uncompressed data from that block has been written to strm->next_out.  The
-  number of unused bits may in general be greater than seven, except when
-  bit 7 of data_type is set, in which case the number of unused bits will be
-  less than eight.
+  number of unused bits in the last byte taken from strm->next_in, plus 64 if
+  inflate() is currently decoding the last block in the deflate stream, plus
+  128 if inflate() returned immediately after decoding an end-of-block code or
+  decoding the complete header up to just before the first byte of the deflate
+  stream.  The end-of-block will not be indicated until all of the uncompressed
+  data from that block has been written to strm->next_out.  The number of
+  unused bits may in general be greater than seven, except when bit 7 of
+  data_type is set, in which case the number of unused bits will be less than
+  eight.  data_type is set as noted here every time inflate() returns for all
+  flush options, and so can be used to determine the amount of currently
+  consumed input in bits.
+
+    The Z_TREES option behaves as Z_BLOCK does, but it also returns when the
+  end of each deflate block header is reached, before any actual data in that
+  block is decoded.  This allows the caller to determine the length of the
+  deflate block header for later use in random access within a deflate block.
+  256 is added to the value of strm->data_type when inflate() returns
+  immediately after reaching the end of the deflate block header.
 
     inflate() should normally be called until it returns Z_STREAM_END or an
-  error. However if all decompression is to be performed in a single step
-  (a single call of inflate), the parameter flush should be set to
-  Z_FINISH. In this case all pending input is processed and all pending
-  output is flushed; avail_out must be large enough to hold all the
-  uncompressed data. (The size of the uncompressed data may have been saved
-  by the compressor for this purpose.) The next operation on this stream must
-  be inflateEnd to deallocate the decompression state. The use of Z_FINISH
-  is never required, but can be used to inform inflate that a faster approach
-  may be used for the single inflate() call.
+  error.  However if all decompression is to be performed in a single step (a
+  single call of inflate), the parameter flush should be set to Z_FINISH.  In
+  this case all pending input is processed and all pending output is flushed;
+  avail_out must be large enough to hold all the uncompressed data.  (The size
+  of the uncompressed data may have been saved by the compressor for this
+  purpose.) The next operation on this stream must be inflateEnd to deallocate
+  the decompression state.  The use of Z_FINISH is never required, but can be
+  used to inform inflate that a faster approach may be used for the single
+  inflate() call.
 
      In this implementation, inflate() always flushes as much output as
   possible to the output buffer, and always uses the faster approach on the
-  first call. So the only effect of the flush parameter in this implementation
+  first call.  So the only effect of the flush parameter in this implementation
   is on the return value of inflate(), as noted below, or when it returns early
-  because Z_BLOCK is used.
+  because Z_BLOCK or Z_TREES is used.
 
      If a preset dictionary is needed after this call (see inflateSetDictionary
-  below), inflate sets strm-adler to the adler32 checksum of the dictionary
+  below), inflate sets strm->adler to the adler32 checksum of the dictionary
   chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
   strm->adler to the adler32 checksum of all output produced so far (that is,
   total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
-  below. At the end of the stream, inflate() checks that its computed adler32
+  below.  At the end of the stream, inflate() checks that its computed adler32
   checksum is equal to that saved by the compressor and returns Z_STREAM_END
   only if the checksum is correct.
 
-    inflate() will decompress and check either zlib-wrapped or gzip-wrapped
-  deflate data.  The header type is detected automatically.  Any information
-  contained in the gzip header is not retained, so applications that need that
-  information should instead use raw inflate, see inflateInit2() below, or
-  inflateBack() and perform their own processing of the gzip header and
-  trailer.
+    inflate() can decompress and check either zlib-wrapped or gzip-wrapped
+  deflate data.  The header type is detected automatically, if requested when
+  initializing with inflateInit2().  Any information contained in the gzip
+  header is not retained, so applications that need that information should
+  instead use raw inflate, see inflateInit2() below, or inflateBack() and
+  perform their own processing of the gzip header and trailer.
 
     inflate() returns Z_OK if some progress has been made (more input processed
   or more output produced), Z_STREAM_END if the end of the compressed data has
@@ -422,27 +486,28 @@ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
   preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
   corrupted (input stream not conforming to the zlib format or incorrect check
   value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
-  if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
+  next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory,
   Z_BUF_ERROR if no progress is possible or if there was not enough room in the
-  output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
+  output buffer when Z_FINISH is used.  Note that Z_BUF_ERROR is not fatal, and
   inflate() can be called again with more input and more output space to
-  continue decompressing. If Z_DATA_ERROR is returned, the application may then
-  call inflateSync() to look for a good compression block if a partial recovery
-  of the data is desired.
+  continue decompressing.  If Z_DATA_ERROR is returned, the application may
+  then call inflateSync() to look for a good compression block if a partial
+  recovery of the data is desired.
 */
 
 
 ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
 /*
      All dynamically allocated data structures for this stream are freed.
-   This function discards any unprocessed input and does not flush any
-   pending output.
+   This function discards any unprocessed input and does not flush any pending
+   output.
 
      inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
-   was inconsistent. In the error case, msg may be set but then points to a
+   was inconsistent.  In the error case, msg may be set but then points to a
    static string (which must not be deallocated).
 */
 
+
                         /* Advanced functions */
 
 /*
@@ -457,52 +522,57 @@ ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
                                      int  memLevel,
                                      int  strategy));
 
-     This is another version of deflateInit with more compression options. The
-   fields next_in, zalloc, zfree and opaque must be initialized before by
-   the caller.
+     This is another version of deflateInit with more compression options.  The
+   fields next_in, zalloc, zfree and opaque must be initialized before by the
+   caller.
 
-     The method parameter is the compression method. It must be Z_DEFLATED in
+     The method parameter is the compression method.  It must be Z_DEFLATED in
    this version of the library.
 
      The windowBits parameter is the base two logarithm of the window size
-   (the size of the history buffer). It should be in the range 8..15 for this
-   version of the library. Larger values of this parameter result in better
-   compression at the expense of memory usage. The default value is 15 if
+   (the size of the history buffer).  It should be in the range 8..15 for this
+   version of the library.  Larger values of this parameter result in better
+   compression at the expense of memory usage.  The default value is 15 if
    deflateInit is used instead.
 
-     windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
-   determines the window size. deflate() will then generate raw deflate data
+     windowBits can also be -8..-15 for raw deflate.  In this case, -windowBits
+   determines the window size.  deflate() will then generate raw deflate data
    with no zlib header or trailer, and will not compute an adler32 check value.
 
-     windowBits can also be greater than 15 for optional gzip encoding. Add
+     windowBits can also be greater than 15 for optional gzip encoding.  Add
    16 to windowBits to write a simple gzip header and trailer around the
-   compressed data instead of a zlib wrapper. The gzip header will have no
-   file name, no extra data, no comment, no modification time (set to zero),
-   no header crc, and the operating system will be set to 255 (unknown).
+   compressed data instead of a zlib wrapper.  The gzip header will have no
+   file name, no extra data, no comment, no modification time (set to zero), no
+   header crc, and the operating system will be set to 255 (unknown).  If a
+   gzip stream is being written, strm->adler is a crc32 instead of an adler32.
 
      The memLevel parameter specifies how much memory should be allocated
-   for the internal compression state. memLevel=1 uses minimum memory but
-   is slow and reduces compression ratio; memLevel=9 uses maximum memory
-   for optimal speed. The default value is 8. See zconf.h for total memory
-   usage as a function of windowBits and memLevel.
+   for the internal compression state.  memLevel=1 uses minimum memory but is
+   slow and reduces compression ratio; memLevel=9 uses maximum memory for
+   optimal speed.  The default value is 8.  See zconf.h for total memory usage
+   as a function of windowBits and memLevel.
 
-     The strategy parameter is used to tune the compression algorithm. Use the
+     The strategy parameter is used to tune the compression algorithm.  Use the
    value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
    filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
    string match), or Z_RLE to limit match distances to one (run-length
-   encoding). Filtered data consists mostly of small values with a somewhat
-   random distribution. In this case, the compression algorithm is tuned to
-   compress them better. The effect of Z_FILTERED is to force more Huffman
+   encoding).  Filtered data consists mostly of small values with a somewhat
+   random distribution.  In this case, the compression algorithm is tuned to
+   compress them better.  The effect of Z_FILTERED is to force more Huffman
    coding and less string matching; it is somewhat intermediate between
-   Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
-   Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
-   parameter only affects the compression ratio but not the correctness of the
-   compressed output even if it is not set appropriately.
-
-      deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
-   memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
-   method). msg is set to null if there is no error message.  deflateInit2 does
-   not perform any compression: this will be done by deflate().
+   Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY.  Z_RLE is designed to be almost as
+   fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data.  The
+   strategy parameter only affects the compression ratio but not the
+   correctness of the compressed output even if it is not set appropriately.
+   Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler
+   decoder for special applications.
+
+     deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid
+   method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is
+   incompatible with the version assumed by the caller (ZLIB_VERSION).  msg is
+   set to null if there is no error message.  deflateInit2 does not perform any
+   compression: this will be done by deflate().
 */
 
 ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
@@ -510,35 +580,37 @@ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
                                              uInt  dictLength));
 /*
      Initializes the compression dictionary from the given byte sequence
-   without producing any compressed output. This function must be called
-   immediately after deflateInit, deflateInit2 or deflateReset, before any
-   call of deflate. The compressor and decompressor must use exactly the same
+   without producing any compressed output.  This function must be called
+   immediately after deflateInit, deflateInit2 or deflateReset, before any call
+   of deflate.  The compressor and decompressor must use exactly the same
    dictionary (see inflateSetDictionary).
 
      The dictionary should consist of strings (byte sequences) that are likely
    to be encountered later in the data to be compressed, with the most commonly
-   used strings preferably put towards the end of the dictionary. Using a
+   used strings preferably put towards the end of the dictionary.  Using a
    dictionary is most useful when the data to be compressed is short and can be
    predicted with good accuracy; the data can then be compressed better than
    with the default empty dictionary.
 
      Depending on the size of the compression data structures selected by
    deflateInit or deflateInit2, a part of the dictionary may in effect be
-   discarded, for example if the dictionary is larger than the window size in
-   deflate or deflate2. Thus the strings most likely to be useful should be
-   put at the end of the dictionary, not at the front.
+   discarded, for example if the dictionary is larger than the window size
+   provided in deflateInit or deflateInit2.  Thus the strings most likely to be
+   useful should be put at the end of the dictionary, not at the front.  In
+   addition, the current implementation of deflate will use at most the window
+   size minus 262 bytes of the provided dictionary.
 
      Upon return of this function, strm->adler is set to the adler32 value
    of the dictionary; the decompressor may later use this value to determine
-   which dictionary has been used by the compressor. (The adler32 value
+   which dictionary has been used by the compressor.  (The adler32 value
    applies to the whole dictionary even if only a subset of the dictionary is
    actually used by the compressor.) If a raw deflate was requested, then the
    adler32 value is not computed and strm->adler is not set.
 
      deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
-   parameter is invalid (such as NULL dictionary) or the stream state is
+   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
    inconsistent (for example if deflate has already been called for this stream
-   or if the compression method is bsort). deflateSetDictionary does not
+   or if the compression method is bsort).  deflateSetDictionary does not
    perform any compression: this will be done by deflate().
 */
 
@@ -549,26 +621,26 @@ ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
 
      This function can be useful when several compression strategies will be
    tried, for example when there are several ways of pre-processing the input
-   data with a filter. The streams that will be discarded should then be freed
+   data with a filter.  The streams that will be discarded should then be freed
    by calling deflateEnd.  Note that deflateCopy duplicates the internal
-   compression state which can be quite large, so this strategy is slow and
-   can consume lots of memory.
+   compression state which can be quite large, so this strategy is slow and can
+   consume lots of memory.
 
      deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
    enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
-   (such as zalloc being NULL). msg is left unchanged in both source and
+   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
    destination.
 */
 
 ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
 /*
      This function is equivalent to deflateEnd followed by deflateInit,
-   but does not free and reallocate all the internal compression state.
-   The stream will keep the same compression level and any other attributes
-   that may have been set by deflateInit2.
+   but does not free and reallocate all the internal compression state.  The
+   stream will keep the same compression level and any other attributes that
+   may have been set by deflateInit2.
 
-      deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
-   stream state was inconsistent (such as zalloc or state being NULL).
+     deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL).
 */
 
 ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
@@ -578,27 +650,45 @@ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
      Dynamically update the compression level and compression strategy.  The
    interpretation of level and strategy is as in deflateInit2.  This can be
    used to switch between compression and straight copy of the input data, or
-   to switch to a different kind of input data requiring a different
-   strategy. If the compression level is changed, the input available so far
-   is compressed with the old level (and may be flushed); the new level will
-   take effect only at the next call of deflate().
+   to switch to a different kind of input data requiring a different strategy.
+   If the compression level is changed, the input available so far is
+   compressed with the old level (and may be flushed); the new level will take
+   effect only at the next call of deflate().
 
      Before the call of deflateParams, the stream state must be set as for
-   a call of deflate(), since the currently available input may have to
-   be compressed and flushed. In particular, strm->avail_out must be non-zero.
+   a call of deflate(), since the currently available input may have to be
+   compressed and flushed.  In particular, strm->avail_out must be non-zero.
 
      deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
-   stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
-   if strm->avail_out was zero.
+   stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if
+   strm->avail_out was zero.
 */
 
+ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
+                                    int good_length,
+                                    int max_lazy,
+                                    int nice_length,
+                                    int max_chain));
+/*
+     Fine tune deflate's internal compression parameters.  This should only be
+   used by someone who understands the algorithm used by zlib's deflate for
+   searching for the best matching string, and even then only by the most
+   fanatic optimizer trying to squeeze out the last compressed bit for their
+   specific input data.  Read the deflate.c source code for the meaning of the
+   max_lazy, good_length, nice_length, and max_chain parameters.
+
+     deflateTune() can be called after deflateInit() or deflateInit2(), and
+   returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
+ */
+
 ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
                                        uLong sourceLen));
 /*
      deflateBound() returns an upper bound on the compressed size after
-   deflation of sourceLen bytes.  It must be called after deflateInit()
-   or deflateInit2().  This would be used to allocate an output buffer
-   for deflation in a single pass, and so would be called before deflate().
+   deflation of sourceLen bytes.  It must be called after deflateInit() or
+   deflateInit2(), and after deflateSetHeader(), if used.  This would be used
+   to allocate an output buffer for deflation in a single pass, and so would be
+   called before deflate().
 */
 
 ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
@@ -606,14 +696,38 @@ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
                                      int value));
 /*
      deflatePrime() inserts bits in the deflate output stream.  The intent
-  is that this function is used to start off the deflate output with the
-  bits leftover from a previous deflate stream when appending to it.  As such,
-  this function can only be used for raw deflate, and must be used before the
-  first deflate() call after a deflateInit2() or deflateReset().  bits must be
-  less than or equal to 16, and that many of the least significant bits of
-  value will be inserted in the output.
-
-      deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
+   is that this function is used to start off the deflate output with the bits
+   leftover from a previous deflate stream when appending to it.  As such, this
+   function can only be used for raw deflate, and must be used before the first
+   deflate() call after a deflateInit2() or deflateReset().  bits must be less
+   than or equal to 16, and that many of the least significant bits of value
+   will be inserted in the output.
+
+     deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
+*/
+
+ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
+                                         gz_headerp head));
+/*
+     deflateSetHeader() provides gzip header information for when a gzip
+   stream is requested by deflateInit2().  deflateSetHeader() may be called
+   after deflateInit2() or deflateReset() and before the first call of
+   deflate().  The text, time, os, extra field, name, and comment information
+   in the provided gz_header structure are written to the gzip header (xflag is
+   ignored -- the extra flags are set according to the compression level).  The
+   caller must assure that, if not Z_NULL, name and comment are terminated with
+   a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
+   available there.  If hcrc is true, a gzip header crc is included.  Note that
+   the current versions of the command-line version of gzip (up through version
+   1.3.x) do not support header crc's, and will report that it is a "multi-part
+   gzip file" and give up.
+
+     If deflateSetHeader is not used, the default gzip header has text false,
+   the time set to zero, and os set to 255, with no extra, name, or comment
+   fields.  The gzip header is returned to the default state by deflateReset().
+
+     deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
    stream state was inconsistent.
 */
 
@@ -621,42 +735,50 @@ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
 ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
                                      int  windowBits));
 
-     This is another version of inflateInit with an extra parameter. The
+     This is another version of inflateInit with an extra parameter.  The
    fields next_in, avail_in, zalloc, zfree and opaque must be initialized
    before by the caller.
 
      The windowBits parameter is the base two logarithm of the maximum window
    size (the size of the history buffer).  It should be in the range 8..15 for
-   this version of the library. The default value is 15 if inflateInit is used
-   instead. windowBits must be greater than or equal to the windowBits value
+   this version of the library.  The default value is 15 if inflateInit is used
+   instead.  windowBits must be greater than or equal to the windowBits value
    provided to deflateInit2() while compressing, or it must be equal to 15 if
-   deflateInit2() was not used. If a compressed stream with a larger window
+   deflateInit2() was not used.  If a compressed stream with a larger window
    size is given as input, inflate() will return with the error code
    Z_DATA_ERROR instead of trying to allocate a larger window.
 
-     windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
-   determines the window size. inflate() will then process raw deflate data,
+     windowBits can also be zero to request that inflate use the window size in
+   the zlib header of the compressed stream.
+
+     windowBits can also be -8..-15 for raw inflate.  In this case, -windowBits
+   determines the window size.  inflate() will then process raw deflate data,
    not looking for a zlib or gzip header, not generating a check value, and not
-   looking for any check values for comparison at the end of the stream. This
+   looking for any check values for comparison at the end of the stream.  This
    is for use with other formats that use the deflate compressed data format
-   such as zip.  Those formats provide their own check values. If a custom
+   such as zip.  Those formats provide their own check values.  If a custom
    format is developed using the raw deflate format for compressed data, it is
    recommended that a check value such as an adler32 or a crc32 be applied to
    the uncompressed data as is done in the zlib, gzip, and zip formats.  For
-   most applications, the zlib format should be used as is. Note that comments
+   most applications, the zlib format should be used as is.  Note that comments
    above on the use in deflateInit2() applies to the magnitude of windowBits.
 
-     windowBits can also be greater than 15 for optional gzip decoding. Add
+     windowBits can also be greater than 15 for optional gzip decoding.  Add
    32 to windowBits to enable zlib and gzip decoding with automatic header
    detection, or add 16 to decode only the gzip format (the zlib format will
-   return a Z_DATA_ERROR).
+   return a Z_DATA_ERROR).  If a gzip stream is being decoded, strm->adler is a
+   crc32 instead of an adler32.
 
      inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
-   memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative
-   memLevel). msg is set to null if there is no error message.  inflateInit2
-   does not perform any decompression apart from reading the zlib header if
-   present: this will be done by inflate(). (So next_in and avail_in may be
-   modified, but next_out and avail_out are unchanged.)
+   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
+   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
+   invalid, such as a null pointer to the structure.  msg is set to null if
+   there is no error message.  inflateInit2 does not perform any decompression
+   apart from possibly reading the zlib header if present: actual decompression
+   will be done by inflate().  (So next_in and avail_in may be modified, but
+   next_out and avail_out are unused and unchanged.) The current implementation
+   of inflateInit2() does not process any header information -- that is
+   deferred until inflate() is called.
 */
 
 ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
@@ -664,33 +786,36 @@ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
                                              uInt  dictLength));
 /*
      Initializes the decompression dictionary from the given uncompressed byte
-   sequence. This function must be called immediately after a call of inflate
-   if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
-   can be determined from the adler32 value returned by this call of
-   inflate. The compressor and decompressor must use exactly the same
-   dictionary (see deflateSetDictionary).
+   sequence.  This function must be called immediately after a call of inflate,
+   if that call returned Z_NEED_DICT.  The dictionary chosen by the compressor
+   can be determined from the adler32 value returned by that call of inflate.
+   The compressor and decompressor must use exactly the same dictionary (see
+   deflateSetDictionary).  For raw inflate, this function can be called
+   immediately after inflateInit2() or inflateReset() and before any call of
+   inflate() to set the dictionary.  The application must insure that the
+   dictionary that was used for compression is provided.
 
      inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
-   parameter is invalid (such as NULL dictionary) or the stream state is
+   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
    inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
-   expected one (incorrect adler32 value). inflateSetDictionary does not
+   expected one (incorrect adler32 value).  inflateSetDictionary does not
    perform any decompression: this will be done by subsequent calls of
    inflate().
 */
 
 ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
 /*
-    Skips invalid compressed data until a full flush point (see above the
-  description of deflate with Z_FULL_FLUSH) can be found, or until all
-  available input is skipped. No output is provided.
-
-    inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
-  if no more input was provided, Z_DATA_ERROR if no flush point has been found,
-  or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
-  case, the application may save the current current value of total_in which
-  indicates where valid compressed data was found. In the error case, the
-  application may repeatedly call inflateSync, providing more input each time,
-  until success or end of the input data.
+     Skips invalid compressed data until a full flush point (see above the
+   description of deflate with Z_FULL_FLUSH) can be found, or until all
+   available input is skipped.  No output is provided.
+
+     inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
+   if no more input was provided, Z_DATA_ERROR if no flush point has been
+   found, or Z_STREAM_ERROR if the stream structure was inconsistent.  In the
+   success case, the application may save the current current value of total_in
+   which indicates where valid compressed data was found.  In the error case,
+   the application may repeatedly call inflateSync, providing more input each
+   time, until success or end of the input data.
 */
 
 ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
@@ -705,22 +830,123 @@ ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
 
      inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
    enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
-   (such as zalloc being NULL). msg is left unchanged in both source and
+   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
    destination.
 */
 
 ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
 /*
      This function is equivalent to inflateEnd followed by inflateInit,
-   but does not free and reallocate all the internal decompression state.
-   The stream will keep attributes that may have been set by inflateInit2.
+   but does not free and reallocate all the internal decompression state.  The
+   stream will keep attributes that may have been set by inflateInit2.
+
+     inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL).
+*/
 
-      inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
-   stream state was inconsistent (such as zalloc or state being NULL).
+ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm,
+                                      int windowBits));
+/*
+     This function is the same as inflateReset, but it also permits changing
+   the wrap and window size requests.  The windowBits parameter is interpreted
+   the same as it is for inflateInit2.
+
+     inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL), or if
+   the windowBits parameter is invalid.
+*/
+
+ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
+                                     int bits,
+                                     int value));
+/*
+     This function inserts bits in the inflate input stream.  The intent is
+   that this function is used to start inflating at a bit position in the
+   middle of a byte.  The provided bits will be used before any bytes are used
+   from next_in.  This function should only be used with raw inflate, and
+   should be used before the first inflate() call after inflateInit2() or
+   inflateReset().  bits must be less than or equal to 16, and that many of the
+   least significant bits of value will be inserted in the input.
+
+     If bits is negative, then the input stream bit buffer is emptied.  Then
+   inflatePrime() can be called again to put bits in the buffer.  This is used
+   to clear out bits leftover after feeding inflate a block description prior
+   to feeding inflate codes.
+
+     inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
 */
 
+ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm));
 /*
-ZEXTERN int ZEXPORT inflateBackInit OF((z_stream FAR *strm, int windowBits,
+     This function returns two values, one in the lower 16 bits of the return
+   value, and the other in the remaining upper bits, obtained by shifting the
+   return value down 16 bits.  If the upper value is -1 and the lower value is
+   zero, then inflate() is currently decoding information outside of a block.
+   If the upper value is -1 and the lower value is non-zero, then inflate is in
+   the middle of a stored block, with the lower value equaling the number of
+   bytes from the input remaining to copy.  If the upper value is not -1, then
+   it is the number of bits back from the current bit position in the input of
+   the code (literal or length/distance pair) currently being processed.  In
+   that case the lower value is the number of bytes already emitted for that
+   code.
+
+     A code is being processed if inflate is waiting for more input to complete
+   decoding of the code, or if it has completed decoding but is waiting for
+   more output space to write the literal or match data.
+
+     inflateMark() is used to mark locations in the input data for random
+   access, which may be at bit positions, and to note those cases where the
+   output of a code may span boundaries of random access blocks.  The current
+   location in the input stream can be determined from avail_in and data_type
+   as noted in the description for the Z_BLOCK flush parameter for inflate.
+
+     inflateMark returns the value noted above or -1 << 16 if the provided
+   source stream state was inconsistent.
+*/
+
+ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
+                                         gz_headerp head));
+/*
+     inflateGetHeader() requests that gzip header information be stored in the
+   provided gz_header structure.  inflateGetHeader() may be called after
+   inflateInit2() or inflateReset(), and before the first call of inflate().
+   As inflate() processes the gzip stream, head->done is zero until the header
+   is completed, at which time head->done is set to one.  If a zlib stream is
+   being decoded, then head->done is set to -1 to indicate that there will be
+   no gzip header information forthcoming.  Note that Z_BLOCK or Z_TREES can be
+   used to force inflate() to return immediately after header processing is
+   complete and before any actual data is decompressed.
+
+     The text, time, xflags, and os fields are filled in with the gzip header
+   contents.  hcrc is set to true if there is a header CRC.  (The header CRC
+   was valid if done is set to one.) If extra is not Z_NULL, then extra_max
+   contains the maximum number of bytes to write to extra.  Once done is true,
+   extra_len contains the actual extra field length, and extra contains the
+   extra field, or that field truncated if extra_max is less than extra_len.
+   If name is not Z_NULL, then up to name_max characters are written there,
+   terminated with a zero unless the length is greater than name_max.  If
+   comment is not Z_NULL, then up to comm_max characters are written there,
+   terminated with a zero unless the length is greater than comm_max.  When any
+   of extra, name, or comment are not Z_NULL and the respective field is not
+   present in the header, then that field is set to Z_NULL to signal its
+   absence.  This allows the use of deflateSetHeader() with the returned
+   structure to duplicate the header.  However if those fields are set to
+   allocated memory, then the application will need to save those pointers
+   elsewhere so that they can be eventually freed.
+
+     If inflateGetHeader is not used, then the header information is simply
+   discarded.  The header is always checked for validity, including the header
+   CRC if present.  inflateReset() will reset the process to discard the header
+   information.  The application would need to call inflateGetHeader() again to
+   retrieve the header from the next gzip stream.
+
+     inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
+*/
+
+/*
+ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
                                         unsigned char FAR *window));
 
      Initialize the internal stream state for decompression using inflateBack()
@@ -736,15 +962,15 @@ ZEXTERN int ZEXPORT inflateBackInit OF((z_stream FAR *strm, int windowBits,
      See inflateBack() for the usage of these routines.
 
      inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
-   the paramaters are invalid, Z_MEM_ERROR if the internal state could not
-   be allocated, or Z_VERSION_ERROR if the version of the library does not
-   match the version of the header file.
+   the paramaters are invalid, Z_MEM_ERROR if the internal state could not be
+   allocated, or Z_VERSION_ERROR if the version of the library does not match
+   the version of the header file.
 */
 
 typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
 typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
 
-ZEXTERN int ZEXPORT inflateBack OF((z_stream FAR *strm,
+ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
                                     in_func in, void FAR *in_desc,
                                     out_func out, void FAR *out_desc));
 /*
@@ -758,15 +984,15 @@ ZEXTERN int ZEXPORT inflateBack OF((z_stream FAR *strm,
      inflateBackInit() must be called first to allocate the internal state
    and to initialize the state with the user-provided window buffer.
    inflateBack() may then be used multiple times to inflate a complete, raw
-   deflate stream with each call.  inflateBackEnd() is then called to free
-   the allocated state.
+   deflate stream with each call.  inflateBackEnd() is then called to free the
+   allocated state.
 
      A raw deflate stream is one with no zlib or gzip header or trailer.
    This routine would normally be used in a utility that reads zip or gzip
    files and writes out uncompressed files.  The utility would decode the
-   header and process the trailer on its own, hence this routine expects
-   only the raw deflate stream to decompress.  This is different from the
-   normal behavior of inflate(), which expects either a zlib or gzip header and
+   header and process the trailer on its own, hence this routine expects only
+   the raw deflate stream to decompress.  This is different from the normal
+   behavior of inflate(), which expects either a zlib or gzip header and
    trailer around the deflate stream.
 
      inflateBack() uses two subroutines supplied by the caller that are then
@@ -792,7 +1018,7 @@ ZEXTERN int ZEXPORT inflateBack OF((z_stream FAR *strm,
    calling inflateBack().  If strm->next_in is Z_NULL, then in() will be called
    immediately for input.  If strm->next_in is not Z_NULL, then strm->avail_in
    must also be initialized, and then if strm->avail_in is not zero, input will
-   initially be taken from strm->next_in[0 .. strm->avail_in - 1].
+   initially be taken from strm->next_in[0 ..  strm->avail_in - 1].
 
      The in_desc and out_desc parameters of inflateBack() is passed as the
    first parameter of in() and out() respectively when they are called.  These
@@ -802,18 +1028,18 @@ ZEXTERN int ZEXPORT inflateBack OF((z_stream FAR *strm,
      On return, inflateBack() will set strm->next_in and strm->avail_in to
    pass back any unused input that was provided by the last in() call.  The
    return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
-   if in() or out() returned an error, Z_DATA_ERROR if there was a format
-   error in the deflate stream (in which case strm->msg is set to indicate the
-   nature of the error), or Z_STREAM_ERROR if the stream was not properly
-   initialized.  In the case of Z_BUF_ERROR, an input or output error can be
-   distinguished using strm->next_in which will be Z_NULL only if in() returned
-   an error.  If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
-   out() returning non-zero.  (in() will always be called before out(), so
-   strm->next_in is assured to be defined if out() returns non-zero.)  Note
-   that inflateBack() cannot return Z_OK.
+   if in() or out() returned an error, Z_DATA_ERROR if there was a format error
+   in the deflate stream (in which case strm->msg is set to indicate the nature
+   of the error), or Z_STREAM_ERROR if the stream was not properly initialized.
+   In the case of Z_BUF_ERROR, an input or output error can be distinguished
+   using strm->next_in which will be Z_NULL only if in() returned an error.  If
+   strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning
+   non-zero.  (in() will always be called before out(), so strm->next_in is
+   assured to be defined if out() returns non-zero.) Note that inflateBack()
+   cannot return Z_OK.
 */
 
-ZEXTERN int ZEXPORT inflateBackEnd OF((z_stream FAR *strm));
+ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
 /*
      All memory allocated by inflateBackInit() is freed.
 
@@ -866,23 +1092,22 @@ ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
                         /* utility functions */
 
 /*
-     The following utility functions are implemented on top of the
-   basic stream-oriented functions. To simplify the interface, some
-   default options are assumed (compression level and memory usage,
-   standard memory allocation functions). The source code of these
-   utility functions can easily be modified if you need special options.
+     The following utility functions are implemented on top of the basic
+   stream-oriented functions.  To simplify the interface, some default options
+   are assumed (compression level and memory usage, standard memory allocation
+   functions).  The source code of these utility functions can be modified if
+   you need special options.
 */
 
 ZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,
                                  const Bytef *source, uLong sourceLen));
 /*
      Compresses the source buffer into the destination buffer.  sourceLen is
-   the byte length of the source buffer. Upon entry, destLen is the total
-   size of the destination buffer, which must be at least the value returned
-   by compressBound(sourceLen). Upon exit, destLen is the actual size of the
+   the byte length of the source buffer.  Upon entry, destLen is the total size
+   of the destination buffer, which must be at least the value returned by
+   compressBound(sourceLen).  Upon exit, destLen is the actual size of the
    compressed buffer.
-     This function can be used to compress a whole file at once if the
-   input file is mmap'ed.
+
      compress returns Z_OK if success, Z_MEM_ERROR if there was not
    enough memory, Z_BUF_ERROR if there was not enough room in the output
    buffer.
@@ -892,11 +1117,11 @@ ZEXTERN int ZEXPORT compress2 OF((Bytef *dest,   uLongf *destLen,
                                   const Bytef *source, uLong sourceLen,
                                   int level));
 /*
-     Compresses the source buffer into the destination buffer. The level
+     Compresses the source buffer into the destination buffer.  The level
    parameter has the same meaning as in deflateInit.  sourceLen is the byte
-   length of the source buffer. Upon entry, destLen is the total size of the
+   length of the source buffer.  Upon entry, destLen is the total size of the
    destination buffer, which must be at least the value returned by
-   compressBound(sourceLen). Upon exit, destLen is the actual size of the
+   compressBound(sourceLen).  Upon exit, destLen is the actual size of the
    compressed buffer.
 
      compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
@@ -907,22 +1132,20 @@ ZEXTERN int ZEXPORT compress2 OF((Bytef *dest,   uLongf *destLen,
 ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
 /*
      compressBound() returns an upper bound on the compressed size after
-   compress() or compress2() on sourceLen bytes.  It would be used before
-   a compress() or compress2() call to allocate the destination buffer.
+   compress() or compress2() on sourceLen bytes.  It would be used before a
+   compress() or compress2() call to allocate the destination buffer.
 */
 
 ZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,
                                    const Bytef *source, uLong sourceLen));
 /*
      Decompresses the source buffer into the destination buffer.  sourceLen is
-   the byte length of the source buffer. Upon entry, destLen is the total
-   size of the destination buffer, which must be large enough to hold the
-   entire uncompressed data. (The size of the uncompressed data must have
-   been saved previously by the compressor and transmitted to the decompressor
-   by some mechanism outside the scope of this compression library.)
-   Upon exit, destLen is the actual size of the compressed buffer.
-     This function can be used to decompress a whole file at once if the
-   input file is mmap'ed.
+   the byte length of the source buffer.  Upon entry, destLen is the total size
+   of the destination buffer, which must be large enough to hold the entire
+   uncompressed data.  (The size of the uncompressed data must have been saved
+   previously by the compressor and transmitted to the decompressor by some
+   mechanism outside the scope of this compression library.) Upon exit, destLen
+   is the actual size of the uncompressed buffer.
 
      uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
    enough memory, Z_BUF_ERROR if there was not enough room in the output
@@ -930,136 +1153,199 @@ ZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,
 */
 
 
-typedef voidp gzFile;
+                        /* gzip file access functions */
+
+/*
+     This library supports reading and writing files in gzip (.gz) format with
+   an interface similar to that of stdio, using the functions that start with
+   "gz".  The gzip format is different from the zlib format.  gzip is a gzip
+   wrapper, documented in RFC 1952, wrapped around a deflate stream.
+*/
+
+typedef voidp gzFile;       /* opaque gzip file descriptor */
 
-ZEXTERN gzFile ZEXPORT gzopen  OF((const char *path, const char *mode));
 /*
-     Opens a gzip (.gz) file for reading or writing. The mode parameter
-   is as in fopen ("rb" or "wb") but can also include a compression level
-   ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
-   Huffman only compression as in "wb1h", or 'R' for run-length encoding
-   as in "wb1R". (See the description of deflateInit2 for more information
-   about the strategy parameter.)
+ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
+
+     Opens a gzip (.gz) file for reading or writing.  The mode parameter is as
+   in fopen ("rb" or "wb") but can also include a compression level ("wb9") or
+   a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only
+   compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F'
+   for fixed code compression as in "wb9F".  (See the description of
+   deflateInit2 for more information about the strategy parameter.) Also "a"
+   can be used instead of "w" to request that the gzip stream that will be
+   written be appended to the file.  "+" will result in an error, since reading
+   and writing to the same gzip file is not supported.
 
      gzopen can be used to read a file which is not in gzip format; in this
    case gzread will directly read from the file without decompression.
 
-     gzopen returns NULL if the file could not be opened or if there was
-   insufficient memory to allocate the (de)compression state; errno
-   can be checked to distinguish the two cases (if errno is zero, the
-   zlib error is Z_MEM_ERROR).  */
+     gzopen returns NULL if the file could not be opened, if there was
+   insufficient memory to allocate the gzFile state, or if an invalid mode was
+   specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).
+   errno can be checked to determine if the reason gzopen failed was that the
+   file could not be opened.
+*/
+
+ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
+/*
+     gzdopen associates a gzFile with the file descriptor fd.  File descriptors
+   are obtained from calls like open, dup, creat, pipe or fileno (if the file
+   has been previously opened with fopen).  The mode parameter is as in gzopen.
+
+     The next call of gzclose on the returned gzFile will also close the file
+   descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor
+   fd.  If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,
+   mode);.  The duplicated descriptor should be saved to avoid a leak, since
+   gzdopen does not close fd if it fails.
+
+     gzdopen returns NULL if there was insufficient memory to allocate the
+   gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not
+   provided, or '+' was provided), or if fd is -1.  The file descriptor is not
+   used until the next gz* read, write, seek, or close operation, so gzdopen
+   will not detect if fd is invalid (unless fd is -1).
+*/
 
-ZEXTERN gzFile ZEXPORT gzdopen  OF((int fd, const char *mode));
+ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size));
 /*
-     gzdopen() associates a gzFile with the file descriptor fd.  File
-   descriptors are obtained from calls like open, dup, creat, pipe or
-   fileno (in the file has been previously opened with fopen).
-   The mode parameter is as in gzopen.
-     The next call of gzclose on the returned gzFile will also close the
-   file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
-   descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
-     gzdopen returns NULL if there was insufficient memory to allocate
-   the (de)compression state.
+     Set the internal buffer size used by this library's functions.  The
+   default buffer size is 8192 bytes.  This function must be called after
+   gzopen() or gzdopen(), and before any other calls that read or write the
+   file.  The buffer memory allocation is always deferred to the first read or
+   write.  Two buffers are allocated, either both of the specified size when
+   writing, or one of the specified size and the other twice that size when
+   reading.  A larger buffer size of, for example, 64K or 128K bytes will
+   noticeably increase the speed of decompression (reading).
+
+     The new buffer size also affects the maximum length for gzprintf().
+
+     gzbuffer() returns 0 on success, or -1 on failure, such as being called
+   too late.
 */
 
 ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
 /*
-     Dynamically update the compression level or strategy. See the description
+     Dynamically update the compression level or strategy.  See the description
    of deflateInit2 for the meaning of these parameters.
+
      gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
    opened for writing.
 */
 
-ZEXTERN int ZEXPORT    gzread  OF((gzFile file, voidp buf, unsigned len));
+ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
 /*
-     Reads the given number of uncompressed bytes from the compressed file.
-   If the input file was not in gzip format, gzread copies the given number
-   of bytes into the buffer.
-     gzread returns the number of uncompressed bytes actually read (0 for
-   end of file, -1 for error). */
+     Reads the given number of uncompressed bytes from the compressed file.  If
+   the input file was not in gzip format, gzread copies the given number of
+   bytes into the buffer.
+
+     After reaching the end of a gzip stream in the input, gzread will continue
+   to read, looking for another gzip stream, or failing that, reading the rest
+   of the input file directly without decompression.  The entire input file
+   will be read if gzread is called until it returns less than the requested
+   len.
+
+     gzread returns the number of uncompressed bytes actually read, less than
+   len for end of file, or -1 for error.
+*/
 
-ZEXTERN int ZEXPORT    gzwrite OF((gzFile file,
-                                   voidpc buf, unsigned len));
+ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
+                                voidpc buf, unsigned len));
 /*
      Writes the given number of uncompressed bytes into the compressed file.
-   gzwrite returns the number of uncompressed bytes actually written
-   (0 in case of error).
+   gzwrite returns the number of uncompressed bytes written or 0 in case of
+   error.
 */
 
-ZEXTERN int ZEXPORTVA   gzprintf OF((gzFile file, const char *format, ...));
+ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
 /*
-     Converts, formats, and writes the args to the compressed file under
-   control of the format string, as in fprintf. gzprintf returns the number of
-   uncompressed bytes actually written (0 in case of error).  The number of
-   uncompressed bytes written is limited to 4095. The caller should assure that
-   this limit is not exceeded. If it is exceeded, then gzprintf() will return
-   return an error (0) with nothing written. In this case, there may also be a
-   buffer overflow with unpredictable consequences, which is possible only if
-   zlib was compiled with the insecure functions sprintf() or vsprintf()
-   because the secure snprintf() or vsnprintf() functions were not available.
+     Converts, formats, and writes the arguments to the compressed file under
+   control of the format string, as in fprintf.  gzprintf returns the number of
+   uncompressed bytes actually written, or 0 in case of error.  The number of
+   uncompressed bytes written is limited to 8191, or one less than the buffer
+   size given to gzbuffer().  The caller should assure that this limit is not
+   exceeded.  If it is exceeded, then gzprintf() will return an error (0) with
+   nothing written.  In this case, there may also be a buffer overflow with
+   unpredictable consequences, which is possible only if zlib was compiled with
+   the insecure functions sprintf() or vsprintf() because the secure snprintf()
+   or vsnprintf() functions were not available.  This can be determined using
+   zlibCompileFlags().
 */
 
 ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
 /*
-      Writes the given null-terminated string to the compressed file, excluding
+     Writes the given null-terminated string to the compressed file, excluding
    the terminating null character.
-      gzputs returns the number of characters written, or -1 in case of error.
+
+     gzputs returns the number of characters written, or -1 in case of error.
 */
 
 ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
 /*
-      Reads bytes from the compressed file until len-1 characters are read, or
-   a newline character is read and transferred to buf, or an end-of-file
-   condition is encountered.  The string is then terminated with a null
-   character.
-      gzgets returns buf, or Z_NULL in case of error.
+     Reads bytes from the compressed file until len-1 characters are read, or a
+   newline character is read and transferred to buf, or an end-of-file
+   condition is encountered.  If any characters are read or if len == 1, the
+   string is terminated with a null character.  If no characters are read due
+   to an end-of-file or len < 1, then the buffer is left untouched.
+
+     gzgets returns buf which is a null-terminated string, or it returns NULL
+   for end-of-file or in case of error.  If there was an error, the contents at
+   buf are indeterminate.
 */
 
-ZEXTERN int ZEXPORT    gzputc OF((gzFile file, int c));
+ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
 /*
-      Writes c, converted to an unsigned char, into the compressed file.
-   gzputc returns the value that was written, or -1 in case of error.
+     Writes c, converted to an unsigned char, into the compressed file.  gzputc
+   returns the value that was written, or -1 in case of error.
 */
 
-ZEXTERN int ZEXPORT    gzgetc OF((gzFile file));
+ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
 /*
-      Reads one byte from the compressed file. gzgetc returns this byte
-   or -1 in case of end of file or error.
+     Reads one byte from the compressed file.  gzgetc returns this byte or -1
+   in case of end of file or error.
 */
 
-ZEXTERN int ZEXPORT    gzungetc OF((int c, gzFile file));
+ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
 /*
-      Push one character back onto the stream to be read again later.
-   Only one character of push-back is allowed.  gzungetc() returns the
-   character pushed, or -1 on failure.  gzungetc() will fail if a
-   character has been pushed but not read yet, or if c is -1. The pushed
-   character will be discarded if the stream is repositioned with gzseek()
-   or gzrewind().
+     Push one character back onto the stream to be read as the first character
+   on the next read.  At least one character of push-back is allowed.
+   gzungetc() returns the character pushed, or -1 on failure.  gzungetc() will
+   fail if c is -1, and may fail if a character has been pushed but not read
+   yet.  If gzungetc is used immediately after gzopen or gzdopen, at least the
+   output buffer size of pushed characters is allowed.  (See gzbuffer above.)
+   The pushed character will be discarded if the stream is repositioned with
+   gzseek() or gzrewind().
 */
 
-ZEXTERN int ZEXPORT    gzflush OF((gzFile file, int flush));
+ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
 /*
-     Flushes all pending output into the compressed file. The parameter
-   flush is as in the deflate() function. The return value is the zlib
-   error number (see function gzerror below). gzflush returns Z_OK if
-   the flush parameter is Z_FINISH and all output could be flushed.
-     gzflush should be called only when strictly necessary because it can
-   degrade compression.
+     Flushes all pending output into the compressed file.  The parameter flush
+   is as in the deflate() function.  The return value is the zlib error number
+   (see function gzerror below).  gzflush is only permitted when writing.
+
+     If the flush parameter is Z_FINISH, the remaining data is written and the
+   gzip stream is completed in the output.  If gzwrite() is called again, a new
+   gzip stream will be started in the output.  gzread() is able to read such
+   concatented gzip streams.
+
+     gzflush should be called only when strictly necessary because it will
+   degrade compression if called too often.
 */
 
-ZEXTERN z_off_t ZEXPORT    gzseek OF((gzFile file,
-                                      z_off_t offset, int whence));
 /*
-      Sets the starting position for the next gzread or gzwrite on the
-   given compressed file. The offset represents a number of bytes in the
-   uncompressed data stream. The whence parameter is defined as in lseek(2);
+ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
+                                   z_off_t offset, int whence));
+
+     Sets the starting position for the next gzread or gzwrite on the given
+   compressed file.  The offset represents a number of bytes in the
+   uncompressed data stream.  The whence parameter is defined as in lseek(2);
    the value SEEK_END is not supported.
+
      If the file is opened for reading, this function is emulated but can be
-   extremely slow. If the file is opened for writing, only forward seeks are
+   extremely slow.  If the file is opened for writing, only forward seeks are
    supported; gzseek then compresses a sequence of zeroes up to the new
    starting position.
 
-      gzseek returns the resulting offset location as measured in bytes from
+     gzseek returns the resulting offset location as measured in bytes from
    the beginning of the uncompressed stream, or -1 in case of error, in
    particular if the file is opened for writing and the new starting position
    would be before the current position.
@@ -1069,63 +1355,127 @@ ZEXTERN int ZEXPORT    gzrewind OF((gzFile file));
 /*
      Rewinds the given file. This function is supported only for reading.
 
-   gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
+     gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
 */
 
+/*
 ZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));
+
+     Returns the starting position for the next gzread or gzwrite on the given
+   compressed file.  This position represents a number of bytes in the
+   uncompressed data stream, and is zero when starting, even if appending or
+   reading a gzip stream from the middle of a file using gzdopen().
+
+     gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
+*/
+
 /*
-     Returns the starting position for the next gzread or gzwrite on the
-   given compressed file. This position represents a number of bytes in the
-   uncompressed data stream.
+ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file));
 
-   gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
+     Returns the current offset in the file being read or written.  This offset
+   includes the count of bytes that precede the gzip stream, for example when
+   appending or when using gzdopen() for reading.  When reading, the offset
+   does not include as yet unused buffered input.  This information can be used
+   for a progress indicator.  On error, gzoffset() returns -1.
 */
 
 ZEXTERN int ZEXPORT gzeof OF((gzFile file));
 /*
-     Returns 1 when EOF has previously been detected reading the given
-   input stream, otherwise zero.
+     Returns true (1) if the end-of-file indicator has been set while reading,
+   false (0) otherwise.  Note that the end-of-file indicator is set only if the
+   read tried to go past the end of the input, but came up short.  Therefore,
+   just like feof(), gzeof() may return false even if there is no more data to
+   read, in the event that the last read request was for the exact number of
+   bytes remaining in the input file.  This will happen if the input file size
+   is an exact multiple of the buffer size.
+
+     If gzeof() returns true, then the read functions will return no more data,
+   unless the end-of-file indicator is reset by gzclearerr() and the input file
+   has grown since the previous end of file was detected.
+*/
+
+ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
+/*
+     Returns true (1) if file is being copied directly while reading, or false
+   (0) if file is a gzip stream being decompressed.  This state can change from
+   false to true while reading the input file if the end of a gzip stream is
+   reached, but is followed by data that is not another gzip stream.
+
+     If the input file is empty, gzdirect() will return true, since the input
+   does not contain a gzip stream.
+
+     If gzdirect() is used immediately after gzopen() or gzdopen() it will
+   cause buffers to be allocated to allow reading the file to determine if it
+   is a gzip file.  Therefore if gzbuffer() is used, it should be called before
+   gzdirect().
 */
 
 ZEXTERN int ZEXPORT    gzclose OF((gzFile file));
 /*
-     Flushes all pending output if necessary, closes the compressed file
-   and deallocates all the (de)compression state. The return value is the zlib
-   error number (see function gzerror below).
+     Flushes all pending output if necessary, closes the compressed file and
+   deallocates the (de)compression state.  Note that once file is closed, you
+   cannot call gzerror with file, since its structures have been deallocated.
+   gzclose must not be called more than once on the same file, just as free
+   must not be called more than once on the same allocation.
+
+     gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a
+   file operation error, or Z_OK on success.
+*/
+
+ZEXTERN int ZEXPORT gzclose_r OF((gzFile file));
+ZEXTERN int ZEXPORT gzclose_w OF((gzFile file));
+/*
+     Same as gzclose(), but gzclose_r() is only for use when reading, and
+   gzclose_w() is only for use when writing or appending.  The advantage to
+   using these instead of gzclose() is that they avoid linking in zlib
+   compression or decompression code that is not used when only reading or only
+   writing respectively.  If gzclose() is used, then both compression and
+   decompression code will be included the application when linking to a static
+   zlib library.
 */
 
 ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
 /*
-     Returns the error message for the last error which occurred on the
-   given compressed file. errnum is set to zlib error number. If an
-   error occurred in the file system and not in the compression library,
-   errnum is set to Z_ERRNO and the application may consult errno
-   to get the exact error code.
+     Returns the error message for the last error which occurred on the given
+   compressed file.  errnum is set to zlib error number.  If an error occurred
+   in the file system and not in the compression library, errnum is set to
+   Z_ERRNO and the application may consult errno to get the exact error code.
+
+     The application must not modify the returned string.  Future calls to
+   this function may invalidate the previously returned string.  If file is
+   closed, then the string previously returned by gzerror will no longer be
+   available.
+
+     gzerror() should be used to distinguish errors from end-of-file for those
+   functions above that do not distinguish those cases in their return values.
 */
 
 ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
 /*
-     Clears the error and end-of-file flags for file. This is analogous to the
-   clearerr() function in stdio. This is useful for continuing to read a gzip
+     Clears the error and end-of-file flags for file.  This is analogous to the
+   clearerr() function in stdio.  This is useful for continuing to read a gzip
    file that is being written concurrently.
 */
 
+
                         /* checksum functions */
 
 /*
      These functions are not related to compression but are exported
-   anyway because they might be useful in applications using the
-   compression library.
+   anyway because they might be useful in applications using the compression
+   library.
 */
 
 ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
-
 /*
      Update a running Adler-32 checksum with the bytes buf[0..len-1] and
-   return the updated checksum. If buf is NULL, this function returns
-   the required initial value for the checksum.
-   An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
-   much faster. Usage example:
+   return the updated checksum.  If buf is Z_NULL, this function returns the
+   required initial value for the checksum.
+
+     An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
+   much faster.
+
+   Usage example:
 
      uLong adler = adler32(0L, Z_NULL, 0);
 
@@ -1135,12 +1485,24 @@ ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
      if (adler != original_adler) error();
 */
 
+/*
+ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
+                                          z_off_t len2));
+
+     Combine two Adler-32 checksums into one.  For two sequences of bytes, seq1
+   and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
+   each, adler1 and adler2.  adler32_combine() returns the Adler-32 checksum of
+   seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
+*/
+
 ZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));
 /*
-     Update a running crc with the bytes buf[0..len-1] and return the updated
-   crc. If buf is NULL, this function returns the required initial value
-   for the crc. Pre- and post-conditioning (one's complement) is performed
-   within this function so it shouldn't be done by the application.
+     Update a running CRC-32 with the bytes buf[0..len-1] and return the
+   updated CRC-32.  If buf is Z_NULL, this function returns the required
+   initial value for the for the crc.  Pre- and post-conditioning (one's
+   complement) is performed within this function so it shouldn't be done by the
+   application.
+
    Usage example:
 
      uLong crc = crc32(0L, Z_NULL, 0);
@@ -1151,6 +1513,16 @@ ZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));
      if (crc != original_crc) error();
 */
 
+/*
+ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
+
+     Combine two CRC-32 check values into one.  For two sequences of bytes,
+   seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
+   calculated for each, crc1 and crc2.  crc32_combine() returns the CRC-32
+   check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
+   len2.
+*/
+
 
                         /* various hacks, don't look :) */
 
@@ -1167,7 +1539,7 @@ ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int  level, int  method,
                                       int stream_size));
 ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int  windowBits,
                                       const char *version, int stream_size));
-ZEXTERN int ZEXPORT inflateBackInit_ OF((z_stream FAR *strm, int windowBits,
+ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
                                          unsigned char FAR *window,
                                          const char *version,
                                          int stream_size));
@@ -1182,16 +1554,57 @@ ZEXTERN int ZEXPORT inflateBackInit_ OF((z_stream FAR *strm, int windowBits,
         inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
 #define inflateBackInit(strm, windowBits, window) \
         inflateBackInit_((strm), (windowBits), (window), \
-        ZLIB_VERSION, sizeof(z_stream))
+                                            ZLIB_VERSION, sizeof(z_stream))
 
+/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or
+ * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
+ * both are true, the application gets the *64 functions, and the regular
+ * functions are changed to 64 bits) -- in case these are set on systems
+ * without large file support, _LFS64_LARGEFILE must also be true
+ */
+#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
+   ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+   ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));
+   ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));
+   ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));
+   ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t));
+   ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t));
+#endif
+
+#if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS-0 == 64 && _LFS64_LARGEFILE-0
+#  define gzopen gzopen64
+#  define gzseek gzseek64
+#  define gztell gztell64
+#  define gzoffset gzoffset64
+#  define adler32_combine adler32_combine64
+#  define crc32_combine crc32_combine64
+#  ifdef _LARGEFILE64_SOURCE
+     ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+     ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int));
+     ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile));
+     ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile));
+     ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
+     ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
+#  endif
+#else
+   ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *));
+   ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int));
+   ZEXTERN z_off_t ZEXPORT gztell OF((gzFile));
+   ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile));
+   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
+   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
+#endif
 
+/* hack for buggy compilers */
 #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
-    struct internal_state {int dummy;}; /* hack for buggy compilers */
+    struct internal_state {int dummy;};
 #endif
 
-ZEXTERN const char   * ZEXPORT zError           OF((int err));
-ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp z));
+/* undocumented functions */
+ZEXTERN const char   * ZEXPORT zError           OF((int));
+ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp));
 ZEXTERN const uLongf * ZEXPORT get_crc_table    OF((void));
+ZEXTERN int            ZEXPORT inflateUndermine OF((z_streamp, int));
 
 #ifdef __cplusplus
 }
diff --git a/dos/Makefile b/dos/Makefile
index fbaca6b..574b65e 100644
--- a/dos/Makefile
+++ b/dos/Makefile
@@ -26,14 +26,16 @@ INCLUDES = -include code16.h -nostdinc -iwithprefix include \
 	   -I. -I.. -I../libfat -I ../libinstaller
 
 SRCS     = syslinux.c \
+	   ../libinstaller/fat.c \
 	   ../libinstaller/syslxmod.c \
+	   ../libinstaller/setadv.c \
 	   ../libinstaller/bootsect_bin.c \
 	   ../libinstaller/ldlinux_bin.c \
 	   ../libinstaller/mbr_bin.c \
            $(wildcard ../libfat/*.c)
 OBJS	 = header.o crt0.o $(patsubst %.c,%.o,$(notdir $(SRCS)))
-LIBOBJS	 = int2526.o conio.o memcpy.o memset.o  skipatou.o atou.o \
-	   malloc.o free.o \
+LIBOBJS	 = int2526.o conio.o memcpy.o memset.o memmove.o skipatou.o atou.o \
+	   malloc.o free.o getsetsl.o \
 	   argv.o printf.o __divdi3.o __udivmoddi4.o
 
 VPATH = .:../libfat:../libinstaller
diff --git a/dos/errno.h b/dos/errno.h
index 30aa046..da733bf 100644
--- a/dos/errno.h
+++ b/dos/errno.h
@@ -1,6 +1,41 @@
 #ifndef ERRNO_H
 #define ERRNO_H
 
+#define	EPERM		 1	/* Operation not permitted */
+#define	ENOENT		 2	/* No such file or directory */
+#define	ESRCH		 3	/* No such process */
+#define	EINTR		 4	/* Interrupted system call */
+#define	EIO		 5	/* I/O error */
+#define	ENXIO		 6	/* No such device or address */
+#define	E2BIG		 7	/* Argument list too long */
+#define	ENOEXEC		 8	/* Exec format error */
+#define	EBADF		 9	/* Bad file number */
+#define	ECHILD		10	/* No child processes */
+#define	EAGAIN		11	/* Try again */
+#define	ENOMEM		12	/* Out of memory */
+#define	EACCES		13	/* Permission denied */
+#define	EFAULT		14	/* Bad address */
+#define	ENOTBLK		15	/* Block device required */
+#define	EBUSY		16	/* Device or resource busy */
+#define	EEXIST		17	/* File exists */
+#define	EXDEV		18	/* Cross-device link */
+#define	ENODEV		19	/* No such device */
+#define	ENOTDIR		20	/* Not a directory */
+#define	EISDIR		21	/* Is a directory */
+#define	EINVAL		22	/* Invalid argument */
+#define	ENFILE		23	/* File table overflow */
+#define	EMFILE		24	/* Too many open files */
+#define	ENOTTY		25	/* Not a typewriter */
+#define	ETXTBSY		26	/* Text file busy */
+#define	EFBIG		27	/* File too large */
+#define	ENOSPC		28	/* No space left on device */
+#define	ESPIPE		29	/* Illegal seek */
+#define	EROFS		30	/* Read-only file system */
+#define	EMLINK		31	/* Too many links */
+#define	EPIPE		32	/* Broken pipe */
+#define	EDOM		33	/* Math argument out of domain of func */
+#define	ERANGE		34	/* Math result not representable */
+
 int errno;
 void perror(const char *);
 
diff --git a/dos/string.h b/dos/string.h
index 8f8c896..5ee829e 100644
--- a/dos/string.h
+++ b/dos/string.h
@@ -7,6 +7,7 @@
 
 /* Standard routines */
 #define memcpy(a,b,c)	__builtin_memcpy(a,b,c)
+#define memmove(a,b,c)	__builtin_memmove(a,b,c)
 #define memset(a,b,c)	__builtin_memset(a,b,c)
 #define strcpy(a,b)	__builtin_strcpy(a,b)
 #define strlen(a)	__builtin_strlen(a)
diff --git a/dos/syslinux.c b/dos/syslinux.c
index 61020a1..9574553 100644
--- a/dos/syslinux.c
+++ b/dos/syslinux.c
@@ -26,6 +26,7 @@
 
 #include "syslinux.h"
 #include "libfat.h"
+#include "setadv.h"
 
 const char *program = "syslinux";	/* Name of program */
 uint16_t dos_version;
@@ -658,6 +659,11 @@ int main(int argc, char *argv[])
 	usage();
 
     /*
+     * Create an ADV in memory... this should be smarter.
+     */
+    syslinux_reset_adv(syslinux_adv);
+
+    /*
      * Figure out which drive we're talking to
      */
     dev_fd = (device[0] & ~0x20) - 0x40;
@@ -685,6 +691,7 @@ int main(int argc, char *argv[])
     set_attributes(ldlinux_name, 0);
     fd = creat(ldlinux_name, 0);	/* SYSTEM HIDDEN READONLY */
     write_ldlinux(fd);
+    write_file(fd, syslinux_adv, 2 * ADV_SIZE);
     close(fd);
     set_attributes(ldlinux_name, 0x07);	/* SYSTEM HIDDEN READONLY */
 
@@ -694,7 +701,8 @@ int main(int argc, char *argv[])
      * this is supposed to be a simple, privileged version
      * of the installer.
      */
-    ldlinux_sectors = (syslinux_ldlinux_len + SECTOR_SIZE - 1) >> SECTOR_SHIFT;
+    ldlinux_sectors = (syslinux_ldlinux_len + 2 * ADV_SIZE
+		       + SECTOR_SIZE - 1) >> SECTOR_SHIFT;
     sectors = calloc(ldlinux_sectors, sizeof *sectors);
     lock_device(2);
     fs = libfat_open(libfat_xpread, dev_fd);
@@ -755,7 +763,7 @@ int main(int argc, char *argv[])
     /*
      * Patch ldlinux.sys and the boot sector
      */
-    i = syslinux_patch(sectors, nsectors, stupid, raid_mode);
+    i = syslinux_patch(sectors, nsectors, stupid, raid_mode, subdir, NULL);
     patch_sectors = (i + SECTOR_SIZE - 1) >> SECTOR_SHIFT;
 
     /*
diff --git a/dosutil/eltorito.asm b/dosutil/eltorito.asm
index eabda12..d6b6b50 100644
--- a/dosutil/eltorito.asm
+++ b/dosutil/eltorito.asm
@@ -1029,9 +1029,11 @@ SpecGo:		mov	si,SpecPkt
 
 ScanDrives:	push	ax		; at df3 in 1.4
 		push	si
-		mov dl, 0ffh		;Start at Drive 0xff
-NextDrv:	mov	ax,4B01h		;Get Bootable CD-ROM Status
-		mov	BYTE [SpecPkt],0		;Clear 1st byte of SpecPkt
+		mov dl, 7fh		;Start at Drive 0x80
+NextDrv:	inc	dl
+		clc
+		mov	ax,4B01h	;Get Bootable CD-ROM Status
+		mov	BYTE [SpecPkt],0	;Clear 1st byte of SpecPkt
 		call	SpecGo
 ; Carry is not cleared in buggy Dell BIOSes,
 ; so I'm checking packet size byte
@@ -1044,10 +1046,9 @@ NextDrv:	mov	ax,4B01h		;Get Bootable CD-ROM Status
 		ja	FindFail	; in 1.4 at e16
 		jmp	short SendFound	; in 1.4 at e26
 
-FindFail:	dec	dl			;Next drive
-		cmp	dl, 80h
-		jb	SendFail		; Check from ffh..80h
-		jmp	short NextDrv
+FindFail:	cmp	dl, 0ffh
+		je	SendFail		; Check from 80h..ffh
+		jmp	short NextDrv		;Next drive
 SendFail:	xor	dl,dl
 		stc
 		jmp	short ThingDone
diff --git a/dosutil/mdiskchk.c b/dosutil/mdiskchk.c
index 42aa511..47bb08e 100644
--- a/dosutil/mdiskchk.c
+++ b/dosutil/mdiskchk.c
@@ -1,6 +1,7 @@
 /* -*- c -*- ------------------------------------------------------------- *
  *
  *   Copyright 2003-2008 H. Peter Anvin - All Rights Reserved
+ *   Portions copyright 2010 Shao Miller
  *
  *   This program is free software; you can redistribute it and/or modify
  *   it under the terms of the GNU General Public License as published by
@@ -21,6 +22,7 @@
  * wcl -3 -osx -mt mdiskchk.c
  */
 
+#include <ctype.h>
 #include <stdio.h>
 #include <string.h>
 #include <i86.h>		/* For MK_FP() */
@@ -29,18 +31,11 @@ typedef unsigned long uint32_t;
 typedef unsigned short uint16_t;
 typedef unsigned char uint8_t;
 
+/* Pull in MEMDISK common structures */
+#include "../memdisk/mstructs.h"
+
 struct memdiskinfo {
-    uint16_t bytes;		/* Bytes from memdisk */
-    uint16_t version;		/* Memdisk version */
-    uint32_t base;		/* Base of disk in high memory */
-    uint32_t size;		/* Size of disk in sectors */
-    char far *cmdline;		/* Command line */
-    void far *oldint13;		/* Old INT 13h */
-    void far *oldint15;		/* Old INT 15h */
-    uint16_t olddosmem;
-    uint8_t bootloaderid;
-
-    uint8_t _pad;
+    struct mdi mdi;
 
     /* We add our own fields at the end */
     int cylinders;
@@ -121,25 +116,242 @@ const char *bootloadername(uint8_t id)
     }
 }
 
+/* The function type for an output function */
+#define OUTPUT_FUNC_DECL(x) \
+void x(const int d, const struct memdiskinfo * const m)
+typedef OUTPUT_FUNC_DECL((*output_func));
+
+/* Show MEMDISK information for the passed structure */
+static OUTPUT_FUNC_DECL(normal_output)
+{
+    if (m == NULL)
+	return;
+    printf("Drive %02X is MEMDISK %u.%02u:\n"
+	   "\tAddress = 0x%08lx, len = %lu sectors, chs = %u/%u/%u,\n"
+	   "\tloader = 0x%02x (%s),\n"
+	   "\tcmdline = %Fs\n",
+	   d, m->mdi.version_major, m->mdi.version_minor,
+	   m->mdi.diskbuf, m->mdi.disksize, m->cylinders, m->heads, m->sectors,
+	   m->mdi.bootloaderid, bootloadername(m->mdi.bootloaderid),
+	   MK_FP(m->mdi.cmdline.seg_off.segment,
+		 m->mdi.cmdline.seg_off.offset));
+}
+
+/* Yield DOS SET command(s) as output for each MEMDISK kernel argument */
+static OUTPUT_FUNC_DECL(batch_output)
+{
+    if (m != NULL) {
+	char buf[256], *bc;
+	const char far *c =
+	    MK_FP(m->mdi.cmdline.seg_off.segment,
+		  m->mdi.cmdline.seg_off.offset);
+	const char *have_equals, is_set[] = "=1";
+
+	while (*c != '\0') {
+	    /* Skip whitespace */
+	    while (isspace(*c))
+		c++;
+	    if (*c == '\0')
+		/* Trailing whitespace.  That's enough processing */
+		break;
+	    /* Walk the kernel arguments while filling the buffer,
+	     * looking for space or NUL or checking for a full buffer
+	     */
+	    bc = buf;
+	    have_equals = is_set;
+	    while ((*c != '\0') && !isspace(*c) &&
+		   (bc < &buf[sizeof(buf) - 1])) {
+		/* Check if the param is "x=y" */
+		if (*c == '=')
+		    /* "=1" not needed */
+		    have_equals = &is_set[sizeof(is_set) - 1];
+		*bc = *c;
+		c++;
+		bc++;
+	    }
+	    /* Found the end of the parameter and optional value sequence */
+	    *bc = '\0';
+	    printf("set %s%s\n", buf, have_equals);
+	}
+    }
+}
+
+/* We do not output batch file output by default.  We show MEMDISK info */
+static output_func show_memdisk = normal_output;
+
+/* A generic function type */
+#define MDISKCHK_FUNC_DECL(x) \
+void x(void)
+typedef MDISKCHK_FUNC_DECL((*mdiskchk_func));
+
+static MDISKCHK_FUNC_DECL(do_nothing)
+{
+    return;
+}
+
+static MDISKCHK_FUNC_DECL(show_usage)
+{
+    printf("\nUsage: mdiskchk [--safe-hooks] [--mbfts] [--batch-output]\n"
+	   "\n"
+	   "Action: --safe-hooks . . Will scan INT 13h \"safe hook\" chain\n"
+	   "        --mbfts . . . .  Will scan memory for MEMDISK mBFTs\n"
+	   "        --batch-output . Will output SET command output based\n"
+	   "                         on MEMDISK kernel arguments\n"
+	   "        --no-sequential  Suppresses probing all drive numbers\n");
+}
+
+/* Search memory for mBFTs and report them via the output method */
+static MDISKCHK_FUNC_DECL(show_mbfts)
+{
+    const uint16_t far * const free_base_mem =
+	MK_FP(0x0040, 0x0013);
+    int seg;
+    uint8_t chksum;
+    uint32_t i;
+    const struct mBFT far *mbft;
+    struct memdiskinfo m;
+    struct patch_area far *patch_area;
+
+    for (seg = *free_base_mem / 16; seg < 0x9FFF; seg++) {
+	mbft = MK_FP(seg, 0);
+	/* Check for signature */
+	if (mbft->acpi.signature[0] != 'm' ||
+	    mbft->acpi.signature[1] != 'B' ||
+	    mbft->acpi.signature[2] != 'F' ||
+	    mbft->acpi.signature[3] != 'T')
+	    continue;
+	if (mbft->acpi.length != sizeof(struct mBFT))
+	    continue;
+	/* Check sum */
+	chksum = 0;
+	for (i = 0; i < sizeof(struct mBFT); i++)
+	    chksum += ((const uint8_t far *)mbft)[i];
+	if (chksum)
+	    continue;
+	/* Copy the MDI from the mBFT */
+	_fmemcpy((void far *)&m, &mbft->mdi, sizeof(struct mdi));
+	/* Adjust C/H/S since we actually know
+	 * it directly for any MEMDISK with an mBFT
+	 */
+	patch_area = (struct patch_area far *)&mbft->mdi;
+	m.cylinders = patch_area->cylinders;
+	m.heads = patch_area->heads;
+	m.sectors = patch_area->sectors;
+	show_memdisk(patch_area->driveno, &m);
+    }
+}
+
+/* Walk the "safe hook" chain as far as possible
+ * and report MEMDISKs that we find via the output method
+ */
+static MDISKCHK_FUNC_DECL(show_safe_hooks)
+{
+    const real_addr_t far * const int13 =
+	MK_FP(0x0000, 0x0013 * sizeof(real_addr_t));
+    const struct safe_hook far *hook =
+	MK_FP(int13->seg_off.segment, int13->seg_off.offset);
+
+    while ((hook->signature[0] == '$') &&
+	   (hook->signature[1] == 'I') &&
+	   (hook->signature[2] == 'N') &&
+	   (hook->signature[3] == 'T') &&
+	   (hook->signature[4] == '1') &&
+	   (hook->signature[5] == '3') &&
+	   (hook->signature[6] == 'S') &&
+	   (hook->signature[7] == 'F')) {
+	/* Found a valid "safe hook" */
+	if ((hook->vendor[0] == 'M') &&
+	    (hook->vendor[1] == 'E') &&
+	    (hook->vendor[2] == 'M') &&
+	    (hook->vendor[3] == 'D') &&
+	    (hook->vendor[4] == 'I') &&
+	    (hook->vendor[5] == 'S') &&
+	    (hook->vendor[6] == 'K')) {
+	    /* Found a valid MEMDISK "safe hook".  It will have an mBFT */
+	    const struct mBFT far *mbft;
+	    struct memdiskinfo m;
+	    struct patch_area far *patch_area;
+
+	    /* Copy the MDI from the mBFT.  Offset is a misnomer here */
+	    mbft = MK_FP(hook->mbft >> 4, 0);	/* Always aligned */
+	    _fmemcpy((void far *)&m, &mbft->mdi, sizeof(struct mdi));
+	    /* Adjust C/H/S since we actually know
+	     * it directly for any MEMDISK with an mBFT
+	     */
+	    patch_area = (struct patch_area far *)&mbft->mdi;
+	    m.cylinders = patch_area->cylinders;
+	    m.heads = patch_area->heads;
+	    m.sectors = patch_area->sectors;
+	    show_memdisk(patch_area->driveno, &m);
+	} /* if */
+	/* Step to the next hook in the "safe hook" chain */
+	hook = MK_FP(hook->old_hook.seg_off.segment,
+		     hook->old_hook.seg_off.offset);
+    } /* while */
+}
+
 int main(int argc, char *argv[])
 {
     int d;
     int found = 0;
-    struct memdiskinfo *m;
+    int sequential_scan = 1;	/* Classic behaviour */
+    const struct memdiskinfo *m;
 
+    /* Default behaviour */
+    mdiskchk_func usage = do_nothing,
+	safe_hooks = do_nothing,
+	mbfts = do_nothing;
+
+    /* For each argument */
+    while (--argc) {
+	/* Argument should begin with one of these chars */
+	if ((*argv[argc] != '/') && (*argv[argc] != '-')) {
+	    /* It doesn't.  Print usage soon */
+	    usage = show_usage;
+	    break;
+	}
+	argv[argc]++;
+
+	/* Next char might be '-' as in "--safe-hooks" */
+	if (*argv[argc] == '-')
+	    argv[argc]++;
+
+	switch (*argv[argc]) {
+	    case 'S':
+	    case 's':
+		safe_hooks = show_safe_hooks;
+		break;
+	    case 'M':
+	    case 'm':
+		mbfts = show_mbfts;
+		break;
+	    case 'B':
+	    case 'b':
+		show_memdisk = batch_output;
+		break;
+	    case 'N':
+	    case 'n':
+		sequential_scan = 0;
+		break;
+	    default:
+		usage = show_usage;
+	} /* switch */
+   } /* while */
+
+    safe_hooks();
+    mbfts();
+    if (!sequential_scan)
+	goto skip_sequential;
     for (d = 0; d <= 0xff; d++) {
-	if ((m = query_memdisk(d)) != NULL) {
-	    printf("Drive %02X is MEMDISK %u.%02u:\n"
-		   "\tAddress = 0x%08lx, len = %lu sectors, chs = %u/%u/%u,\n"
-		   "\tloader = 0x%02x (%s),\n"
-		   "\tcmdline = %Fs\n",
-		   d, m->version >> 8, m->version & 0xff,
-		   m->base, m->size, m->cylinders, m->heads, m->sectors,
-		   m->bootloaderid, bootloadername(m->bootloaderid),
-		   m->cmdline);
+	m = query_memdisk(d);
+	if (m != NULL) {
 	    found++;
+	    show_memdisk(d, m);
 	}
     }
+skip_sequential:
+    usage();
 
     return found;
 }
+
diff --git a/dosutil/mdiskchk.com b/dosutil/mdiskchk.com
index 7825751..22ccfe5 100644
Binary files a/dosutil/mdiskchk.com and b/dosutil/mdiskchk.com differ
diff --git a/extlinux/Makefile b/extlinux/Makefile
index ab92c2c..83cf1a5 100644
--- a/extlinux/Makefile
+++ b/extlinux/Makefile
@@ -24,11 +24,13 @@ CFLAGS	 = $(GCCWARN) -Wno-sign-compare -D_FILE_OFFSET_BITS=64 \
 LDFLAGS	 = # -s
 
 SRCS     = main.c \
+	   ../libinstaller/syslxmod.c \
 	   ../libinstaller/syslxopt.c \
 	   ../libinstaller/syslxcom.c \
 	   ../libinstaller/setadv.c \
-	   ../libinstaller/extlinux_bss_bin.c \
-	   ../libinstaller/extlinux_sys_bin.c
+	   ../libinstaller/advio.c \
+	   ../libinstaller/bootsect_bin.c \
+	   ../libinstaller/ldlinux_bin.c
 OBJS	 = $(patsubst %.c,%.o,$(notdir $(SRCS)))
 
 .SUFFIXES: .c .o .i .s .S
diff --git a/extlinux/fat.h b/extlinux/fat.h
index dd5a362..5d13402 100644
--- a/extlinux/fat.h
+++ b/extlinux/fat.h
@@ -2,61 +2,6 @@
 #define _H_FAT_
 
 #define MSDOS_SUPER_MAGIC       0x4d44          /* MD */
-#if 0
-/* FAT bootsector format, also used by other disk-based derivatives */
-struct boot_sector {
-    uint8_t bsJump[3];
-    char bsOemName[8];
-    uint16_t bsBytesPerSec;
-    uint8_t bsSecPerClust;
-    uint16_t bsResSectors;
-    uint8_t bsFATs;
-    uint16_t bsRootDirEnts;
-    uint16_t bsSectors;
-    uint8_t bsMedia;
-    uint16_t bsFATsecs;
-    uint16_t bsSecPerTrack;
-    uint16_t bsHeads;
-    uint32_t bsHiddenSecs;
-    uint32_t bsHugeSectors;
+/* The rest is defined in syslxint.h */
 
-    union {
-        struct {
-            uint8_t DriveNumber;
-            uint8_t Reserved1;
-            uint8_t BootSignature;
-            uint32_t VolumeID;
-            char VolumeLabel[11];
-            char FileSysType[8];
-            uint8_t Code[442];
-        } __attribute__ ((packed)) bs16;
-        struct {
-            uint32_t FATSz32; 
-            uint16_t ExtFlags;
-            uint16_t FSVer;
-            uint32_t RootClus;
-            uint16_t FSInfo;
-            uint16_t BkBootSec;
-            uint8_t Reserved0[12];
-            uint8_t DriveNumber;
-            uint8_t Reserved1;
-            uint8_t BootSignature;
-            uint32_t VolumeID;
-            char VolumeLabel[11];
-            char FileSysType[8];
-            uint8_t Code[414];
-        } __attribute__ ((packed)) bs32;
-    } __attribute__ ((packed));
-    
-    uint32_t NextSector;        /* Pointer to the first unused sector */
-    uint16_t MaxTransfer;       /* Max sectors per transfer */
-    uint16_t bsSignature;
-} __attribute__ ((packed));
-
-#define bsHead      bsJump
-#define bsHeadLen   offsetof(struct boot_sector, bsOemName)
-#define bsCode      bs32.Code   /* The common safe choice */
-#define bsCodeLen   (offsetof(struct boot_sector, bsSignature) - \
-                     offsetof(struct boot_sector, bsCode))
-#endif
 #endif
diff --git a/extlinux/main.c b/extlinux/main.c
index 0669bb9..daebc10 100644
--- a/extlinux/main.c
+++ b/extlinux/main.c
@@ -14,7 +14,7 @@
 /*
  * extlinux.c
  *
- * Install the extlinux boot block on an fat, ext2/3/4 and btrfs filesystem
+ * Install the syslinux boot block on an fat, ext2/3/4 and btrfs filesystem
  */
 
 #define  _GNU_SOURCE		/* Enable everything */
@@ -41,18 +41,8 @@ typedef uint64_t u64;
 #include <sys/mount.h>
 #include <sys/vfs.h>
 
-#include <linux/fd.h>		/* Floppy geometry */
-#include <linux/hdreg.h>	/* Hard disk geometry */
-#define statfs _kernel_statfs	/* HACK to deal with broken 2.4 distros */
-#include <linux/fs.h>		/* FIGETBSZ, FIBMAP */
-#include <linux/msdos_fs.h>	/* FAT_IOCTL_SET_ATTRIBUTES */
-#ifndef FAT_IOCTL_SET_ATTRIBUTES
-# define FAT_IOCTL_SET_ATTRIBUTES _IOW('r', 0x11, uint32_t)
-#endif
-#undef statfs
-#undef SECTOR_SIZE		/* Garbage from <linux/msdos_fs.h> */
+#include "linuxioctl.h"
 
-#include "ext2_fs.h"
 #include "btrfs.h"
 #include "fat.h"
 #include "../version.h"
@@ -67,38 +57,19 @@ typedef uint64_t u64;
 # define dprintf(...) ((void)0)
 #endif
 
-#if defined(__linux__) && !defined(BLKGETSIZE64)
-/* This takes a u64, but the size field says size_t.  Someone screwed big. */
-# define BLKGETSIZE64 _IOR(0x12,114,size_t)
-#endif
-
 #ifndef EXT2_SUPER_OFFSET
 #define EXT2_SUPER_OFFSET 1024
 #endif
 
 /* the btrfs partition first 64K blank area is used to store boot sector and
-   boot image, the boot sector is from 0~512, the boot image starts at 2K */
-#define BTRFS_EXTLINUX_OFFSET (2*1024)
+   boot image, the boot sector is from 0~512, the boot image starts after */
+#define BTRFS_BOOTSECT_AREA	65536
+#define BTRFS_EXTLINUX_OFFSET	SECTOR_SIZE
 #define BTRFS_SUBVOL_OPT "subvol="
 #define BTRFS_SUBVOL_MAX 256	/* By btrfs specification */
 static char subvol[BTRFS_SUBVOL_MAX];
-/*
- * Boot block
- */
-extern unsigned char extlinux_bootsect[];
-extern unsigned int extlinux_bootsect_len;
-#define boot_block	extlinux_bootsect
-#define boot_block_len  extlinux_bootsect_len
 
-/*
- * Image file
- */
-extern unsigned char extlinux_image[];
-extern unsigned int extlinux_image_len;
-#define boot_image	extlinux_image
-#define boot_image_len  extlinux_image_len
-
-#define BTRFS_ADV_OFFSET (BTRFS_EXTLINUX_OFFSET + boot_image_len)
+#define BTRFS_ADV_OFFSET (BTRFS_BOOTSECT_AREA - 2 * ADV_SIZE)
 
 /*
  * Get the size of a block device
@@ -149,6 +120,8 @@ static const struct geometry_table standard_geometries[] = {
 int get_geometry(int devfd, uint64_t totalbytes, struct hd_geometry *geo)
 {
     struct floppy_struct fd_str;
+    struct loop_info li;
+    struct loop_info64 li64;
     const struct geometry_table *gp;
 
     memset(geo, 0, sizeof *geo);
@@ -186,6 +159,12 @@ int get_geometry(int devfd, uint64_t totalbytes, struct hd_geometry *geo)
 		"         (on hard disks, this is usually harmless.)\n",
 		geo->heads, geo->sectors);
 
+    /* If this is a loopback device, try to set the start */
+    if (!ioctl(devfd, LOOP_GET_STATUS64, &li64))
+	geo->start = li64.lo_offset >> SECTOR_SHIFT;
+    else if (!ioctl(devfd, LOOP_GET_STATUS, &li))
+	geo->start = (unsigned int)li.lo_offset >> SECTOR_SHIFT;
+
     return 1;
 }
 
@@ -200,16 +179,12 @@ int patch_file_and_bootblock(int fd, const char *dir, int devfd)
 {
     struct stat dirst, xdst;
     struct hd_geometry geo;
-    uint32_t *sectp;
+    sector_t *sectp;
     uint64_t totalbytes, totalsectors;
     int nsect;
-    uint32_t *wp;
-    struct boot_sector *bs;
-    struct patch_area *patcharea;
-    int i, dw, nptrs;
-    uint32_t csum;
-    int secptroffset, diroffset, dirlen, subvoloffset, subvollen;
+    struct boot_sector *sbs;
     char *dirpath, *subpath, *xdirpath, *xsubpath;
+    int rv;
 
     dirpath = realpath(dir, NULL);
     if (!dirpath || stat(dir, &dirst)) {
@@ -266,35 +241,27 @@ int patch_file_and_bootblock(int fd, const char *dir, int devfd)
        early bootstrap share code with the FAT version. */
     dprintf("heads = %u, sect = %u\n", geo.heads, geo.sectors);
 
-    bs = (struct boot_sector *)boot_block;
+    sbs = (struct boot_sector *)syslinux_bootsect;
 
     totalsectors = totalbytes >> SECTOR_SHIFT;
     if (totalsectors >= 65536) {
-	set_16(&bs->bsSectors, 0);
+	set_16(&sbs->bsSectors, 0);
     } else {
-	set_16(&bs->bsSectors, totalsectors);
+	set_16(&sbs->bsSectors, totalsectors);
     }
-    set_32(&bs->bsHugeSectors, totalsectors);
-
-    set_16(&bs->bsBytesPerSec, SECTOR_SIZE);
-    set_16(&bs->bsSecPerTrack, geo.sectors);
-    set_16(&bs->bsHeads, geo.heads);
-    set_32(&bs->bsHiddenSecs, geo.start);
+    set_32(&sbs->bsHugeSectors, totalsectors);
 
-    /* If we're in RAID mode then patch the appropriate instruction;
-       either way write the proper boot signature */
-    i = get_16(&bs->bsSignature);
-    if (opt.raid_mode)
-	set_16((uint16_t *) (boot_block + i), 0x18CD);	/* INT 18h */
+    set_16(&sbs->bsBytesPerSec, SECTOR_SIZE);
+    set_16(&sbs->bsSecPerTrack, geo.sectors);
+    set_16(&sbs->bsHeads, geo.heads);
+    set_32(&sbs->bsHiddenSecs, geo.start);
 
-    set_16(&bs->bsSignature, 0xAA55);
-
-    /* Construct the boot file */
+    /* Construct the boot file map */
 
     dprintf("directory inode = %lu\n", (unsigned long)dirst.st_ino);
     nsect = (boot_image_len + SECTOR_SIZE - 1) >> SECTOR_SHIFT;
     nsect += 2;			/* Two sectors for the ADV */
-    sectp = alloca(sizeof(uint32_t) * nsect);
+    sectp = alloca(sizeof(sector_t) * nsect);
     if (fs_type == EXT2 || fs_type == VFAT) {
 	if (sectmap(fd, sectp, nsect)) {
 		perror("bmap");
@@ -302,86 +269,19 @@ int patch_file_and_bootblock(int fd, const char *dir, int devfd)
 	}
     } else if (fs_type == BTRFS) {
 	int i;
+	sector_t *sp = sectp;
 
-	for (i = 0; i < nsect; i++)
-		*(sectp + i) = BTRFS_EXTLINUX_OFFSET/SECTOR_SIZE + i;
+	for (i = 0; i < nsect - 2; i++)
+	    *sp++ = BTRFS_EXTLINUX_OFFSET/SECTOR_SIZE + i;
+	for (i = 0; i < 2; i++)
+	    *sp++ = BTRFS_ADV_OFFSET/SECTOR_SIZE + i;
     }
 
-    /* First sector need pointer in boot sector */
-    set_32(&bs->NextSector, *sectp++);
-    /* Stupid mode? */
-    if (opt.stupid_mode)
-	set_16(&bs->MaxTransfer, 1);
-
-    /* Search for LDLINUX_MAGIC to find the patch area */
-    for (wp = (uint32_t *) boot_image; get_32(wp) != LDLINUX_MAGIC; wp++) ;
-    patcharea = (struct patch_area *)wp;
-
-    /* Set up the totals */
-    dw = boot_image_len >> 2;	/* COMPLETE dwords, excluding ADV */
-    set_16(&patcharea->data_sectors, nsect - 2);	/* -2 for the ADVs */
-    set_16(&patcharea->adv_sectors, 2);
-    set_32(&patcharea->dwords, dw);
+    /* Create the modified image in memory */
+    rv = syslinux_patch(sectp, nsect, opt.stupid_mode,
+			opt.raid_mode, subpath, subvol);
 
-    /* Set the sector pointers */
-    secptroffset = get_16(&patcharea->secptroffset);
-    wp = (uint32_t *) ((char *)boot_image + secptroffset);
-    nptrs = get_16(&patcharea->secptrcnt);
-
-    memset(wp, 0, nptrs * 4);
-    while (--nsect) /* the first sector in bs->NextSector */
-	set_32(wp++, *sectp++);
-
-    /* Poke in the base directory path */
-    diroffset = get_16(&patcharea->diroffset);
-    dirlen = get_16(&patcharea->dirlen);
-    if (dirlen <= strlen(subpath)) {
-	fprintf(stderr, "Subdirectory path too long... aborting install!\n");
-	exit(1);
-    }
-    strncpy((char *)boot_image + diroffset, subpath, dirlen);
     free(dirpath);
-
-    /* write subvol info if we have */
-    subvoloffset = get_16(&patcharea->subvoloffset);
-    subvollen = get_16(&patcharea->subvollen);
-    if (subvollen <= strlen(subvol)) {
-	fprintf(stderr, "Subvol name too long... aborting install!\n");
-	exit(1);
-    }
-    strncpy((char *)boot_image + subvoloffset, subvol, subvollen);
-
-    /* Now produce a checksum */
-    set_32(&patcharea->checksum, 0);
-
-    csum = LDLINUX_MAGIC;
-    for (i = 0, wp = (uint32_t *) boot_image; i < dw; i++, wp++)
-	csum -= get_32(wp);	/* Negative checksum */
-
-    set_32(&patcharea->checksum, csum);
-
-    /*
-     * Assume all bytes modified.  This can be optimized at the expense
-     * of keeping track of what the highest modified address ever was.
-     */
-    return dw << 2;
-}
-
-/*
- * Make any user-specified ADV modifications
- */
-int modify_adv(void)
-{
-    int rv = 0;
-
-    if (opt.set_once) {
-	if (syslinux_setadv(ADV_BOOTONCE, strlen(opt.set_once), opt.set_once)) {
-	    fprintf(stderr, "%s: not enough space for boot-once command\n",
-		    program);
-	    rv = -1;
-	}
-    }
-
     return rv;
 }
 
@@ -427,15 +327,16 @@ int install_bootblock(int fd, const char *device)
 	return 1;
     }
     if (fs_type == VFAT) {
-	struct boot_sector *bs = (struct boot_sector *)extlinux_bootsect;
-        if (xpwrite(fd, &bs->bsHead, bsHeadLen, 0) != bsHeadLen ||
-	    xpwrite(fd, &bs->bsCode, bsCodeLen,
+	struct boot_sector *sbs = (struct boot_sector *)syslinux_bootsect;
+        if (xpwrite(fd, &sbs->bsHead, bsHeadLen, 0) != bsHeadLen ||
+	    xpwrite(fd, &sbs->bsCode, bsCodeLen,
 		    offsetof(struct boot_sector, bsCode)) != bsCodeLen) {
 	    perror("writing fat bootblock");
 	    return 1;
 	}
     } else {
-	if (xpwrite(fd, boot_block, boot_block_len, 0) != boot_block_len) {
+	if (xpwrite(fd, syslinux_bootsect, syslinux_bootsect_len, 0)
+	    != syslinux_bootsect_len) {
 	    perror("writing bootblock");
 	    return 1;
 	}
@@ -446,13 +347,16 @@ int install_bootblock(int fd, const char *device)
 
 int ext2_fat_install_file(const char *path, int devfd, struct stat *rst)
 {
-    char *file;
+    char *file, *oldfile;
     int fd = -1, dirfd = -1;
     int modbytes;
+    int r1, r2;
 
-    asprintf(&file, "%s%sextlinux.sys",
-	     path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/");
-    if (!file) {
+    r1 = asprintf(&file, "%s%sldlinux.sys",
+		  path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/");
+    r2 = asprintf(&oldfile, "%s%sextlinux.sys",
+		  path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/");
+    if (r1 < 0 || !file || r2 < 0 || !oldfile) {
 	perror(program);
 	return 1;
     }
@@ -510,6 +414,17 @@ int ext2_fat_install_file(const char *path, int devfd, struct stat *rst)
 
     close(dirfd);
     close(fd);
+
+    /* Look if we have the old filename */
+    fd = open(oldfile, O_RDONLY);
+    if (fd >= 0) {
+	clear_attributes(fd);
+	close(fd);
+	unlink(oldfile);
+    }
+
+    free(file);
+    free(oldfile);
     return 0;
 
 bail:
@@ -518,12 +433,14 @@ bail:
     if (fd >= 0)
 	close(fd);
 
+    free(file);
+    free(oldfile);
     return 1;
 }
 
-/* btrfs has to install the extlinux.sys in the first 64K blank area, which
+/* btrfs has to install the ldlinux.sys in the first 64K blank area, which
    is not managered by btrfs tree, so actually this is not installed as files.
-   since the cow feature of btrfs will move the extlinux.sys every where */
+   since the cow feature of btrfs will move the ldlinux.sys every where */
 int btrfs_install_file(const char *path, int devfd, struct stat *rst)
 {
     patch_file_and_bootblock(-1, path, devfd);
@@ -532,13 +449,13 @@ int btrfs_install_file(const char *path, int devfd, struct stat *rst)
 	perror("writing bootblock");
 	return 1;
     }
-    printf("write boot_image to 0x%x\n", BTRFS_EXTLINUX_OFFSET);
-    if (xpwrite(devfd, syslinux_adv, 2 * ADV_SIZE,
-		BTRFS_EXTLINUX_OFFSET + boot_image_len) != 2 * ADV_SIZE) {
+    dprintf("write boot_image to 0x%x\n", BTRFS_EXTLINUX_OFFSET);
+    if (xpwrite(devfd, syslinux_adv, 2 * ADV_SIZE, BTRFS_ADV_OFFSET)
+	!= 2 * ADV_SIZE) {
 	perror("writing adv");
 	return 1;
     }
-    printf("write adv to 0x%x\n", BTRFS_EXTLINUX_OFFSET + boot_image_len);
+    dprintf("write adv to 0x%x\n", BTRFS_ADV_OFFSET);
     if (stat(path, rst)) {
 	perror(path);
 	return 1;
@@ -555,14 +472,17 @@ int install_file(const char *path, int devfd, struct stat *rst)
 	return 1;
 }
 
-/* EXTLINUX installs the string 'EXTLINUX' at offset 3 in the boot
-   sector; this is consistent with FAT filesystems. */
+/*
+ * SYSLINUX installs the string 'SYSLINUX' at offset 3 in the boot
+ * sector; this is consistent with FAT filesystems.  Earlier versions
+ * would install the string "EXTLINUX" instead, handle both.
+ */
 int already_installed(int devfd)
 {
     char buffer[8];
 
     xpread(devfd, buffer, 8, 3);
-    return !memcmp(buffer, "EXTLINUX", 8);
+    return !memcmp(buffer, "SYSLINUX", 8) || !memcmp(buffer, "EXTLINUX", 8);
 }
 
 #ifdef __KLIBC__
@@ -765,22 +685,36 @@ static int open_device(const char *path, struct stat *st, const char **_devname)
     return devfd;
 }
 
-static int ext_read_adv(const char *path, const char *cfg, int devfd)
+static int btrfs_read_adv(int devfd)
 {
-    if (fs_type == BTRFS) { /* btrfs "extlinux.sys" is in 64k blank area */
-	if (xpread(devfd, syslinux_adv, 2 * ADV_SIZE,
-		BTRFS_ADV_OFFSET) != 2 * ADV_SIZE) {
-		perror("btrfs writing adv");
-		return 1;
-	}
-	return 0;
+    if (xpread(devfd, syslinux_adv, 2 * ADV_SIZE, BTRFS_ADV_OFFSET)
+	!= 2 * ADV_SIZE)
+	return -1;
+
+    return syslinux_validate_adv(syslinux_adv) ? 1 : 0;
+}
+
+static int ext_read_adv(const char *path, int devfd, const char **namep)
+{
+    int err;
+    const char *name;
+
+    if (fs_type == BTRFS) {
+	/* btrfs "ldlinux.sys" is in 64k blank area */
+	return btrfs_read_adv(devfd);
+    } else {
+	err = read_adv(path, name = "ldlinux.sys");
+	if (err == 2)		/* ldlinux.sys does not exist */
+	    err = read_adv(path, name = "extlinux.sys");
+	if (namep)
+	    *namep = name; 
+	return err;
     }
-    return read_adv(path, cfg);
 }
 
 static int ext_write_adv(const char *path, const char *cfg, int devfd)
 {
-    if (fs_type == BTRFS) { /* btrfs "extlinux.sys" is in 64k blank area */
+    if (fs_type == BTRFS) { /* btrfs "ldlinux.sys" is in 64k blank area */
 	if (xpwrite(devfd, syslinux_adv, 2 * ADV_SIZE,
 		BTRFS_ADV_OFFSET) != 2 * ADV_SIZE) {
 		perror("writing adv");
@@ -802,25 +736,26 @@ int install_loader(const char *path, int update_only)
 	return 1;
 
     if (update_only && !already_installed(devfd)) {
-	fprintf(stderr, "%s: no previous extlinux boot sector found\n",
+	fprintf(stderr, "%s: no previous syslinux boot sector found\n",
 		program);
 	close(devfd);
 	return 1;
     }
 
     /* Read a pre-existing ADV, if already installed */
-    if (opt.reset_adv)
+    if (opt.reset_adv) {
 	syslinux_reset_adv(syslinux_adv);
-    else if (ext_read_adv(path, "extlinux.sys", devfd) < 0) {
+    } else if (ext_read_adv(path, devfd, NULL) < 0) {
 	close(devfd);
 	return 1;
     }
+
     if (modify_adv() < 0) {
 	close(devfd);
 	return 1;
     }
 
-    /* Install extlinux.sys */
+    /* Install ldlinux.sys */
     if (install_file(path, devfd, &fst)) {
 	close(devfd);
 	return 1;
@@ -845,6 +780,7 @@ int install_loader(const char *path, int update_only)
  */
 int modify_existing_adv(const char *path)
 {
+    const char *filename;
     int devfd;
 
     devfd = open_device(path, NULL, NULL);
@@ -853,7 +789,7 @@ int modify_existing_adv(const char *path)
 
     if (opt.reset_adv)
 	syslinux_reset_adv(syslinux_adv);
-    else if (ext_read_adv(path, "extlinux.sys", devfd) < 0) {
+    else if (ext_read_adv(path, devfd, &filename) < 0) {
 	close(devfd);
 	return 1;
     }
@@ -861,7 +797,7 @@ int modify_existing_adv(const char *path)
 	close(devfd);
 	return 1;
     }
-    if (ext_write_adv(path, "extlinux.sys", devfd) < 0) {
+    if (ext_write_adv(path, filename, devfd) < 0) {
 	close(devfd);
 	return 1;
     }
@@ -871,16 +807,16 @@ int modify_existing_adv(const char *path)
 
 int main(int argc, char *argv[])
 {
-    parse_options(argc, argv, 0);
+    parse_options(argc, argv, MODE_EXTLINUX);
 
     if (!opt.directory)
 	usage(EX_USAGE, 0);
 
     if (opt.update_only == -1) {
-	if (opt.reset_adv || opt.set_once)
+	if (opt.reset_adv || opt.set_once || opt.menu_save)
 	    return modify_existing_adv(opt.directory);
 	else
-	    usage(EX_USAGE, 0);
+	    usage(EX_USAGE, MODE_EXTLINUX);
     }
 
     return install_loader(opt.directory, opt.update_only);
diff --git a/libfat/libfat.h b/libfat/libfat.h
index 1ebc869..a0179d7 100644
--- a/libfat/libfat.h
+++ b/libfat/libfat.h
@@ -26,7 +26,7 @@
 #define LIBFAT_SECTOR_SIZE	512
 #define LIBFAT_SECTOR_MASK	511
 
-typedef uint32_t libfat_sector_t;
+typedef uint64_t libfat_sector_t;
 struct libfat_filesystem;
 
 struct libfat_direntry {
diff --git a/libfat/open.c b/libfat/open.c
index 19a34ad..7281e03 100644
--- a/libfat/open.c
+++ b/libfat/open.c
@@ -21,9 +21,9 @@
 #include "libfatint.h"
 #include "ulint.h"
 
-struct libfat_filesystem
-    *libfat_open(int (*readfunc) (intptr_t, void *, size_t, libfat_sector_t),
-		 intptr_t readptr)
+struct libfat_filesystem *
+libfat_open(int (*readfunc) (intptr_t, void *, size_t, libfat_sector_t),
+	    intptr_t readptr)
 {
     struct libfat_filesystem *fs = NULL;
     struct fat_bootsect *bs;
diff --git a/libinstaller/Makefile b/libinstaller/Makefile
index 82c1990..2beb931 100644
--- a/libinstaller/Makefile
+++ b/libinstaller/Makefile
@@ -1,6 +1,5 @@
 # _bin.c files required by both BTARGET and ITARGET installers
 BINFILES = bootsect_bin.c ldlinux_bin.c \
-	   extlinux_bss_bin.c extlinux_sys_bin.c \
 	   mbr_bin.c gptmbr_bin.c
 
 PERL	 = perl
@@ -13,12 +12,6 @@ bootsect_bin.c: ../core/ldlinux.bss bin2c.pl
 ldlinux_bin.c: ../core/ldlinux.sys bin2c.pl
 	$(PERL) bin2c.pl syslinux_ldlinux 512 < $< > $@
 
-extlinux_bss_bin.c: ../core/extlinux.bss bin2c.pl
-	$(PERL) bin2c.pl extlinux_bootsect < $< > $@
-
-extlinux_sys_bin.c: ../core/extlinux.sys bin2c.pl
-	$(PERL) bin2c.pl extlinux_image 512 < $< > $@
-
 mbr_bin.c: ../mbr/mbr.bin bin2c.pl
 	$(PERL) bin2c.pl syslinux_mbr < $< > $@
 
diff --git a/libinstaller/setadv.c b/libinstaller/setadv.c
index 682b883..9cf6f18 100644
--- a/libinstaller/setadv.c
+++ b/libinstaller/setadv.c
@@ -1,6 +1,7 @@
 /* ----------------------------------------------------------------------- *
  *
  *   Copyright 2007-2008 H. Peter Anvin - All Rights Reserved
+ *   Copyright 2010 Intel Corporation; author: H. Peter Anvin
  *
  *   This program is free software; you can redistribute it and/or modify
  *   it under the terms of the GNU General Public License as published by
@@ -26,13 +27,7 @@
 #include <stddef.h>
 #include <stdint.h>
 #include <string.h>
-#include <getopt.h>
-#include <unistd.h>
 #include <errno.h>
-#include <fcntl.h>
-#include <sys/ioctl.h>
-#include <sys/stat.h>
-#include <sys/types.h>
 #include "syslxint.h"
 #include "syslxcom.h"
 
@@ -170,127 +165,3 @@ int syslinux_validate_adv(unsigned char *advbuf)
 	return -1;
     }
 }
-
-/*
- * Read the ADV from an existing instance, or initialize if invalid.
- * Returns -1 on fatal errors, 0 if ADV is okay, and 1 if no valid
- * ADV was found.
- */
-int read_adv(const char *path, const char *cfg)
-{
-    char *file;
-    int fd = -1;
-    struct stat st;
-    int err = 0;
-
-    err = asprintf(&file, "%s%s%s",
-	path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/", cfg);
-
-    if (!file) {
-	perror(program);
-	return -1;
-    }
-
-    fd = open(file, O_RDONLY);
-    if (fd < 0) {
-	if (errno != ENOENT) {
-	    err = -1;
-	} else {
-	    syslinux_reset_adv(syslinux_adv);
-	}
-    } else if (fstat(fd, &st)) {
-	err = -1;
-    } else if (st.st_size < 2 * ADV_SIZE) {
-	/* Too small to be useful */
-	syslinux_reset_adv(syslinux_adv);
-	err = 0;		/* Nothing to read... */
-    } else if (xpread(fd, syslinux_adv, 2 * ADV_SIZE,
-		      st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
-	err = -1;
-    } else {
-	/* We got it... maybe? */
-	err = syslinux_validate_adv(syslinux_adv) ? 1 : 0;
-    }
-
-    if (err < 0)
-	perror(file);
-
-    if (fd >= 0)
-	close(fd);
-    if (file)
-	free(file);
-
-    return err;
-}
-
-/*
- * Update the ADV in an existing installation.
- */
-int write_adv(const char *path, const char *cfg)
-{
-    unsigned char advtmp[2 * ADV_SIZE];
-    char *file;
-    int fd = -1;
-    struct stat st, xst;
-    int err = 0;
-
-    err = asprintf(&file, "%s%s%s",
-	path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/", cfg);
-
-    if (!file) {
-	perror(program);
-	return -1;
-    }
-
-    fd = open(file, O_RDONLY);
-    if (fd < 0) {
-	err = -1;
-    } else if (fstat(fd, &st)) {
-	err = -1;
-    } else if (st.st_size < 2 * ADV_SIZE) {
-	/* Too small to be useful */
-	err = -2;
-    } else if (xpread(fd, advtmp, 2 * ADV_SIZE,
-		      st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
-	err = -1;
-    } else {
-	/* We got it... maybe? */
-	err = syslinux_validate_adv(advtmp) ? -2 : 0;
-	if (!err) {
-	    /* Got a good one, write our own ADV here */
-	    clear_attributes(fd);
-
-	    /* Need to re-open read-write */
-	    close(fd);
-	    fd = open(file, O_RDWR | O_SYNC);
-	    if (fd < 0) {
-		err = -1;
-	    } else if (fstat(fd, &xst) || xst.st_ino != st.st_ino ||
-		       xst.st_dev != st.st_dev || xst.st_size != st.st_size) {
-		fprintf(stderr, "%s: race condition on write\n", file);
-		err = -2;
-	    }
-	    /* Write our own version ... */
-	    if (xpwrite(fd, syslinux_adv, 2 * ADV_SIZE,
-			st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
-		err = -1;
-	    }
-
-	    sync();
-	    set_attributes(fd);
-	}
-    }
-
-    if (err == -2)
-	fprintf(stderr, "%s: cannot write auxilliary data (need --update)?\n",
-		file);
-    else if (err == -1)
-	perror(file);
-
-    if (fd >= 0)
-	close(fd);
-    if (file)
-	free(file);
-
-    return err;
-}
diff --git a/libinstaller/syslinux.h b/libinstaller/syslinux.h
index 8d0212c..710d30e 100644
--- a/libinstaller/syslinux.h
+++ b/libinstaller/syslinux.h
@@ -26,6 +26,11 @@ extern unsigned char syslinux_ldlinux[];
 extern const unsigned int syslinux_ldlinux_len;
 extern const int syslinux_ldlinux_mtime;
 
+#define boot_sector	syslinux_bootsect
+#define boot_sector_len syslinux_bootsect_len
+#define boot_image	syslinux_ldlinux
+#define boot_image_len	syslinux_ldlinux_len
+
 extern unsigned char syslinux_mbr[];
 extern const unsigned int syslinux_mbr_len;
 extern const int syslinux_mbr_mtime;
@@ -41,7 +46,9 @@ void syslinux_make_bootsect(void *);
 const char *syslinux_check_bootsect(const void *bs);
 
 /* This patches the boot sector and ldlinux.sys based on a sector map */
-int syslinux_patch(const uint32_t * sectors, int nsectors,
-		   int stupid, int raid_mode);
+typedef uint64_t sector_t;
+int syslinux_patch(const sector_t *sectors, int nsectors,
+		   int stupid, int raid_mode,
+		   const char *subdir, const char *subvol);
 
 #endif
diff --git a/libinstaller/syslxcom.c b/libinstaller/syslxcom.c
index 825419b..b176f6d 100644
--- a/libinstaller/syslxcom.c
+++ b/libinstaller/syslxcom.c
@@ -26,13 +26,11 @@
 #include <getopt.h>
 #include <unistd.h>
 #include <errno.h>
-#include <sys/ioctl.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <sys/mount.h>
 #include <sys/vfs.h>
-#include <linux/fs.h>		/* FIGETBSZ, FIBMAP */
-#include <linux/msdos_fs.h>	/* FAT_IOCTL_SET_ATTRIBUTES */
+#include "linuxioctl.h"
 #include "syslxcom.h"
 
 const char *program;
@@ -46,15 +44,6 @@ int fs_type;
 #endif
 
 #define SECTOR_SHIFT	9
-#define EXT2_IMMUTABLE_FL		0x00000010	/* Immutable file */
-
-/*
- * ioctl commands
- */
-#define	EXT2_IOC_GETFLAGS		_IOR('f', 1, long)
-#define	EXT2_IOC_SETFLAGS		_IOW('f', 2, long)
-#define	EXT2_IOC_GETVERSION		_IOR('v', 1, long)
-#define	EXT2_IOC_SETVERSION		_IOW('v', 2, long)
 
 static void die(const char *msg)
 {
@@ -180,13 +169,86 @@ void set_attributes(int fd)
     }
 }
 
-/*
- * Produce file map
- */
-int sectmap(int fd, uint32_t * sectors, int nsectors)
+/* New FIEMAP based mapping */
+static int sectmap_fie(int fd, sector_t *sectors, int nsectors)
+{
+    struct fiemap *fm;
+    struct fiemap_extent *fe;
+    unsigned int i, nsec;
+    sector_t sec, *secp, *esec;
+    struct stat st;
+    uint64_t maplen;
+
+    if (fstat(fd, &st))
+	return -1;
+
+    fm = alloca(sizeof(struct fiemap)
+		+ nsectors * sizeof(struct fiemap_extent));
+
+    memset(fm, 0, sizeof *fm);
+
+    maplen = (uint64_t)nsectors << SECTOR_SHIFT;
+    if (maplen > (uint64_t)st.st_size)
+	maplen = st.st_size;
+
+    fm->fm_start        = 0;
+    fm->fm_length       = maplen;
+    fm->fm_flags        = FIEMAP_FLAG_SYNC;
+    fm->fm_extent_count = nsectors;
+
+    if (ioctl(fd, FS_IOC_FIEMAP, fm))
+	return -1;
+
+    memset(sectors, 0, nsectors * sizeof *sectors);
+    esec = sectors + nsectors;
+
+    fe = fm->fm_extents;
+
+    if (fm->fm_mapped_extents < 1 ||
+	!(fe[fm->fm_mapped_extents-1].fe_flags & FIEMAP_EXTENT_LAST))
+	return -1;
+
+    for (i = 0; i < fm->fm_mapped_extents; i++) {
+	if (fe->fe_flags & FIEMAP_EXTENT_LAST) {
+	    /* If this is the *final* extent, pad the length */
+	    fe->fe_length = (fe->fe_length + SECTOR_SIZE - 1)
+		& ~(SECTOR_SIZE - 1);
+	}
+
+	if ((fe->fe_logical | fe->fe_physical| fe->fe_length) &
+	    (SECTOR_SIZE - 1))
+	    return -1;
+
+	if (fe->fe_flags & (FIEMAP_EXTENT_UNKNOWN|
+			    FIEMAP_EXTENT_DELALLOC|
+			    FIEMAP_EXTENT_ENCODED|
+			    FIEMAP_EXTENT_DATA_ENCRYPTED|
+			    FIEMAP_EXTENT_UNWRITTEN))
+	    return -1;
+
+	secp = sectors + (fe->fe_logical >> SECTOR_SHIFT);
+	sec  = fe->fe_physical >> SECTOR_SHIFT;
+	nsec = fe->fe_length >> SECTOR_SHIFT;
+
+	while (nsec--) {
+	    if (secp >= esec)
+		break;
+	    *secp++ = sec++;
+	}
+
+	fe++;
+    }
+
+    return 0;
+}
+
+/* Legacy FIBMAP based mapping */
+static int sectmap_fib(int fd, sector_t *sectors, int nsectors)
 {
-    unsigned int blksize, blk, nblk;
+    unsigned int blk, nblk;
     unsigned int i;
+    unsigned int blksize;
+    sector_t sec;
 
     /* Get block size */
     if (ioctl(fd, FIGETBSZ, &blksize))
@@ -197,22 +259,28 @@ int sectmap(int fd, uint32_t * sectors, int nsectors)
 
     nblk = 0;
     while (nsectors) {
-
 	blk = nblk++;
-	dprintf("querying block %u\n", blk);
 	if (ioctl(fd, FIBMAP, &blk))
 	    return -1;
 
-	blk *= blksize;
+	sec = (sector_t)blk * blksize;
 	for (i = 0; i < blksize; i++) {
-	    if (!nsectors)
-		return 0;
-
-	    dprintf("Sector: %10u\n", blk);
-	    *sectors++ = blk++;
-	    nsectors--;
+	    *sectors++ = sec++;
+	    if (! --nsectors)
+		break;
 	}
     }
 
     return 0;
 }
+
+/*
+ * Produce file map
+ */
+int sectmap(int fd, sector_t *sectors, int nsectors)
+{
+    if (!sectmap_fie(fd, sectors, nsectors))
+	return 0;
+
+    return sectmap_fib(fd, sectors, nsectors);
+}
diff --git a/libinstaller/syslxcom.h b/libinstaller/syslxcom.h
index ba4f1d0..39ca09d 100644
--- a/libinstaller/syslxcom.h
+++ b/libinstaller/syslxcom.h
@@ -1,6 +1,8 @@
 #ifndef _H_SYSLXCOM_
 #define _H_SYSLXCOM_
 
+#include "syslinux.h"
+
 /* Global fs_type for handling fat, ext2/3/4 and btrfs */
 enum filesystem {
     NONE,
@@ -15,6 +17,6 @@ ssize_t xpread(int fd, void *buf, size_t count, off_t offset);
 ssize_t xpwrite(int fd, const void *buf, size_t count, off_t offset);
 void clear_attributes(int fd);
 void set_attributes(int fd);
-int sectmap(int fd, uint32_t * sectors, int nsectors);
+int sectmap(int fd, sector_t *sectors, int nsectors);
 
 #endif
diff --git a/libinstaller/syslxint.h b/libinstaller/syslxint.h
index 2276bfe..f16c2e5 100644
--- a/libinstaller/syslxint.h
+++ b/libinstaller/syslxint.h
@@ -15,6 +15,12 @@
 
 #include "syslinux.h"
 
+#if defined(__386__) || defined(__i386__) || defined(__x86_64__)
+# define X86_MEM 1		/* Littleendian and unaligned safe */
+#else
+# define X86_MEM 0
+#endif
+
 /*
  * Access functions for littleendian numbers, possibly misaligned.
  */
@@ -25,37 +31,47 @@ static inline uint8_t get_8(const uint8_t * p)
 
 static inline uint16_t get_16(const uint16_t * p)
 {
-#if defined(__i386__) || defined(__x86_64__)
+#if X86_MEM
     /* Littleendian and unaligned-capable */
     return *p;
 #else
     const uint8_t *pp = (const uint8_t *)p;
-    return (uint16_t) pp[0] + ((uint16_t) pp[1] << 8);
+    return pp[0] + ((uint16_t)pp[1] << 8);
 #endif
 }
 
 static inline uint32_t get_32(const uint32_t * p)
 {
-#if defined(__i386__) || defined(__x86_64__)
+#if X86_MEM
     /* Littleendian and unaligned-capable */
     return *p;
 #else
-    const uint8_t *pp = (const uint8_t *)p;
-    return (uint32_t) pp[0] + ((uint32_t) pp[1] << 8) +
-	((uint32_t) pp[2] << 16) + ((uint32_t) pp[3] << 24);
+    const uint16_t *pp = (const uint16_t *)p;
+    return get_16(pp[0]) + (uint32_t)get_16(pp[1]);
+#endif
+}
+
+static inline uint64_t get_64(const uint64_t * p)
+{
+#if X86_MEM
+    /* Littleendian and unaligned-capable */
+    return *p;
+#else
+    const uint32_t *pp = (const uint32_t *)p;
+    return get_32(pp[0]) + (uint64_t)get_32(pp[1]);
 #endif
 }
 
-static inline void set_8(uint8_t * p, uint8_t v)
+static inline void set_8(uint8_t *p, uint8_t v)
 {
     *p = v;
 }
 
-static inline void set_16(uint16_t * p, uint16_t v)
+static inline void set_16(uint16_t *p, uint16_t v)
 {
-#if defined(__i386__) || defined(__x86_64__)
+#if X86_MEM
     /* Littleendian and unaligned-capable */
-    *(uint16_t *) p = v;
+    *p = v;
 #else
     uint8_t *pp = (uint8_t *) p;
     pp[0] = (v & 0xff);
@@ -63,11 +79,11 @@ static inline void set_16(uint16_t * p, uint16_t v)
 #endif
 }
 
-static inline void set_32(uint32_t * p, uint32_t v)
+static inline void set_32(uint32_t *p, uint32_t v)
 {
-#if defined(__i386__) || defined(__x86_64__)
+#if X86_MEM
     /* Littleendian and unaligned-capable */
-    *(uint32_t *) p = v;
+    *p = v;
 #else
     uint8_t *pp = (uint8_t *) p;
     pp[0] = (v & 0xff);
@@ -77,6 +93,68 @@ static inline void set_32(uint32_t * p, uint32_t v)
 #endif
 }
 
+static inline void set_64(uint64_t *p, uint64_t v)
+{
+#if X86_MEM
+    /* Littleendian and unaligned-capable */
+    *p = v;
+#else
+    uint32_t *pp = (uint32_t *) p;
+    set_32(pp[0], v);
+    set_32(pp[1], v >> 32);
+#endif
+}
+
+/*
+ * Special handling for the MS-DOS derivative: syslinux_ldlinux
+ * is a "far" object...
+ */
+#ifdef __MSDOS__
+
+extern uint16_t ldlinux_seg;	/* Defined in dos/syslinux.c */
+
+static inline __attribute__ ((const))
+uint16_t ds(void)
+{
+    uint16_t v;
+    asm("movw %%ds,%0":"=rm"(v));
+    return v;
+}
+
+static inline void *set_fs(const void *p)
+{
+    uint16_t seg;
+
+    seg = ldlinux_seg + ((size_t) p >> 4);
+    asm volatile ("movw %0,%%fs"::"rm" (seg));
+    return (void *)((size_t) p & 0xf);
+}
+
+uint8_t get_8_sl(const uint8_t * p);
+uint16_t get_16_sl(const uint16_t * p);
+uint32_t get_32_sl(const uint32_t * p);
+uint64_t get_64_sl(const uint64_t * p);
+void set_8_sl(uint8_t * p, uint8_t v);
+void set_16_sl(uint16_t * p, uint16_t v);
+void set_32_sl(uint32_t * p, uint32_t v);
+void set_64_sl(uint64_t * p, uint64_t v);
+void memcpy_to_sl(void *dst, const void *src, size_t len);
+
+#else
+
+/* Sane system ... */
+#define get_8_sl(x)    		get_8(x)
+#define get_16_sl(x)   		get_16(x)
+#define get_32_sl(x)   		get_32(x)
+#define get_64_sl(x)   		get_64(x)
+#define set_8_sl(x,y)  		set_8(x,y)
+#define set_16_sl(x,y) 		set_16(x,y)
+#define set_32_sl(x,y) 		set_32(x,y)
+#define set_64_sl(x,y) 		set_64(x,y)
+#define memcpy_to_sl(d,s,l)	memcpy(d,s,l)
+
+#endif
+
 #define LDLINUX_MAGIC	0x3eb202fe
 
 /* Patch area for disk-based installers */
@@ -87,15 +165,31 @@ struct patch_area {
     uint16_t adv_sectors;
     uint32_t dwords;
     uint32_t checksum;
-    uint16_t diroffset;
-    uint16_t dirlen;
-    uint16_t subvoloffset;
-    uint16_t subvollen;
-    uint16_t secptroffset;
-    uint16_t secptrcnt;
+    uint16_t maxtransfer;
+    uint16_t epaoffset;		/* Pointer to the extended patch area */
 };
 
-  /* FAT bootsector format, also used by other disk-based derivatives */
+struct ext_patch_area {
+    uint16_t advptroffset;	/* ADV pointers */
+    uint16_t diroffset;		/* Current directory field */
+    uint16_t dirlen;		/* Length of current directory field */
+    uint16_t subvoloffset;	/* Subvolume field */
+    uint16_t subvollen;		/* Length of subvolume field */
+    uint16_t secptroffset;	/* Sector extent pointers */
+    uint16_t secptrcnt;		/* Number of sector extent pointers */
+
+    uint16_t sect1ptr0;		/* Boot sector offset of sector 1 ptr LSW */
+    uint16_t sect1ptr1;		/* Boot sector offset of sector 1 ptr MSW */
+    uint16_t raidpatch;		/* Boot sector RAID mode patch pointer */
+};
+
+/* Sector extent */
+struct syslinux_extent {
+    uint64_t lba;
+    uint16_t len;
+} __attribute__((packed));
+
+/* FAT bootsector format, also used by other disk-based derivatives */
 struct boot_sector {
     uint8_t bsJump[3];
     char bsOemName[8];
@@ -120,7 +214,7 @@ struct boot_sector {
 	    uint32_t VolumeID;
 	    char VolumeLabel[11];
 	    char FileSysType[8];
-	    uint8_t Code[442];
+	    uint8_t Code[448];
 	} __attribute__ ((packed)) bs16;
 	struct {
 	    uint32_t FATSz32;
@@ -136,17 +230,15 @@ struct boot_sector {
 	    uint32_t VolumeID;
 	    char VolumeLabel[11];
 	    char FileSysType[8];
-	    uint8_t Code[414];
+	    uint8_t Code[420];
 	} __attribute__ ((packed)) bs32;
     } __attribute__ ((packed));
 
-    uint32_t NextSector;	/* Pointer to the first unused sector */
-    uint16_t MaxTransfer;	/* Max sectors per transfer */
     uint16_t bsSignature;
 } __attribute__ ((packed));
 
 #define bsHead      bsJump
-#define bsHeadLen   offsetof(struct boot_sector, bsOemName)
+#define bsHeadLen   offsetof(struct boot_sector, bsBytesPerSec)
 #define bsCode	    bs32.Code	/* The common safe choice */
 #define bsCodeLen   (offsetof(struct boot_sector, bsSignature) - \
 		     offsetof(struct boot_sector, bsCode))
diff --git a/libinstaller/syslxmod.c b/libinstaller/syslxmod.c
index 9ab139c..a68f19f 100644
--- a/libinstaller/syslxmod.c
+++ b/libinstaller/syslxmod.c
@@ -1,7 +1,7 @@
 /* ----------------------------------------------------------------------- *
  *
  *   Copyright 1998-2008 H. Peter Anvin - All Rights Reserved
- *   Copyright 2009 Intel Corporation; author H. Peter Anvin
+ *   Copyright 2009-2010 Intel Corporation; author H. Peter Anvin
  *
  *   This program is free software; you can redistribute it and/or modify
  *   it under the terms of the GNU General Public License as published by
@@ -21,200 +21,67 @@
 #include <inttypes.h>
 #include <string.h>
 #include <stddef.h>
+#include <stdlib.h>
 
 #include "syslinux.h"
 #include "syslxint.h"
 
-void syslinux_make_bootsect(void *bs)
-{
-    struct boot_sector *bootsect = bs;
-    const struct boot_sector *sbs =
-	(const struct boot_sector *)syslinux_bootsect;
-
-    memcpy(&bootsect->bsHead, &sbs->bsHead, bsHeadLen);
-    memcpy(&bootsect->bsCode, &sbs->bsCode, bsCodeLen);
-}
 
 /*
- * Check to see that what we got was indeed an MS-DOS boot sector/superblock;
- * Return NULL if OK and otherwise an error message;
+ * Generate sector extents
  */
-const char *syslinux_check_bootsect(const void *bs)
-{
-    int veryold;
-    int sectorsize;
-    long long sectors, fatsectors, dsectors;
-    long long clusters;
-    int rootdirents, clustersize;
-    const struct boot_sector *sectbuf = bs;
-
-    veryold = 0;
-
-    /* Must be 0xF0 or 0xF8..0xFF */
-    if (get_8(&sectbuf->bsMedia) != 0xF0 && get_8(&sectbuf->bsMedia) < 0xF8)
-	return "invalid media signature (not a FAT filesystem?)";
-
-    sectorsize = get_16(&sectbuf->bsBytesPerSec);
-    if (sectorsize == SECTOR_SIZE)
-	;			/* ok */
-    else if (sectorsize >= 512 && sectorsize <= 4096 &&
-	     (sectorsize & (sectorsize - 1)) == 0)
-	return "unsupported sectors size";
-    else
-	return "impossible sector size";
-
-    clustersize = get_8(&sectbuf->bsSecPerClust);
-    if (clustersize == 0 || (clustersize & (clustersize - 1)))
-	return "impossible cluster size";
-
-    sectors = get_16(&sectbuf->bsSectors);
-    sectors = sectors ? sectors : get_32(&sectbuf->bsHugeSectors);
-
-    dsectors = sectors - get_16(&sectbuf->bsResSectors);
-
-    fatsectors = get_16(&sectbuf->bsFATsecs);
-    fatsectors = fatsectors ? fatsectors : get_32(&sectbuf->bs32.FATSz32);
-    fatsectors *= get_8(&sectbuf->bsFATs);
-    dsectors -= fatsectors;
-
-    rootdirents = get_16(&sectbuf->bsRootDirEnts);
-    dsectors -= (rootdirents + sectorsize / 32 - 1) / sectorsize;
-
-    if (dsectors < 0)
-	return "negative number of data sectors";
-
-    if (fatsectors == 0)
-	return "zero FAT sectors";
-
-    clusters = dsectors / clustersize;
-
-    if (clusters < 0xFFF5) {
-	/* FAT12 or FAT16 */
-
-	if (!get_16(&sectbuf->bsFATsecs))
-	    return "zero FAT sectors (FAT12/16)";
-
-	if (get_8(&sectbuf->bs16.BootSignature) == 0x29) {
-	    if (!memcmp(&sectbuf->bs16.FileSysType, "FAT12   ", 8)) {
-		if (clusters >= 0xFF5)
-		    return "more than 4084 clusters but claims FAT12";
-	    } else if (!memcmp(&sectbuf->bs16.FileSysType, "FAT16   ", 8)) {
-		if (clusters < 0xFF5)
-		    return "less than 4084 clusters but claims FAT16";
-	    } else if (!memcmp(&sectbuf->bs16.FileSysType, "FAT32   ", 8)) {
-		    return "less than 65525 clusters but claims FAT32";
-	    } else if (memcmp(&sectbuf->bs16.FileSysType, "FAT     ", 8)) {
-		static char fserr[] =
-		    "filesystem type \"????????\" not supported";
-		memcpy(fserr + 17, &sectbuf->bs16.FileSysType, 8);
-		return fserr;
-	    }
-	}
-    } else if (clusters < 0x0FFFFFF5) {
-	/*
-	 * FAT32...
-	 *
-	 * Moving the FileSysType and BootSignature was a lovely stroke
-	 * of M$ idiocy...
-	 */
-	if (get_8(&sectbuf->bs32.BootSignature) != 0x29 ||
-	    memcmp(&sectbuf->bs32.FileSysType, "FAT32   ", 8))
-	    return "missing FAT32 signature";
-    } else {
-	return "impossibly large number of clusters";
-    }
-
-    return NULL;
-}
-
-/*
- * Special handling for the MS-DOS derivative: syslinux_ldlinux
- * is a "far" object...
- */
-#ifdef __MSDOS__
-
-#define __noinline __attribute__((noinline))
-
-extern uint16_t ldlinux_seg;	/* Defined in dos/syslinux.c */
-
-static inline __attribute__ ((const))
-uint16_t ds(void)
-{
-    uint16_t v;
-asm("movw %%ds,%0":"=rm"(v));
-    return v;
-}
-
-static inline void *set_fs(const void *p)
+static void generate_extents(struct syslinux_extent *ex, int nptrs,
+			     const sector_t *sectp, int nsect)
 {
-    uint16_t seg;
-
-    seg = ldlinux_seg + ((size_t) p >> 4);
-    asm volatile ("movw %0,%%fs"::"rm" (seg));
-    return (void *)((size_t) p & 0xf);
-}
+    uint32_t addr = 0x7c00 + 2*SECTOR_SIZE;
+    uint32_t base;
+    sector_t sect, lba;
+    unsigned int len;
 
-#if 0				/* unused */
-static __noinline uint8_t get_8_sl(const uint8_t * p)
-{
-    uint8_t v;
+    len = lba = base = 0;
 
-    p = set_fs(p);
-    asm volatile ("movb %%fs:%1,%0":"=q" (v):"m"(*p));
-    return v;
-}
-#endif
+    memset(ex, 0, nptrs * sizeof *ex);
 
-static __noinline uint16_t get_16_sl(const uint16_t * p)
-{
-    uint16_t v;
+    while (nsect) {
+	sect = *sectp++;
 
-    p = set_fs(p);
-    asm volatile ("movw %%fs:%1,%0":"=r" (v):"m"(*p));
-    return v;
-}
+	if (len && sect == lba + len &&
+	    ((addr ^ (base + len * SECTOR_SIZE)) & 0xffff0000) == 0) {
+	    /* We can add to the current extent */
+	    len++;
+	    goto next;
+	}
 
-static __noinline uint32_t get_32_sl(const uint32_t * p)
-{
-    uint32_t v;
+	if (len) {
+	    set_64_sl(&ex->lba, lba);
+	    set_16_sl(&ex->len, len);
+	    ex++;
+	}
 
-    p = set_fs(p);
-    asm volatile ("movl %%fs:%1,%0":"=r" (v):"m"(*p));
-    return v;
-}
+	base = addr;
+	lba  = sect;
+	len  = 1;
 
-#if 0				/* unused */
-static __noinline void set_8_sl(uint8_t * p, uint8_t v)
-{
-    p = set_fs(p);
-    asm volatile ("movb %1,%%fs:%0":"=m" (*p):"qi"(v));
-}
-#endif
+    next:
+	addr += SECTOR_SIZE;
+	nsect--;
+    }
 
-static __noinline void set_16_sl(uint16_t * p, uint16_t v)
-{
-    p = set_fs(p);
-    asm volatile ("movw %1,%%fs:%0":"=m" (*p):"ri"(v));
+    if (len) {
+	set_64_sl(&ex->lba, lba);
+	set_16_sl(&ex->len, len);
+	ex++;
+    }
 }
 
-static __noinline void set_32_sl(uint32_t * p, uint32_t v)
+/*
+ * Form a pointer based on a 16-bit patcharea/epa field
+ */
+static inline void *ptr(void *img, uint16_t *offset_p)
 {
-    p = set_fs(p);
-    asm volatile ("movl %1,%%fs:%0":"=m" (*p):"ri"(v));
+    return (char *)img + get_16_sl(offset_p);
 }
 
-#else
-
-/* Sane system ... */
-#define get_8_sl(x)    get_8(x)
-#define get_16_sl(x)   get_16(x)
-#define get_32_sl(x)   get_32(x)
-#define set_8_sl(x,y)  set_8(x,y)
-#define set_16_sl(x,y) set_16(x,y)
-#define set_32_sl(x,y) set_32(x,y)
-
-#endif
-
 /*
  * This patches the boot sector and the beginning of ldlinux.sys
  * based on an ldlinux.sys sector map passed in.  Typically this is
@@ -226,67 +93,105 @@ static __noinline void set_32_sl(uint32_t * p, uint32_t v)
  * Returns the number of modified bytes in ldlinux.sys if successful,
  * otherwise -1.
  */
-int syslinux_patch(const uint32_t * sectors, int nsectors,
-		   int stupid, int raid_mode)
+#define NADV 2
+
+int syslinux_patch(const sector_t *sectp, int nsectors,
+		   int stupid, int raid_mode,
+		   const char *subdir, const char *subvol)
 {
     struct patch_area *patcharea;
+    struct ext_patch_area *epa;
+    struct syslinux_extent *ex;
     uint32_t *wp;
-    int nsect = (syslinux_ldlinux_len + 511) >> 9;
+    int nsect = ((boot_image_len + SECTOR_SIZE - 1) >> SECTOR_SHIFT) + 2;
     uint32_t csum;
-    int i, dw, nptrs, rv;
-    struct boot_sector *sbs = (struct boot_sector *)syslinux_bootsect;
+    int i, dw, nptrs;
+    struct boot_sector *sbs = (struct boot_sector *)boot_sector;
+    uint64_t *advptrs;
 
     if (nsectors < nsect)
-	return -1;
-
-    /* Patch in options, as appropriate */
-    if (stupid) {
-	/* Access only one sector at a time */
-	set_16(&sbs->MaxTransfer, 1);
-    }
-
-    i = get_16(&sbs->bsSignature);
-    if (raid_mode)
-	set_16((uint16_t *) ((char *)sbs + i), 0x18CD);	/* INT 18h */
-    set_16(&sbs->bsSignature, 0xAA55);
-
-    /* First sector need pointer in boot sector */
-    set_32(&sbs->NextSector, *sectors++);
+	return -1;		/* The actual file is too small for content */
 
     /* Search for LDLINUX_MAGIC to find the patch area */
-    for (wp = (uint32_t *) syslinux_ldlinux; get_32_sl(wp) != LDLINUX_MAGIC;
-	 wp++) ;
+    for (wp = (uint32_t *)boot_image; get_32_sl(wp) != LDLINUX_MAGIC;
+	 wp++)
+	;
     patcharea = (struct patch_area *)wp;
+    epa = ptr(boot_image, &patcharea->epaoffset);
+
+    /* First sector need pointer in boot sector */
+    set_32(ptr(sbs, &epa->sect1ptr0), sectp[0]);
+    set_32(ptr(sbs, &epa->sect1ptr1), sectp[0] >> 32);
+    sectp++;
+
+    /* Handle RAID mode */
+    if (raid_mode) {
+	/* Patch in INT 18h = CD 18 */
+	set_16(ptr(sbs, &epa->raidpatch), 0x18CD);
+    }
 
     /* Set up the totals */
-    dw = syslinux_ldlinux_len >> 2;	/* COMPLETE dwords, excluding ADV */
-    set_16_sl(&patcharea->data_sectors, nsect);	/* Not including ADVs */
+    dw = boot_image_len >> 2;	/* COMPLETE dwords, excluding ADV */
+    set_16_sl(&patcharea->data_sectors, nsect - 2); /* Not including ADVs */
     set_16_sl(&patcharea->adv_sectors, 2);	/* ADVs need 2 sectors */
     set_32_sl(&patcharea->dwords, dw);
 
-    /* Set the sector pointers */
-    wp = (uint32_t *) ((char *)syslinux_ldlinux +
-		       get_16_sl(&patcharea->secptroffset));
-    nptrs = get_16_sl(&patcharea->secptrcnt);
+    /* Handle Stupid mode */
+    if (stupid) {
+	/* Access only one sector at a time */
+	set_16_sl(&patcharea->maxtransfer, 1);
+    }
+
+    /* Set the sector extents */
+    ex = ptr(boot_image, &epa->secptroffset);
+    nptrs = get_16_sl(&epa->secptrcnt);
 
-    nsect += 2;
-    while (--nsect) { /* the first sector is in bs->NextSector */
-	set_32_sl(wp++, *sectors++);
-	nptrs--;
+    if (nsect > nptrs) {
+	/* Not necessarily an error in this case, but a general problem */
+	fprintf(stderr, "Insufficient extent space, build error!\n");
+	exit(1);
     }
-    while (nptrs--)
-	set_32_sl(wp++, 0);
 
-    rv = (char *)wp - (char *)syslinux_ldlinux;
+    /* -1 for the pointer in the boot sector, -2 for the two ADVs */
+    generate_extents(ex, nptrs, sectp, nsect-1-2);
+
+    /* ADV pointers */
+    advptrs = ptr(boot_image, &epa->advptroffset);
+    set_64_sl(&advptrs[0], sectp[nsect-1-2]);
+    set_64_sl(&advptrs[1], sectp[nsect-1-1]);
+
+    /* Poke in the base directory path */
+    if (subdir) {
+	int sublen = strlen(subdir) + 1;
+	if (get_16_sl(&epa->dirlen) < sublen) {
+	    fprintf(stderr, "Subdirectory path too long... aborting install!\n");
+	    exit(1);
+	}
+	memcpy_to_sl(ptr(boot_image, &epa->diroffset), subdir, sublen);
+    }
+
+    /* Poke in the subvolume information */
+    if (subvol) {
+	int sublen = strlen(subvol) + 1;
+	if (get_16_sl(&epa->subvollen) < sublen) {
+	    fprintf(stderr, "Subvol name too long... aborting install!\n");
+	    exit(1);
+	}
+	memcpy_to_sl(ptr(boot_image, &epa->subvoloffset), subvol, sublen);
+    }
 
     /* Now produce a checksum */
     set_32_sl(&patcharea->checksum, 0);
 
     csum = LDLINUX_MAGIC;
-    for (i = 0, wp = (uint32_t *) syslinux_ldlinux; i < dw; i++, wp++)
+    for (i = 0, wp = (uint32_t *)boot_image; i < dw; i++, wp++)
 	csum -= get_32_sl(wp);	/* Negative checksum */
 
     set_32_sl(&patcharea->checksum, csum);
 
-    return rv;
+    /*
+     * Assume all bytes modified.  This can be optimized at the expense
+     * of keeping track of what the highest modified address ever was.
+     */
+    return dw << 2;
 }
diff --git a/libinstaller/syslxopt.c b/libinstaller/syslxopt.c
index 7718de3..0ff2efb 100644
--- a/libinstaller/syslxopt.c
+++ b/libinstaller/syslxopt.c
@@ -20,6 +20,7 @@
 #include <stdlib.h>
 #include <stddef.h>
 #include <stdint.h>
+#include <string.h>
 #include <getopt.h>
 #include <sysexits.h>
 #include "../version.h"
@@ -38,12 +39,14 @@ struct sys_options opt = {
     .directory = NULL,
     .device = NULL,
     .offset = 0,
+    .menu_save = NULL,
 };
 
 const struct option long_options[] = {
+    {"force", 0, NULL, 'f'},	/* dummy option for compatibility */
     {"install", 0, NULL, 'i'},
     {"directory", 1, NULL, 'd'},
-    {"offset", 1, NULL, 'f'},
+    {"offset", 1, NULL, 't'},
     {"update", 0, NULL, 'U'},
     {"zipdrive", 0, NULL, 'z'},
     {"sectors", 1, NULL, 'S'},
@@ -52,26 +55,36 @@ const struct option long_options[] = {
     {"raid-mode", 0, NULL, 'r'},
     {"version", 0, NULL, 'v'},
     {"help", 0, NULL, 'h'},
-    {"once", 1, NULL, 'o'},
+    {"once", 1, NULL, OPT_ONCE},
     {"clear-once", 0, NULL, 'O'},
     {"reset-adv", 0, NULL, OPT_RESET_ADV},
+    {"menu-save", 1, NULL, 'M'},
     {0, 0, 0, 0}
 };
 
-const char short_options[] = "id:f:UuzS:H:rvho:O";
+const char short_options[] = "t:fid:UuzS:H:rvho:OM:";
 
-void __attribute__ ((noreturn)) usage(int rv, int mode)
+void __attribute__ ((noreturn)) usage(int rv, enum syslinux_mode mode)
 {
-    if (mode) /* for unmounted fs installation */
+    switch (mode) {
+    case MODE_SYSLINUX:
+	/* For unmounted fs installation (syslinux) */
 	fprintf(stderr,
 	    "Usage: %s [options] device\n"
-	    "  --offset     -f Offset of the file system on the device \n"
+	    "  --offset     -t  Offset of the file system on the device \n"
 	    "  --directory  -d  Directory for installation target\n",
 	    program);
-    else /* actually extlinux can also use -d to provide directory too */
+	break;
+
+    case MODE_EXTLINUX:
+	/* Mounted fs installation (extlinux) */
+	/* Actually extlinux can also use -d to provide a directory too... */
 	fprintf(stderr,
 	    "Usage: %s [options] directory\n",
 	    program);
+	break;
+    }
+
     fprintf(stderr,
 	    "  --install    -i  Install over the current bootsector\n"
 	    "  --update     -U  Update a previous EXTLINUX installation\n"
@@ -80,9 +93,10 @@ void __attribute__ ((noreturn)) usage(int rv, int mode)
 	    "  --heads=#    -H  Force number of heads\n"
 	    "  --stupid     -s  Slow, safe and stupid mode\n"
 	    "  --raid       -r  Fall back to the next device on boot failure\n"
-	    "  --once=...   -o  Execute a command once upon boot\n"
+	    "  --once=...   %s  Execute a command once upon boot\n"
 	    "  --clear-once -O  Clear the boot-once command\n"
 	    "  --reset-adv      Reset auxilliary data\n"
+	    "  --menu-save= -M  Set the label to select as default on the next boot\n"
 	    "\n"
 	    "  Note: geometry is determined at boot time for devices which\n"
 	    "  are considered hard disks by the BIOS.  Unfortunately, this is\n"
@@ -90,13 +104,13 @@ void __attribute__ ((noreturn)) usage(int rv, int mode)
 	    "  which includes zipdisks and LS-120 superfloppies.\n"
 	    "\n"
 	    "  The -z option is useful for USB devices which are considered\n"
-	    "  hard disks by some BIOSes and zipdrives by other BIOSes.\n"
-	    );
+	    "  hard disks by some BIOSes and zipdrives by other BIOSes.\n",
+	    mode == MODE_SYSLINUX ? "  " : "-o");
 
     exit(rv);
 }
 
-void parse_options(int argc, char *argv[], int mode)
+void parse_options(int argc, char *argv[], enum syslinux_mode mode)
 {
     int o;
 
@@ -104,6 +118,8 @@ void parse_options(int argc, char *argv[], int mode)
     while ((o = getopt_long(argc, argv, short_options,
 			    long_options, NULL)) != EOF) {
 	switch (o) {
+	case 'f':
+	    break;
 	case 'z':
 	    opt.heads = 64;
 	    opt.sectors = 32;
@@ -143,29 +159,79 @@ void parse_options(int argc, char *argv[], int mode)
 	    usage(0, mode);
 	    break;
 	case 'o':
+	    if (mode == MODE_SYSLINUX) {
+		fprintf(stderr,	"%s: -o will change meaning in a future version, use -t or --offset\n", program);
+		goto opt_offset;
+	    }
+	    /* else fall through */
+	case OPT_ONCE:
 	    opt.set_once = optarg;
 	    break;
-	case 'f':
+	case 't':
+	opt_offset:
 	    opt.offset = strtoul(optarg, NULL, 0);
+	    break;
 	case 'O':
 	    opt.set_once = "";
 	    break;
 	case 'd':
 	    opt.directory = optarg;
+	    break;
 	case OPT_RESET_ADV:
 	    opt.reset_adv = 1;
 	    break;
+	case 'M':
+	    opt.menu_save = optarg;
+	    break;
 	case 'v':
-	    fputs(program, stderr);
-	    fputs(" " VERSION_STR
-		  "  Copyright 1994-" YEAR_STR " H. Peter Anvin \n", stderr);
+	    fprintf(stderr,
+		    "%s " VERSION_STR "  Copyright 1994-" YEAR_STR
+		    " H. Peter Anvin et al\n", program);
 	    exit(0);
 	default:
+	    fprintf(stderr, "%s: Unknown option: -%c\n", program, optopt);
 	    usage(EX_USAGE, mode);
 	}
     }
-    if (mode)
-	opt.device = argv[optind];
-    else if (!opt.directory)
-	opt.directory = argv[optind];
+
+    switch (mode) {
+    case MODE_SYSLINUX:
+	opt.device = argv[optind++];
+	break;
+    case MODE_EXTLINUX:
+	if (!opt.directory)
+	    opt.directory = argv[optind++];
+	break;
+    }
+
+    if (argv[optind])
+	usage(EX_USAGE, mode);	/* Excess arguments */
+}
+
+/*
+ * Make any user-specified ADV modifications in memory
+ */
+int modify_adv(void)
+{
+    int rv = 0;
+
+    if (opt.reset_adv)
+	syslinux_reset_adv(syslinux_adv);
+
+    if (opt.set_once) {
+	if (syslinux_setadv(ADV_BOOTONCE, strlen(opt.set_once), opt.set_once)) {
+	    fprintf(stderr, "%s: not enough space for boot-once command\n",
+		    program);
+	    rv = -1;
+	}
+    }
+    if (opt.menu_save) {
+        if (syslinux_setadv(ADV_MENUSAVE, strlen(opt.menu_save), opt.menu_save)) {
+	    fprintf(stderr, "%s: not enough space for menu-save label\n",
+		    program);
+	    rv = -1;
+        }
+    }
+
+    return rv;
 }
diff --git a/libinstaller/syslxopt.h b/libinstaller/syslxopt.h
index d925fa3..446ab9a 100644
--- a/libinstaller/syslxopt.h
+++ b/libinstaller/syslxopt.h
@@ -13,15 +13,23 @@ struct sys_options {
     const char *directory;
     const char *device;
     unsigned int offset;
+    const char *menu_save;
 };
 
 enum long_only_opt {
     OPT_NONE,
     OPT_RESET_ADV,
+    OPT_ONCE,
 };
 
-void __attribute__ ((noreturn)) usage(int rv, int mode);
-void parse_options(int argc, char *argv[], int mode);
+enum syslinux_mode {
+    MODE_SYSLINUX,		/* Unmounted filesystem */
+    MODE_EXTLINUX,
+};
+
+void __attribute__ ((noreturn)) usage(int rv, enum syslinux_mode mode);
+void parse_options(int argc, char *argv[], enum syslinux_mode mode);
+int modify_adv(void);
 
 extern struct sys_options opt;
 extern const struct option long_options[];
diff --git a/linux/Makefile b/linux/Makefile
index 9bf56d1..ffe2272 100644
--- a/linux/Makefile
+++ b/linux/Makefile
@@ -17,15 +17,17 @@
 topdir = ..
 include $(topdir)/MCONFIG
 
-OPTFLAGS = -g -Os
+OPTFLAGS = -g -O0 -Dalloca=malloc
 INCLUDES = -I. -I.. -I../libinstaller
 CFLAGS	 = $(GCCWARN) -D_FILE_OFFSET_BITS=64 $(OPTFLAGS) $(INCLUDES)
-LDFLAGS	 = -s
+LDFLAGS	 = 
 
 SRCS     = syslinux.c \
 	   ../libinstaller/syslxopt.c \
 	   ../libinstaller/syslxcom.c \
 	   ../libinstaller/setadv.c \
+	   ../libinstaller/advio.c \
+           ../libinstaller/fat.c \
            ../libinstaller/syslxmod.c \
 	   ../libinstaller/bootsect_bin.c \
 	   ../libinstaller/ldlinux_bin.c
diff --git a/linux/syslinux.c b/linux/syslinux.c
index 3032edc..9462138 100644
--- a/linux/syslinux.c
+++ b/linux/syslinux.c
@@ -1,6 +1,7 @@
 /* ----------------------------------------------------------------------- *
  *
  *   Copyright 1998-2008 H. Peter Anvin - All Rights Reserved
+ *   Copyright 2009-2010 Intel Corporation; author: H. Peter Anvin
  *
  *   This program is free software; you can redistribute it and/or modify
  *   it under the terms of the GNU General Public License as published by
@@ -46,14 +47,7 @@
 #include <sys/wait.h>
 #include <sys/mount.h>
 
-#include <sys/ioctl.h>
-#include <linux/fs.h>		/* FIGETBSZ, FIBMAP */
-#include <linux/msdos_fs.h>	/* FAT_IOCTL_SET_ATTRIBUTES */
-#ifndef FAT_IOCTL_SET_ATTRIBUTES
-# define FAT_IOCTL_SET_ATTRIBUTES _IOW('r', 0x11, uint32_t)
-#endif
-#undef SECTOR_SIZE
-#undef SECTOR_SHIFT
+#include "linuxioctl.h"
 
 #include <paths.h>
 #ifndef _PATH_MOUNT
@@ -83,12 +77,6 @@ extern const char *program;	/* Name of program */
 pid_t mypid;
 char *mntpath = NULL;		/* Path on which to mount */
 
-/*
- * Image file
- */
-#define boot_image	syslinux_ldlinux
-#define boot_image_len  syslinux_ldlinux_len
-
 #if DO_DIRECT_MOUNT
 int loop_fd = -1;		/* Loop device */
 #endif
@@ -231,24 +219,6 @@ void do_umount(const char *mntpath, int cookie)
 }
 
 /*
- * Make any user-specified ADV modifications
- */
-int modify_adv(void)
-{
-    int rv = 0;
-
-    if (opt.set_once) {
-	if (syslinux_setadv(ADV_BOOTONCE, strlen(opt.set_once), opt.set_once)) {
-	    fprintf(stderr, "%s: not enough space for boot-once command\n",
-		    program);
-	    rv = -1;
-	}
-    }
-
-    return rv;
-}
-
-/*
  * Modify the ADV of an existing installation
  */
 int modify_existing_adv(const char *path)
@@ -276,8 +246,8 @@ int main(int argc, char *argv[])
     char mntname[128];
     char *ldlinux_name;
     char *ldlinux_path;
-    const char *subdir;
-    uint32_t *sectors = NULL;
+    char *subdir;
+    sector_t *sectors = NULL;
     int ldlinux_sectors = (boot_image_len + SECTOR_SIZE - 1) >> SECTOR_SHIFT;
     const char *errmsg;
     int mnt_cookie;
@@ -286,12 +256,25 @@ int main(int argc, char *argv[])
 
     mypid = getpid();
     umask(077);
-    parse_options(argc, argv, 1);
-
-    subdir = opt.directory;
+    parse_options(argc, argv, MODE_SYSLINUX);
+
+    /* Note: subdir is guaranteed to start and end in / */
+    if (opt.directory && opt.directory[0]) {
+	int len = strlen(opt.directory);
+	int rv = asprintf(&subdir, "%s%s%s",
+			  opt.directory[0] == '/' ? "" : "/",
+			  opt.directory,
+			  opt.directory[len-1] == '/' ? "" : "/");
+	if (rv < 0 || !subdir) {
+	    perror(program);
+	    exit(1);
+	}
+    } else {
+	subdir = "/";
+    }
 
     if (!opt.device)
-	usage(EX_USAGE, 1);
+	usage(EX_USAGE, MODE_SYSLINUX);
 
     /*
      * First make sure we can open the device at all, and that we have
@@ -337,7 +320,8 @@ int main(int argc, char *argv[])
 	   Make a temp dir and pass all the gunky options to mount. */
 
 	if (chdir(_PATH_TMP)) {
-	    perror(program);
+	    fprintf(stderr, "%s: Cannot access the %s directory.\n",
+		    program, _PATH_TMP);
 	    exit(1);
 	}
 #define TMP_MODE (S_IXUSR|S_IWUSR|S_IXGRP|S_IWGRP|S_IWOTH|S_IXOTH|S_ISVTX)
@@ -379,9 +363,8 @@ int main(int argc, char *argv[])
 	die("mount failed");
     }
 
-    ldlinux_path = alloca(strlen(mntpath) +  (subdir ? strlen(subdir) + 2 : 0));
-    sprintf(ldlinux_path, "%s%s%s",
-	    mntpath, subdir ? "//" : "", subdir ? subdir : "");
+    ldlinux_path = alloca(strlen(mntpath) + strlen(subdir) + 1);
+    sprintf(ldlinux_path, "%s%s", mntpath, subdir);
 
     ldlinux_name = alloca(strlen(ldlinux_path) + 14);
     if (!ldlinux_name) {
@@ -389,7 +372,7 @@ int main(int argc, char *argv[])
 	err = 1;
 	goto umount;
     }
-    sprintf(ldlinux_name, "%s//ldlinux.sys", ldlinux_path);
+    sprintf(ldlinux_name, "%sldlinux.sys", ldlinux_path);
 
     /* update ADV only ? */
     if (opt.update_only == -1) {
@@ -399,8 +382,10 @@ int main(int argc, char *argv[])
 	    sync();
 	    rmdir(mntpath);
 	    exit(0);
-	} else
-	    usage(EX_USAGE, 0);
+	} else {
+	    fprintf(stderr, "%s: please specify --install or --update for the future\n", argv[0]);
+	    opt.update_only = 0;
+	}
     }
 
     /* Read a pre-existing ADV, if already installed */
@@ -465,7 +450,8 @@ umount:
     /*
      * Patch ldlinux.sys and the boot sector
      */
-    i = syslinux_patch(sectors, ldlinux_sectors, opt.stupid_mode, opt.raid_mode);
+    i = syslinux_patch(sectors, ldlinux_sectors, opt.stupid_mode,
+		       opt.raid_mode, subdir, NULL);
     patch_sectors = (i + SECTOR_SIZE - 1) >> SECTOR_SHIFT;
 
     /*
diff --git a/man/extlinux.1 b/man/extlinux.1
index 426eeb3..3192122 100644
--- a/man/extlinux.1
+++ b/man/extlinux.1
@@ -28,6 +28,9 @@ Clear the boot-once command.
 \fB\-o\fR, \fB\-\-once\fR=\fIcommand\fR
 Execute a command once upon boot.
 .TP
+\fB\-M\fR, \fB\-\-menu\-save\fR=\fIlabel\fR
+Set the label to select as default on the next boot
+.TP
 \fB\-r\fR, \fB\-\-raid\fR
 Fall back to the next device on boot failure.
 .TP
@@ -42,6 +45,8 @@ Updates a previous \fBEXTLINUX\fP installation.
 .TP
 \fB\-z\fR, \fB\-\-zip\fR
 Force zipdrive geometry (-H 64 -S 32).
+.SH FILES
+The extlinux configuration file needs to be named extlinux.conf and needs to be stored in the extlinux installation directory. For more information about the contents of extlinux.conf, see syslinux(1) manpage, section files.
 .SH BUGS
 I would appreciate hearing of any problems you have with \s-1SYSLINUX\s+1.  I
 would also like to hear from you if you have successfully used \s-1SYSLINUX\s+1,
diff --git a/man/syslinux.1 b/man/syslinux.1
index 70d44d1..1729ddd 100644
--- a/man/syslinux.1
+++ b/man/syslinux.1
@@ -76,10 +76,16 @@ with a hash mark (#) are ignored.
 Sets the default command line. If \fBsyslinux\fP boots automatically, it will act
 just as if the entries after "default" had been typed in at the "boot:" prompt.
 .IP
-If no configuration file is present, or no "default" entry is present in the
-configuration file, the default is "linux auto".
+If no DEFAULT or UI statement is found, or the configuration file is missing
+entirely, \s-1SYSLINUX\s+1 drops to the boot: prompt with an error message (if
+NOESCAPE is set, it stops with a "boot failed" message; this is also the case
+for PXELINUX if the configuration file is not found.)
 .TP
-NOTE: Earlier versions of \s-1SYSLINUX\s+1 used to automatically
+NOTE: Until \s-1SYSLINUX\s+1 3.85, if no configuration file is present, or no
+"default" entry is present in the configuration file, the default is
+"linux auto".
+.TP
+Even earlier versions of \s-1SYSLINUX\s+1 used to automatically
 append the string "auto" to whatever the user specified using
 the DEFAULT command.  As of version 1.54, this is no longer
 true, as it caused problems when using a shell as a substitute
diff --git a/mbr/checksize.pl b/mbr/checksize.pl
index c1984db..4b42327 100755
--- a/mbr/checksize.pl
+++ b/mbr/checksize.pl
@@ -26,7 +26,7 @@ if (!defined($maxsize)) {
     if ($file =~ /^mbr[^0-9a-z]/) {
 	$maxsize = $padsize = 440;
     } elsif ($file =~ /^gptmbr[^0-9a-z]/) {
-	$maxsize = $padsize = 424;
+	$maxsize = $padsize = 440;
     } elsif ($file =~ /^isohdp[fp]x[^0-9a-z]/) {
 	$maxsize = $padsize = 432;
     } elsif ($file =~ /^altmbr[^0-9a-z]/) {
diff --git a/mbr/gptmbr.S b/mbr/gptmbr.S
index 8d42e8b..8ed4cf4 100644
--- a/mbr/gptmbr.S
+++ b/mbr/gptmbr.S
@@ -1,7 +1,7 @@
 /* -----------------------------------------------------------------------
  *
  *   Copyright 2007-2009 H. Peter Anvin - All Rights Reserved
- *   Copyright 2009 Intel Corporation; author: H. Peter Anvin
+ *   Copyright 2009-2010 Intel Corporation; author: H. Peter Anvin
  *
  *   Permission is hereby granted, free of charge, to any person
  *   obtaining a copy of this software and associated documentation
@@ -40,8 +40,6 @@ phdr		= stack		/* Above the stack, overwritten by bootsect */
 /* To handle > 32K we need to play segment tricks... */
 psec		= _phdr + 512
 
-/* BootGUID */
-bootguid	= _start + 0x1a8
 /* Where we put DS:SI */
 dssi_out	= _start + 0x1be
 
@@ -148,24 +146,37 @@ get_ptab:
 	loopw	get_ptab
 
 	/* Find the boot partition */
-	popw	%si			/* Partition table in memory */
+	xorw	%si,%si			/* Nothing found yet */
+	popw	%di			/* Partition table in memory */
 	popw	%cx			/* NumberOfPartitionEntries */
 	popw	%ax			/* SizeOfPartitionEntry */
+
 find_part:
-	pushw	%cx
-	pushw	%si
-	addw	$16,%si
-	movw	$bootguid,%di
-	movw	$8,%cx
-	repe; cmpsw
-	popw	%si
-	popw	%cx
-	je found_part
-	addw	%ax,%si
+	/* If the PartitionTypeGUID is all zero, it's an empty slot */
+	movl	  (%di),%edx
+	orl	 4(%di),%edx
+	orl	 8(%di),%edx
+	orl	12(%di),%edx
+	jz	not_this
+	testb	$0x04,48(%di)
+	jz	not_this
+	andw	%si,%si
+	jnz	found_multiple
+	movw	%di,%si
+not_this:
+	addw	%ax,%di
 	loopw	find_part
 
+	andw	%si,%si
+	jnz	found_part
+
+missing_os:
+	call	error
+	.ascii	"Missing OS\r\n"
+
+found_multiple:
 	call	error
-	.ascii	"Boot partition not found\r\n"
+	.ascii	"Multiple active partitions\r\n"
 
 found_part:
 	xchgw	%ax,%cx		/* Set up %cx for rep movsb further down */
@@ -178,19 +189,22 @@ found_part:
 	xorl	%eax,%eax
 	movb	$0x80,%al
 	stosl
-	movb	$0xee,%al
+	movb	$0xed,%al
 	stosl
 	movl	32(%si),%eax
 	movl	36(%si),%edx
 	call	saturate_stosl		/* Partition start */
 
 	movl	40(%si),%eax
-	movl	48(%si),%edx
+	movl	44(%si),%edx
 	subl	32(%si),%eax
 	sbbl	36(%si),%edx
 	call	inc64
 	call	saturate_stosl		/* Partition length */
 
+	movzwl	%cx,%eax		/* Length of GPT entry */
+	stosl
+	
 	rep; movsb			/* GPT entry follows MBR entry */
 	popw	%si
 
@@ -200,8 +214,8 @@ found_part:
  * is phdr == 0x7c00 == the address of the boot sector.
  */
 boot:
-	movl	(32+16)(%si),%eax
-	movl	(36+16)(%si),%edx
+	movl	(32+20)(%si),%eax
+	movl	(36+20)(%si),%edx
 	popw	%bx
 	call	read_sector
 	cmpw	$0xaa55, -2(%bx)
@@ -214,19 +228,20 @@ boot:
 	cli
 	jmpw	*%sp		/* %sp == bootsec */
 
-missing_os:
-	call	error
-	.ascii	"OS not bootable\r\n"
-
+/*
+ * Store the value in %eax to %di iff %edx == 0, otherwise store -1.
+ * Returns the value that was actually written in %eax.
+ */
 saturate_stosl:
-	pushl	%eax
 	andl	%edx,%edx
 	jz 1f
 	orl	$-1,%eax
 1:	stosl
-	popl	%eax
 	ret
 
+/*
+ * Increment %edx:%eax
+ */
 inc64:
 	addl	$1,%eax
 	adcl	$0,%edx
diff --git a/mbr/isohdpfx.S b/mbr/isohdpfx.S
index 801115c..0bf807e 100644
--- a/mbr/isohdpfx.S
+++ b/mbr/isohdpfx.S
@@ -81,14 +81,16 @@ _start:
 	jz	1f
 	testb	$0x7f, (%si)		/* Invalid active flag field? */
 	jnz	1f
+	cmpb	%cl, 4(%si)		/* Partition type zero == invalid? */
+	je	1f
 	cmpl	$0x58504721, %eax	/* !GPT signature in EAX? */
 	jne	2f
-	cmpb	$0xee, 4(%si)		/* EFI partition type? */
+	cmpb	$0xed, 4(%si)		/* EFI partition type? */
 	jne	2f
 	
 	/* We have GPT partition information */
-	movl	(32+16)(%si), %ecx
-	movl	(36+16)(%si), %ebx
+	movl	(32+20)(%si), %ecx
+	movl	(36+20)(%si), %ebx
 	jmp	1f
 
 	/* We have non-GPT partition information */
diff --git a/memdisk/Makefile b/memdisk/Makefile
index 2e6330f..d2f20c5 100644
--- a/memdisk/Makefile
+++ b/memdisk/Makefile
@@ -16,7 +16,7 @@ include $(topdir)/MCONFIG.embedded
 -include $(topdir)/version.mk
 
 INCLUDES = -I$(topdir)/com32/include
-CFLAGS  += -DDATE='"$(DATE)"'
+CFLAGS  += -D__MEMDISK__ -DDATE='"$(DATE)"'
 LDFLAGS  = $(GCCOPT) -g
 NASM     = nasm
 NASMOPT  = -O9999
diff --git a/memdisk/acpi.h b/memdisk/acpi.h
index 630c5f5..732d116 100644
--- a/memdisk/acpi.h
+++ b/memdisk/acpi.h
@@ -31,6 +31,7 @@
  * This is the structure common to the start of all ACPI system
  * description tables.
  */
+MEMDISK_PACKED_PREFIX
 struct acpi_description_header {
 	/** ACPI signature (4 ASCII characters) */
 	char signature[4];
@@ -50,5 +51,5 @@ struct acpi_description_header {
 	char asl_compiler_id[4];
 	/** ASL compiler revision number */
 	uint32_t asl_compiler_revision;
-} __attribute__ (( packed ));
+} MEMDISK_PACKED_POSTFIX;
 
diff --git a/memdisk/eltorito.h b/memdisk/eltorito.h
index 7d46e1d..494c4a1 100644
--- a/memdisk/eltorito.h
+++ b/memdisk/eltorito.h
@@ -1,6 +1,6 @@
 /* ----------------------------------------------------------------------- *
  *
- *   Copyright 2009 Shao Miller - All Rights Reserved
+ *   Copyright 2009-2010 Shao Miller - All Rights Reserved
  *
  *   This program is free software; you can redistribute it and/or modify
  *   it under the terms of the GNU General Public License as published by
@@ -17,18 +17,10 @@
  */
 
 #include <stdint.h>
-
-/*
- * Uncomment for El Torito debugging
- *
- * #define DBG_ELTORITO 1
- */
-
-#ifdef DBG_ELTORITO
-extern void eltorito_dump(uint32_t);
-#endif
+#include "compiler.h"
 
 /* EDD-4 Bootable Optical Disc Drive Boot Volume Descriptor */
+MEMDISK_PACKED_PREFIX
 struct edd4_bvd {
     uint8_t boot_rec_ind;	/* Boot Record Indicator */
     uint8_t iso9660_id[5];	/* ISO9660 ID            */
@@ -37,8 +29,9 @@ struct edd4_bvd {
     uint8_t res1[32];		/* Reserved              */
     uint32_t boot_cat;		/* Boot catalog sector   */
     uint8_t res2[1973];		/* Reserved              */
-} __attribute__ ((packed));
+} MEMDISK_PACKED_POSTFIX;
 
+MEMDISK_PACKED_PREFIX
 struct validation_entry {
     uint8_t header_id;		/* Header ID                      */
     uint8_t platform_id;	/* Platform ID                    */
@@ -47,8 +40,9 @@ struct validation_entry {
     uint16_t checksum;		/* Sums with whole record to zero */
     uint8_t key55;		/* Key byte 0x55                  */
     uint8_t keyAA;		/* Key byte 0xAA                  */
-} __attribute__ ((packed));
+} MEMDISK_PACKED_POSTFIX;
 
+MEMDISK_PACKED_PREFIX
 struct initial_entry {
     uint8_t header_id;		/* Header ID                */
     uint8_t media_type;		/* Media type               */
@@ -58,15 +52,17 @@ struct initial_entry {
     uint16_t sect_count;	/* Emulated sectors to load */
     uint32_t load_block;	/* Starting sector of image */
     uint8_t res2[4];		/* Reserved                 */
-} __attribute__ ((packed));
+} MEMDISK_PACKED_POSTFIX;
 
 /* EDD-4 Bootable Optical Disc Drive Boot Catalog (fixed-size portions) */
+MEMDISK_PACKED_PREFIX
 struct edd4_bootcat {
     struct validation_entry validation_entry;
     struct initial_entry initial_entry;
-} __attribute__ ((packed));
+} MEMDISK_PACKED_POSTFIX;
 
 /* EDD-4 CD Specification Packet */
+MEMDISK_PACKED_PREFIX
 struct edd4_cd_pkt {
     uint8_t size;		/* Packet size                     */
     uint8_t type;		/* Boot media type (flags)         */
@@ -80,4 +76,5 @@ struct edd4_cd_pkt {
     uint8_t geom1;		/* Cylinders bits 0 thru 7         */
     uint8_t geom2;		/* Sects/track 0 thru 5, cyls 8, 9 */
     uint8_t geom3;		/* Heads                           */
-} __attribute__ ((packed));
+} MEMDISK_PACKED_POSTFIX;
+
diff --git a/memdisk/memdisk.inc b/memdisk/memdisk.inc
index e1a0901..91040ba 100644
--- a/memdisk/memdisk.inc
+++ b/memdisk/memdisk.inc
@@ -119,7 +119,7 @@
 		; must be first in the binary
 Pointers:	dw Int13Start
 		dw Int15Start
-		dw PatchArea
+		dw MemDisk_Info		; Portions are patched by installer
 		dw TotalSize
 		dw IretPtr
 
@@ -616,7 +616,12 @@ ElToritoTerminate:
 		mov ax,[cs:SavedAX]
 		cmp al,1		; We only support query, not terminate
 		jne ElToritoErr		; Fail
-		mov es,P_DS		; Caller's DS:SI pointed to packet
+		cmp dl,7fh		; Terminate all?
+		je .doit
+		cmp dl,[cs:DriveNo]	; Terminate our drive?
+		je .doit
+		jmp ElToritoErr		; Fail
+.doit:		mov es,P_DS		; Caller's DS:SI pointed to packet
 		mov di,P_SI		; We'll use ES:DI
 		mov si,CD_PKT.size	; First byte is packet size
 		xor cx,0		; Empty our count
@@ -1076,12 +1081,11 @@ mBFT:
 
 ; Note that the above ends on a DWORD boundary.
 ; The MDI has always started at such a boundary.
+; Portions of the MDI are patched by the installer
 MemDisk_Info	equ $			; Pointed to by installation check
 MDI_Bytes	dw MDI_Len		; Total bytes in MDI structure
 MDI_Version	db VERSION_MINOR, VERSION_MAJOR	; MEMDISK version
 
-PatchArea	equ $			; This gets filled in by the installer
-
 DiskBuf		dd 0			; Linear address of high memory disk
 DiskSize	dd 0			; Size of disk in blocks
 CommandLine	dw 0, 0			; Far pointer to saved command line
@@ -1171,7 +1175,8 @@ CD_PKT:
 
 %endif ; EDD
 
-		; End patch area
+; End patch area
+
 		alignb 4, db 0
 Stack		dd 0			; Saved SS:ESP on invocation
 		dw 0
diff --git a/memdisk/setup.c b/memdisk/setup.c
index db1c4bc..3f69cd3 100644
--- a/memdisk/setup.c
+++ b/memdisk/setup.c
@@ -14,11 +14,9 @@
  * ----------------------------------------------------------------------- */
 
 #include <stdint.h>
-#include "acpi.h"
 #include "bda.h"
 #include "dskprobe.h"
 #include "e820.h"
-#include "eltorito.h"
 #include "conio.h"
 #include "version.h"
 #include "memdisk.h"
@@ -41,131 +39,8 @@ extern const char _binary_memdisk_iso_2048_bin_start[];
 extern const char _binary_memdisk_iso_2048_bin_end[];
 extern const char _binary_memdisk_iso_2048_bin_size[];
 
-struct memdisk_header {
-    uint16_t int13_offs;
-    uint16_t int15_offs;
-    uint16_t patch_offs;
-    uint16_t total_size;
-    uint16_t iret_offs;
-};
-
-struct safe_hook {
-    uint8_t jump[3];		/* Max. three bytes for jump */
-    uint8_t signature[8];	/* "$INT13SF" */
-    uint8_t vendor[8];		/* "MEMDISK " */
-    uint32_t old_hook;		/* SEG:OFF for previous INT 13h hook */
-    uint32_t flags;		/* "Safe hook" flags */
-    /* The next field is a MEMDISK extension to the "safe hook" structure */
-    uint32_t mBFT;		/* Offset from hook to the mBFT; refilled
-				 * by setup() with the physical address
-				 */
-} __attribute__((packed));
-
-/* The Disk Parameter Table may be required */
-typedef union {
-    struct hd_dpt {
-	uint16_t max_cyl;	/* Max cylinder */
-	uint8_t max_head;	/* Max head */
-	uint8_t junk1[5];	/* Obsolete junk, leave at zero */
-	uint8_t ctrl;		/* Control byte */
-	uint8_t junk2[7];	/* More obsolete junk */
-    } hd;
-    struct fd_dpt {
-	uint8_t specify1;	/* "First specify byte" */
-	uint8_t specify2;	/* "Second specify byte" */
-	uint8_t delay;		/* Delay until motor turn off */
-	uint8_t sectors;	/* Sectors/track */
-
-	uint8_t bps;		/* Bytes/sector (02h = 512) */
-	uint8_t isgap;		/* Length of intersector gap */
-	uint8_t dlen;		/* Data length (0FFh) */
-	uint8_t fgap;		/* Formatting gap */
-
-	uint8_t ffill;		/* Format fill byte */
-	uint8_t settle;		/* Head settle time (ms) */
-	uint8_t mstart;		/* Motor start time */
-	uint8_t maxtrack;	/* Maximum track number */
-
-	uint8_t rate;		/* Data transfer rate */
-	uint8_t cmos;		/* CMOS type */
-	uint8_t pad[2];
-
-	uint32_t old_fd_dpt;	/* Extension: pointer to old INT 1Eh */
-    } fd;
-} dpt_t;
-
-/* EDD disk parameter table */
-struct edd_dpt {
-    uint16_t len;		/* Length of table */
-    uint16_t flags;		/* Information flags */
-    uint32_t c;			/* Physical cylinders (count!) */
-    uint32_t h;			/* Physical heads (count!) */
-    uint32_t s;			/* Physical sectors/track (count!) */
-    uint64_t sectors;		/* Total sectors */
-    uint16_t bytespersec;	/* Bytes/sector */
-    uint16_t dpte_off, dpte_seg;	/* DPTE pointer */
-    uint16_t dpikey;		/* Device Path Info magic */
-    uint8_t  dpilen;		/* Device Path Info length */
-    uint8_t  res1;		/* Reserved */
-    uint16_t res2;		/* Reserved */
-    uint8_t  bustype[4];	/* Host bus type */
-    uint8_t  inttype[8];	/* Interface type */
-    uint64_t intpath;		/* Interface path */
-    uint64_t devpath[2];	/* Device path (double QuadWord!) */
-    uint8_t  res3;		/* Reserved */
-    uint8_t  chksum;		/* DPI checksum */
-} __attribute__((packed));
-
-struct mBFT {
-    struct acpi_description_header acpi;
-    uint32_t safe_hook;		/* "Safe hook" physical address */
-} __attribute__((packed));
-
-struct patch_area {
-    uint32_t diskbuf;
-    uint32_t disksize;
-    uint16_t cmdline_off, cmdline_seg;
-
-    uint32_t oldint13;
-    uint32_t oldint15;
-
-    uint16_t olddosmem;
-    uint8_t bootloaderid;
-    uint8_t _pad1;
-
-    uint16_t dpt_ptr;
-    /* End of the official MemDisk_Info */
-    uint8_t driveshiftlimit;	/* Do not shift drives above this region */
-    uint8_t _pad2;		/* Pad to DWORD */
-    uint16_t _pad3;		/* Pad to QWORD */
-
-    uint16_t memint1588;
-
-    uint16_t cylinders;
-    uint16_t heads;
-    uint32_t sectors;
-
-    uint32_t mem1mb;
-    uint32_t mem16mb;
-
-    uint8_t driveno;
-    uint8_t drivetype;
-    uint8_t drivecnt;
-    uint8_t configflags;
-
-#define CONFIG_READONLY	0x01
-#define CONFIG_RAW	0x02
-#define CONFIG_SAFEINT	0x04
-#define CONFIG_BIGRAW	0x08	/* MUST be 8! */
-#define CONFIG_MODEMASK	0x0e
-
-    uint16_t mystack;
-    uint16_t statusptr;
-
-    dpt_t dpt;
-    struct edd_dpt edd_dpt;
-    struct edd4_cd_pkt cd_pkt; /* Only really in a memdisk_iso_* hook */
-} __attribute__((packed));
+/* Pull in structures common to MEMDISK and MDISKCHK.COM */
+#include "mstructs.h"
 
 /* An EDD disk packet */
 struct edd_dsk_pkt {
@@ -177,6 +52,13 @@ struct edd_dsk_pkt {
     uint64_t buf64;		/* 64-bit buf pointer */
 } __attribute__ ((packed));
 
+/* Change to 1 for El Torito debugging */
+#define DBG_ELTORITO 0
+
+#if DBG_ELTORITO
+extern void eltorito_dump(uint32_t);
+#endif
+
 /*
  * Routine to seek for a command-line item and return a pointer
  * to the data portion, if present
@@ -360,7 +242,7 @@ struct geometry {
     uint32_t boot_lba;		/* LBA of bootstrap code */
     uint8_t type;		/* Type byte for INT 13h AH=08h */
     uint8_t driveno;		/* Drive no */
-    uint16_t sector_size;	/* Sector size in bytes (512 vs. 2048) */
+    uint8_t sector_shift;	/* Sector size as a power of 2 */
     const char *hsrc, *ssrc;	/* Origins of H and S geometries */
 };
 
@@ -440,13 +322,13 @@ static const struct geometry *get_disk_image_geometry(uint32_t where,
 
     printf("command line: %s\n", shdr->cmdline);
 
-    hd_geometry.sector_size = 512;	/* Assume floppy/HDD at first */
+    hd_geometry.sector_shift = 9;	/* Assume floppy/HDD at first */
 
     offset = 0;
     if (CMD_HASDATA(p = getcmditem("offset")) && (v = atou(p)))
 	offset = v;
 
-    sectors = xsectors = (size - offset) >> 9;
+    sectors = xsectors = (size - offset) >> hd_geometry.sector_shift;
 
     hd_geometry.hsrc = "guess";
     hd_geometry.ssrc = "guess";
@@ -454,7 +336,7 @@ static const struct geometry *get_disk_image_geometry(uint32_t where,
     hd_geometry.offset = offset;
 
     if ((p = getcmditem("iso")) != CMD_NOTFOUND) {
-#ifdef DBG_ELTORITO
+#if DBG_ELTORITO
 	eltorito_dump(where);
 #endif
 	struct edd4_bvd *bvd = (struct edd4_bvd *)(where + 17 * 2048);
@@ -490,8 +372,7 @@ static const struct geometry *get_disk_image_geometry(uint32_t where,
 	    hd_geometry.h = 255;
 	    hd_geometry.s = 15;
 	    /* 2048-byte sectors, so adjust the size and count */
-	    hd_geometry.sector_size = 2048;
-	    sectors = (size - hd_geometry.offset) >> 11;
+	    hd_geometry.sector_shift = 11;
 	    break;
 	case 1:		/* 1.2 MB floppy  */
 	    hd_geometry.s = 15;
@@ -511,9 +392,10 @@ static const struct geometry *get_disk_image_geometry(uint32_t where,
 	case 4:
 	    hd_geometry.driveno = 0x80;
 	    hd_geometry.type = 0;
-	    sectors = (size - hd_geometry.offset) >> 9;
 	    break;
 	}
+	sectors = (size - hd_geometry.offset) >> hd_geometry.sector_shift;
+
 	/* For HDD emulation, we figure out the geometry later. Otherwise: */
 	if (hd_geometry.s) {
 	    hd_geometry.hsrc = hd_geometry.ssrc = "El Torito";
@@ -531,7 +413,7 @@ static const struct geometry *get_disk_image_geometry(uint32_t where,
 	hd_geometry.h = dosemu.h;
 	hd_geometry.s = dosemu.s;
 	hd_geometry.offset += dosemu.offset;
-	sectors = (size - hd_geometry.offset) >> 9;
+	sectors = (size - hd_geometry.offset) >> hd_geometry.sector_shift;
 
 	hd_geometry.hsrc = hd_geometry.ssrc = "DOSEMU";
     }
@@ -584,7 +466,7 @@ static const struct geometry *get_disk_image_geometry(uint32_t where,
 
 	if (!(max_h | max_s)) {
 	    /* No FAT filesystem found to steal geometry from... */
-	    if ((sectors < 4096 * 2) && (hd_geometry.sector_size == 512)) {
+	    if ((sectors < 4096 * 2) && (hd_geometry.sector_shift == 9)) {
 		int ok = 0;
 		unsigned int xsectors = sectors;
 
@@ -835,8 +717,8 @@ void setup(const struct real_mode_args *rm_args_ptr)
     unsigned int bin_size;
     char *memdisk_hook;
     struct memdisk_header *hptr;
-    struct safe_hook *safe_hook;
     struct patch_area *pptr;
+    struct mBFT *mbft;
     uint16_t driverseg;
     uint32_t driverptr, driveraddr;
     uint16_t dosmem_k;
@@ -896,7 +778,7 @@ void setup(const struct real_mode_args *rm_args_ptr)
 
     /* Choose the appropriate installable memdisk hook */
     if (do_eltorito) {
-	if (geometry->sector_size == 2048) {
+	if (geometry->sector_shift == 11) {
 	    bin_size = (int)&_binary_memdisk_iso_2048_bin_size;
 	    memdisk_hook = (char *)&_binary_memdisk_iso_2048_bin_start;
 	} else {
@@ -919,11 +801,10 @@ void setup(const struct real_mode_args *rm_args_ptr)
 
     /* Figure out where it needs to go */
     hptr = (struct memdisk_header *)memdisk_hook;
-    safe_hook = (struct safe_hook *)(memdisk_hook + hptr->int13_offs);
     pptr = (struct patch_area *)(memdisk_hook + hptr->patch_offs);
 
     dosmem_k = rdz_16(BIOS_BASEMEM);
-    pptr->olddosmem = dosmem_k;
+    pptr->mdi.olddosmem = dosmem_k;
     stddosmem = dosmem_k << 10;
     /* If INT 15 E820 and INT 12 disagree, go with the most conservative */
     if (stddosmem > dos_mem)
@@ -934,11 +815,12 @@ void setup(const struct real_mode_args *rm_args_ptr)
     pptr->cylinders = geometry->c;	/* Possible precision loss */
     pptr->heads = geometry->h;
     pptr->sectors = geometry->s;
-    pptr->disksize = geometry->sectors;
-    pptr->diskbuf = ramdisk_image + geometry->offset;
+    pptr->mdi.disksize = geometry->sectors;
+    pptr->mdi.diskbuf = ramdisk_image + geometry->offset;
+    pptr->mdi.sector_shift = geometry->sector_shift;
     pptr->statusptr = (geometry->driveno & 0x80) ? 0x474 : 0x441;
 
-    pptr->bootloaderid = shdr->type_of_loader;
+    pptr->mdi.bootloaderid = shdr->type_of_loader;
 
     pptr->configflags = CONFIG_SAFEINT;	/* Default */
     /* Set config flags */
@@ -1031,7 +913,7 @@ void setup(const struct real_mode_args *rm_args_ptr)
 	     * for INT 0x13, AH=0x48 "EDD Get Disk Parameters" call on an
 	     * El Torito ODD.  Check for 2048-byte sector size
 	     */
-	    if (geometry->sector_size != 2048)
+	    if (geometry->sector_shift != 11)
 		pptr->edd_dpt.flags |= 0x0002;	/* Geometry valid */
 	}
 	if (!(geometry->driveno & 0x80)) {
@@ -1040,7 +922,7 @@ void setup(const struct real_mode_args *rm_args_ptr)
 	    pptr->edd_dpt.flags |= 0x0014;
 	}
 
-	pptr->edd_dpt.devpath[0] = pptr->diskbuf;
+	pptr->edd_dpt.devpath[0] = pptr->mdi.diskbuf;
 	pptr->edd_dpt.chksum = -checksum_buf(&pptr->edd_dpt.dpikey, 73 - 30);
     }
 
@@ -1109,8 +991,8 @@ void setup(const struct real_mode_args *rm_args_ptr)
     /* Anything beyond the end is for the stack */
     pptr->mystack = (uint16_t) (stddosmem - driveraddr);
 
-    pptr->oldint13 = rdz_32(BIOS_INT13);
-    pptr->oldint15 = rdz_32(BIOS_INT15);
+    pptr->mdi.oldint13.uint32 = rdz_32(BIOS_INT13);
+    pptr->mdi.oldint15.uint32 = rdz_32(BIOS_INT15);
 
     /* Adjust the E820 table: if there are null ranges (type 0)
        at the end, change them to type end of list (-1).
@@ -1125,7 +1007,7 @@ void setup(const struct real_mode_args *rm_args_ptr)
 	bios_drives = 0;
 	pptr->drivecnt = 0;
 	no_bpt = 1;
-	pptr->oldint13 = driverptr + hptr->iret_offs;
+	pptr->mdi.oldint13.uint32 = driverptr + hptr->iret_offs;
 	wrz_8(BIOS_EQUIP, rdz_8(BIOS_EQUIP) & ~0xc1);
 	wrz_8(BIOS_HD_COUNT, 0);
     } else if (getcmditem("nopass") != CMD_NOTFOUND) {
@@ -1173,9 +1055,6 @@ void setup(const struct real_mode_args *rm_args_ptr)
 	}
     }
 
-    /* Note the previous INT 13h hook in the "safe hook" structure */
-    safe_hook->old_hook = pptr->oldint13;
-
     /* Add ourselves to the drive count */
     pptr->drivecnt++;
 
@@ -1191,8 +1070,8 @@ void setup(const struct real_mode_args *rm_args_ptr)
 	pptr->driveshiftlimit);
 
     /* Pointer to the command line */
-    pptr->cmdline_off = bin_size + (nranges + 1) * sizeof(ranges[0]);
-    pptr->cmdline_seg = driverseg;
+    pptr->mdi.cmdline.seg_off.offset = bin_size + (nranges + 1) * sizeof(ranges[0]);
+    pptr->mdi.cmdline.seg_off.segment = driverseg;
 
     /* Copy driver followed by E820 table followed by command line */
     {
@@ -1200,7 +1079,6 @@ void setup(const struct real_mode_args *rm_args_ptr)
 
 	/* Adjust these pointers to point to the installed image */
 	/* Careful about the order here... the image isn't copied yet! */
-	safe_hook = (struct safe_hook *)(dpp + hptr->int13_offs);
 	pptr = (struct patch_area *)(dpp + hptr->patch_offs);
 	hptr = (struct memdisk_header *)dpp;
 
@@ -1210,8 +1088,12 @@ void setup(const struct real_mode_args *rm_args_ptr)
 	dpp = mempcpy(dpp, shdr->cmdline, cmdline_len);
     }
 
+    /* Note the previous INT 13h hook in the "safe hook" structure */
+    hptr->safe_hook.old_hook.uint32 = pptr->mdi.oldint13.uint32;
+
     /* Re-fill the "safe hook" mBFT field with the physical address */
-    safe_hook->mBFT += (uint32_t)hptr;
+    mbft = (struct mBFT *)(((const char *)hptr) + hptr->safe_hook.mbft);
+    hptr->safe_hook.mbft = (size_t)mbft;
 
     /* Update various BIOS magic data areas (gotta love this shit) */
 
@@ -1242,21 +1124,18 @@ void setup(const struct real_mode_args *rm_args_ptr)
 	if (getcmditem("dpt") != CMD_NOTFOUND ||
 	    ((nflop == 1 || no_bpt) && getcmditem("nodpt") == CMD_NOTFOUND)) {
 	    /* Do install a replacement DPT into INT 1Eh */
-	    pptr->dpt_ptr = hptr->patch_offs + offsetof(struct patch_area, dpt);
+	    pptr->mdi.dpt_ptr =
+		hptr->patch_offs + offsetof(struct patch_area, dpt);
 	}
     }
 
     /* Complete the mBFT */
-    {
-	struct mBFT *mBFT = (struct mBFT *)safe_hook->mBFT;
-
-	mBFT->acpi.signature[0] = 'm';	/* "mBFT" */
-	mBFT->acpi.signature[1] = 'B';
-	mBFT->acpi.signature[2] = 'F';
-	mBFT->acpi.signature[3] = 'T';
-	mBFT->safe_hook = (uint32_t)safe_hook;
-	mBFT->acpi.checksum = -checksum_buf(mBFT, mBFT->acpi.length);
-    }
+    mbft->acpi.signature[0] = 'm';	/* "mBFT" */
+    mbft->acpi.signature[1] = 'B';
+    mbft->acpi.signature[2] = 'F';
+    mbft->acpi.signature[3] = 'T';
+    mbft->safe_hook = (size_t)&hptr->safe_hook;
+    mbft->acpi.checksum = -checksum_buf(mbft, mbft->acpi.length);
 
     /* Install the interrupt handlers */
     printf("old: int13 = %08x  int15 = %08x  int1e = %08x\n",
@@ -1264,8 +1143,8 @@ void setup(const struct real_mode_args *rm_args_ptr)
 
     wrz_32(BIOS_INT13, driverptr + hptr->int13_offs);
     wrz_32(BIOS_INT15, driverptr + hptr->int15_offs);
-    if (pptr->dpt_ptr)
-	wrz_32(BIOS_INT1E, driverptr + pptr->dpt_ptr);
+    if (pptr->mdi.dpt_ptr)
+	wrz_32(BIOS_INT1E, driverptr + pptr->mdi.dpt_ptr);
 
     printf("new: int13 = %08x  int15 = %08x  int1e = %08x\n",
 	   rdz_32(BIOS_INT13), rdz_32(BIOS_INT15), rdz_32(BIOS_INT1E));
@@ -1291,7 +1170,8 @@ void setup(const struct real_mode_args *rm_args_ptr)
     /* Reboot into the new "disk" */
     puts("Loading boot sector... ");
 
-    memcpy((void *)boot_base, (char *)pptr->diskbuf + geometry->boot_lba * 512,
+    memcpy((void *)boot_base,
+	   (char *)pptr->mdi.diskbuf + geometry->boot_lba * 512,
 	   boot_len);
 
     if (getcmditem("pause") != CMD_NOTFOUND) {
@@ -1306,3 +1186,4 @@ void setup(const struct real_mode_args *rm_args_ptr)
     shdr->esdi = pnp_install_check();
     shdr->edx = geometry->driveno;
 }
+
diff --git a/mtools/Makefile b/mtools/Makefile
index 91b6852..70bed14 100644
--- a/mtools/Makefile
+++ b/mtools/Makefile
@@ -7,7 +7,9 @@ CFLAGS	 = $(GCCWARN) -D_FILE_OFFSET_BITS=64 $(OPTFLAGS) $(INCLUDES)
 LDFLAGS	 = -s
 
 SRCS     = syslinux.c \
+	   ../libinstaller/fat.c \
 	   ../libinstaller/syslxmod.c \
+	   ../libinstaller/setadv.c \
 	   ../libinstaller/bootsect_bin.c \
 	   ../libinstaller/ldlinux_bin.c \
 	   $(wildcard ../libfat/*.c)
diff --git a/mtools/syslinux.c b/mtools/syslinux.c
index 2c5387e..76cd2ca 100644
--- a/mtools/syslinux.c
+++ b/mtools/syslinux.c
@@ -1,6 +1,7 @@
 /* ----------------------------------------------------------------------- *
  *
  *   Copyright 1998-2008 H. Peter Anvin - All Rights Reserved
+ *   Copyright 2010 Intel Corporation; author: H. Peter Anvin
  *
  *   This program is free software; you can redistribute it and/or modify
  *   it under the terms of the GNU General Public License as published by
@@ -18,8 +19,7 @@
  * We need device write permission anyway.
  */
 
-#define _XOPEN_SOURCE 500	/* Required on glibc 2.x */
-#define _BSD_SOURCE
+#define _GNU_SOURCE
 #include <alloca.h>
 #include <errno.h>
 #include <fcntl.h>
@@ -37,6 +37,7 @@
 
 #include "syslinux.h"
 #include "libfat.h"
+#include "setadv.h"
 
 char *program;			/* Name of program */
 char *device;			/* Device to install to */
@@ -56,6 +57,12 @@ void __attribute__ ((noreturn)) die(const char *msg)
     exit(1);
 }
 
+void __attribute__ ((noreturn)) die_err(const char *msg)
+{
+    fprintf(stderr, "%s: %s: %s\n", program, msg, strerror(errno));
+    exit(1);
+}
+
 /*
  * read/write wrapper functions
  */
@@ -130,7 +137,8 @@ int main(int argc, char *argv[])
     struct stat st;
     int status;
     char **argp, *opt;
-    char mtools_conf[] = "/tmp/syslinux-mtools-XXXXXX";
+    const char *tmpdir;
+    char *mtools_conf;
     const char *subdir = NULL;
     int mtc_fd;
     FILE *mtc, *mtp;
@@ -187,12 +195,26 @@ int main(int argc, char *argv[])
 	usage();
 
     /*
+     * Temp directory of choice...
+     */
+    tmpdir = getenv("TMPDIR");
+    if (!tmpdir) {
+#ifdef P_tmpdir
+	tmpdir = P_tmpdir;
+#elif defined(_PATH_TMP)
+	tmpdir = _PATH_TMP;
+#else
+	tmpdir = "/tmp";
+#endif
+    }
+
+    /*
      * First make sure we can open the device at all, and that we have
      * read/write permission.
      */
     dev_fd = open(device, O_RDWR);
     if (dev_fd < 0 || fstat(dev_fd, &st) < 0) {
-	perror(device);
+	die_err(device);
 	exit(1);
     }
 
@@ -215,11 +237,14 @@ int main(int argc, char *argv[])
     /*
      * Create an mtools configuration file
      */
+    if (asprintf(&mtools_conf, "%s//syslinux-mtools-XXXXXX", tmpdir) < 0 ||
+	!mtools_conf)
+	die_err(tmpdir);
+
     mtc_fd = mkstemp(mtools_conf);
-    if (mtc_fd < 0 || !(mtc = fdopen(mtc_fd, "w"))) {
-	perror(program);
-	exit(1);
-    }
+    if (mtc_fd < 0 || !(mtc = fdopen(mtc_fd, "w")))
+	die_err(mtools_conf);
+
     fprintf(mtc,
 	    /* These are needed for some flash memories */
 	    "MTOOLS_SKIP_CHECK=1\n"
@@ -229,7 +254,8 @@ int main(int argc, char *argv[])
 	    "  offset=%llu\n",
 	    (unsigned long)mypid,
 	    dev_fd, (unsigned long long)filesystem_offset);
-    fclose(mtc);
+    if (ferror(mtc) || fclose(mtc))
+	die_err(mtools_conf);
 
     /*
      * Run mtools to create the LDLINUX.SYS file
@@ -239,12 +265,21 @@ int main(int argc, char *argv[])
 	exit(1);
     }
 
+    /*
+     * Create a vacuous ADV in memory.  This should be smarter.
+     */
+    syslinux_reset_adv(syslinux_adv);
+
     /* This command may fail legitimately */
-    system("mattrib -h -r -s s:/ldlinux.sys 2>/dev/null");
+    status = system("mattrib -h -r -s s:/ldlinux.sys 2>/dev/null");
+    (void)status;		/* Keep _FORTIFY_SOURCE happy */
 
     mtp = popen("mcopy -D o -D O -o - s:/ldlinux.sys", "w");
-    if (!mtp || (fwrite(syslinux_ldlinux, 1, syslinux_ldlinux_len, mtp)
-		 != syslinux_ldlinux_len) ||
+    if (!mtp ||
+	fwrite(syslinux_ldlinux, 1, syslinux_ldlinux_len, mtp)
+		!= syslinux_ldlinux_len ||
+	fwrite(syslinux_adv, 1, 2 * ADV_SIZE, mtp)
+		!= 2 * ADV_SIZE ||
 	(status = pclose(mtp), !WIFEXITED(status) || WEXITSTATUS(status))) {
 	die("failed to create ldlinux.sys");
     }
@@ -252,7 +287,8 @@ int main(int argc, char *argv[])
     /*
      * Now, use libfat to create a block map
      */
-    ldlinux_sectors = (syslinux_ldlinux_len + SECTOR_SIZE - 1) >> SECTOR_SHIFT;
+    ldlinux_sectors = (syslinux_ldlinux_len + 2 * ADV_SIZE
+		       + SECTOR_SIZE - 1) >> SECTOR_SHIFT;
     sectors = calloc(ldlinux_sectors, sizeof *sectors);
     fs = libfat_open(libfat_xpread, dev_fd);
     ldlinux_cluster = libfat_searchdir(fs, 0, "LDLINUX SYS", NULL);
@@ -267,7 +303,7 @@ int main(int argc, char *argv[])
     libfat_close(fs);
 
     /* Patch ldlinux.sys and the boot sector */
-    i = syslinux_patch(sectors, nsectors, stupid, raid_mode);
+    i = syslinux_patch(sectors, nsectors, stupid, raid_mode, subdir, NULL);
     patch_sectors = (i + SECTOR_SIZE - 1) >> SECTOR_SHIFT;
 
     /* Write the now-patched first sectors of ldlinux.sys */
@@ -313,7 +349,8 @@ int main(int argc, char *argv[])
 
 	/* This command may fail legitimately */
 	sprintf(command, "mattrib -h -r -s %s 2>/dev/null", target_file);
-	system(command);
+	status = system(command);
+	(void)status;		/* Keep _FORTIFY_SOURCE happy */
 
 	sprintf(command, "mmove -D o -D O s:/ldlinux.sys %s", target_file);
 	status = system(command);
diff --git a/utils/Makefile b/utils/Makefile
index 5930b99..455eb82 100644
--- a/utils/Makefile
+++ b/utils/Makefile
@@ -20,7 +20,7 @@ include $(topdir)/MCONFIG
 CFLAGS   = $(GCCWARN) -Os -fomit-frame-pointer -D_FILE_OFFSET_BITS=64
 LDFLAGS  = -O2 -s
 
-TARGETS	 = mkdiskimage isohybrid gethostip
+TARGETS	 = mkdiskimage isohybrid gethostip memdiskfind
 TARGETS += isohybrid.pl  # about to be obsoleted
 ASIS     = keytab-lilo lss16toppm md5pass ppmtolss16 sha1pass syslinux2ansi \
 	   pxelinux-options
@@ -46,12 +46,15 @@ isohybrid.pl: isohybrid.in $(ISOHDPFX) bin2hex.pl
 isohdpfx.c: $(ISOHDPFX) isohdpfxarray.pl
 	$(PERL) isohdpfxarray.pl $(ISOHDPFX) > $@
 
-isohybrid: isohybrid.c isohdpfx.c isohybrid.h
-	$(CC) $(UMAKEDEPS) $(CFLGAS) -o $@ isohybrid.c isohdpfx.c
+isohybrid: isohybrid.o isohdpfx.o
+	$(CC) $(LDFLAGS) -o $@ $^
 
 gethostip: gethostip.o
 	$(CC) $(LDFLAGS) -o $@ $^
 
+memdiskfind: memdiskfind.o
+	$(CC) $(LDFLAGS) -o $@ $^
+
 tidy dist:
 	rm -f *.o .*.d isohdpfx.c
 
diff --git a/utils/isohybrid.c b/utils/isohybrid.c
index 4e504b9..57c1015 100644
--- a/utils/isohybrid.c
+++ b/utils/isohybrid.c
@@ -401,7 +401,7 @@ display_mbr(const uint8_t *mbr, size_t len)
     unsigned char c = 0;
     unsigned int i = 0, j = 0;
 
-    printf("sizeof(MBR): %d bytes\n", len);
+    printf("sizeof(MBR): %zu bytes\n", len);
     for (i = 0; i < len; i++)
     {
         if (!(i % 16))
@@ -499,7 +499,7 @@ main(int argc, char *argv[])
     padding = (frac > 0) ? cylsize - frac : 0;
 
     if (mode & VERBOSE)
-        printf("imgsize: %lu, padding: %d\n", isostat.st_size, padding);
+        printf("imgsize: %zu, padding: %d\n", (size_t)isostat.st_size, padding);
 
     cc = c = (isostat.st_size + padding) / cylsize;
     if (c > 1024)
@@ -514,7 +514,9 @@ main(int argc, char *argv[])
         if (fseek(fp, 440, SEEK_SET))
             err(1, "%s: seek error - 4", argv[0]);
 
-        fscanf(fp, "%4c", &id);
+	if (fread(&id, 1, 4, fp) != 4)
+	    err(1, "%s: read error", argv[0]);
+
         id = lendian_int(id);
         if (!id)
         {
diff --git a/win32/Makefile b/win32/Makefile
index a0be1d4..a077b30 100644
--- a/win32/Makefile
+++ b/win32/Makefile
@@ -1,6 +1,7 @@
 ## -----------------------------------------------------------------------
 ##
 ##   Copyright 1998-2008 H. Peter Anvin - All Rights Reserved
+##   Copyright 2010 Intel Corporation; author: H. Peter Anvin
 ##
 ##   This program is free software; you can redistribute it and/or modify
 ##   it under the terms of the GNU General Public License as published by
@@ -44,13 +45,18 @@ WINCC_IS_GOOD := $(shell $(WINCC) $(WINCFLAGS) $(WINLDFLAGS) -o hello.exe hello.
 
 .SUFFIXES: .c .o .i .s .S
 
-SRCS     = syslinux.c \
+SRCS     = syslinux.c
+OBJS     = $(patsubst %.c,%.obj,$(notdir $(SRCS)))
+LIBSRC   = ../libinstaller/fat.c \
 	   ../libinstaller/syslxmod.c \
+	   ../libinstaller/setadv.c \
 	   ../libinstaller/bootsect_bin.c \
 	   ../libinstaller/ldlinux_bin.c \
 	   ../libinstaller/mbr_bin.c \
 	   $(wildcard ../libfat/*.c)
-OBJS     = $(patsubst %.c,%.o,$(notdir $(SRCS)))
+LIBOBJS  = $(patsubst %.c,%.obj,$(notdir $(LIBSRC)))
+
+LIB	 = syslinux.lib
 
 VPATH = .:../libfat:../libinstaller
 
@@ -64,7 +70,7 @@ all:
 endif
 
 tidy dist:
-	-rm -f *.o *.i *.s *.a .*.d *.tmp *_bin.c hello.exe
+	-rm -f *.o *.obj *.lib *.i *.s *.a .*.d *.tmp *_bin.c hello.exe
 
 clean: tidy
 
@@ -73,11 +79,15 @@ spotless: clean
 
 installer:
 
-syslinux.exe: $(OBJS)
+$(LIB): $(LIBOBJS)
+	$(WINAR) cq $@ $^
+	$(WINRANLIB) $@
+
+syslinux.exe: $(OBJS) $(LIB)
 	$(WINCC) $(WINLDFLAGS) -o $@ $^
 
 
-%.o: %.c
+%.obj: %.c
 	$(WINCC) $(UMAKEDEPS) $(WINCFLAGS) -c -o $@ $<
 %.i: %.c
 	$(WINCC) $(UMAKEDEPS) $(WINCFLAGS) -E -o $@ $<
diff --git a/win32/syslinux.c b/win32/syslinux.c
index d8c6c82..ca98d78 100644
--- a/win32/syslinux.c
+++ b/win32/syslinux.c
@@ -23,6 +23,7 @@
 
 #include "syslinux.h"
 #include "libfat.h"
+#include "setadv.h"
 
 #ifdef __GNUC__
 # define noreturn void __attribute__((noreturn))
@@ -384,6 +385,9 @@ int main(int argc, char *argv[])
     /* Just ignore error if the file do not exists */
     DeleteFile(ldlinux_name);
 
+    /* Initialize the ADV -- this should be smarter */
+    syslinux_reset_adv(syslinux_adv);
+
     /* Create ldlinux.sys file */
     f_handle = CreateFile(ldlinux_name, GENERIC_READ | GENERIC_WRITE,
 			  FILE_SHARE_READ | FILE_SHARE_WRITE,
@@ -397,15 +401,16 @@ int main(int argc, char *argv[])
     }
 
     /* Write ldlinux.sys file */
-    if (!WriteFile
-	(f_handle, syslinux_ldlinux, syslinux_ldlinux_len, &bytes_written,
-	 NULL)) {
+    if (!WriteFile(f_handle, syslinux_ldlinux, syslinux_ldlinux_len,
+		   &bytes_written, NULL) ||
+	bytes_written != syslinux_ldlinux_len) {
 	error("Could not write ldlinux.sys");
 	exit(1);
     }
-
-    if (bytes_written != syslinux_ldlinux_len) {
-	fprintf(stderr, "Could not write whole ldlinux.sys\n");
+    if (!WriteFile(f_handle, syslinux_adv, 2 * ADV_SIZE,
+		   &bytes_written, NULL) ||
+	bytes_written != 2 * ADV_SIZE) {
+	error("Could not write ADV to ldlinux.sys");
 	exit(1);
     }
 
@@ -416,7 +421,8 @@ int main(int argc, char *argv[])
     }
 
     /* Map the file (is there a better way to do this?) */
-    ldlinux_sectors = (syslinux_ldlinux_len + SECTOR_SIZE - 1) >> SECTOR_SHIFT;
+    ldlinux_sectors = (syslinux_ldlinux_len + 2 * ADV_SIZE + SECTOR_SIZE - 1)
+	>> SECTOR_SHIFT;
     sectors = calloc(ldlinux_sectors, sizeof *sectors);
     fs = libfat_open(libfat_readfile, (intptr_t) d_handle);
     ldlinux_cluster = libfat_searchdir(fs, 0, "LDLINUX SYS", NULL);
@@ -433,7 +439,7 @@ int main(int argc, char *argv[])
     /*
      * Patch ldlinux.sys and the boot sector
      */
-    syslinux_patch(sectors, nsectors, stupid, raid_mode);
+    syslinux_patch(sectors, nsectors, stupid, raid_mode, subdir, NULL);
 
     /*
      * Rewrite the file



More information about the Syslinux-commits mailing list