Commit 4f3865fb57a04db7cca068fed1c15badc064a302

Authored by Richard Purdie
Committed by Linus Torvalds
1 parent 4f1bcaf094

[PATCH] zlib_inflate: Upgrade library code to a recent version

Upgrade the zlib_inflate implementation in the kernel from a patched
version 1.1.3/4 to a patched 1.2.3.

The code in the kernel is about seven years old and I noticed that the
external zlib library's inflate performance was significantly faster (~50%)
than the code in the kernel on ARM (and faster again on x86_32).

For comparison the newer deflate code is 20% slower on ARM and 50% slower
on x86_32 but gives an approx 1% compression ratio improvement.  I don't
consider this to be an improvement for kernel use so have no plans to
change the zlib_deflate code.

Various changes have been made to the zlib code in the kernel, the most
significant being the extra functions/flush option used by ppp_deflate.
This update reimplements the features PPP needs to ensure it continues to
work.

This code has been tested on ARM under both JFFS2 (with zlib compression
enabled) and ppp_deflate and on x86_32.  JFFS2 sees an approx.  10% real
world file read speed improvement.

This patch also removes ZLIB_VERSION as it no longer has a correct value.
We don't need version checks anyway as the kernel's module handling will
take care of that for us.  This removal is also more in keeping with the
zlib author's wishes (http://www.zlib.net/zlib_faq.html#faq24) and I've
added something to the zlib.h header to note its a modified version.

Signed-off-by: Richard Purdie <rpurdie@rpsys.net>
Acked-by: Joern Engel <joern@wh.fh-wedel.de>
Signed-off-by: Andrew Morton <akpm@osdl.org>
Signed-off-by: Linus Torvalds <torvalds@osdl.org>

Showing 24 changed files with 1877 additions and 2006 deletions Inline Diff

arch/powerpc/boot/Makefile
1 # Makefile for making ELF bootable images for booting on CHRP 1 # Makefile for making ELF bootable images for booting on CHRP
2 # using Open Firmware. 2 # using Open Firmware.
3 # 3 #
4 # Geert Uytterhoeven September 1997 4 # Geert Uytterhoeven September 1997
5 # 5 #
6 # Based on coffboot by Paul Mackerras 6 # Based on coffboot by Paul Mackerras
7 # Simplified for ppc64 by Todd Inglett 7 # Simplified for ppc64 by Todd Inglett
8 # 8 #
9 # NOTE: this code is built for 32 bit in ELF32 format even though 9 # NOTE: this code is built for 32 bit in ELF32 format even though
10 # it packages a 64 bit kernel. We do this to simplify the 10 # it packages a 64 bit kernel. We do this to simplify the
11 # bootloader and increase compatibility with OpenFirmware. 11 # bootloader and increase compatibility with OpenFirmware.
12 # 12 #
13 # To this end we need to define BOOTCC, etc, as the tools 13 # To this end we need to define BOOTCC, etc, as the tools
14 # needed to build the 32 bit image. These are normally HOSTCC, 14 # needed to build the 32 bit image. These are normally HOSTCC,
15 # but may be a third compiler if, for example, you are cross 15 # but may be a third compiler if, for example, you are cross
16 # compiling from an intel box. Once the 64bit ppc gcc is 16 # compiling from an intel box. Once the 64bit ppc gcc is
17 # stable it will probably simply be a compiler switch to 17 # stable it will probably simply be a compiler switch to
18 # compile for 32bit mode. 18 # compile for 32bit mode.
19 # To make it easier to setup a cross compiler, 19 # To make it easier to setup a cross compiler,
20 # CROSS32_COMPILE is setup as a prefix just like CROSS_COMPILE 20 # CROSS32_COMPILE is setup as a prefix just like CROSS_COMPILE
21 # in the toplevel makefile. 21 # in the toplevel makefile.
22 22
23 23
24 HOSTCC := gcc 24 HOSTCC := gcc
25 BOOTCFLAGS := $(HOSTCFLAGS) -fno-builtin -nostdinc -isystem \ 25 BOOTCFLAGS := $(HOSTCFLAGS) -fno-builtin -nostdinc -isystem \
26 $(shell $(CROSS32CC) -print-file-name=include) -fPIC 26 $(shell $(CROSS32CC) -print-file-name=include) -fPIC
27 BOOTAFLAGS := -D__ASSEMBLY__ $(BOOTCFLAGS) -traditional -nostdinc 27 BOOTAFLAGS := -D__ASSEMBLY__ $(BOOTCFLAGS) -traditional -nostdinc
28 OBJCOPYFLAGS := contents,alloc,load,readonly,data 28 OBJCOPYFLAGS := contents,alloc,load,readonly,data
29 OBJCOPY_COFF_ARGS := -O aixcoff-rs6000 --set-start 0x500000 29 OBJCOPY_COFF_ARGS := -O aixcoff-rs6000 --set-start 0x500000
30 OBJCOPY_MIB_ARGS := -O aixcoff-rs6000 -R .stab -R .stabstr -R .comment 30 OBJCOPY_MIB_ARGS := -O aixcoff-rs6000 -R .stab -R .stabstr -R .comment
31 31
32 zlib := infblock.c infcodes.c inffast.c inflate.c inftrees.c infutil.c 32 zlib := inffast.c inflate.c inftrees.c
33 zlibheader := infblock.h infcodes.h inffast.h inftrees.h infutil.h 33 zlibheader := inffast.h inffixed.h inflate.h inftrees.h infutil.h
34 zliblinuxheader := zlib.h zconf.h zutil.h 34 zliblinuxheader := zlib.h zconf.h zutil.h
35 35
36 $(addprefix $(obj)/,$(zlib) main.o): $(addprefix $(obj)/,$(zliblinuxheader)) $(addprefix $(obj)/,$(zlibheader)) 36 $(addprefix $(obj)/,$(zlib) main.o): $(addprefix $(obj)/,$(zliblinuxheader)) $(addprefix $(obj)/,$(zlibheader))
37 #$(addprefix $(obj)/,main.o): $(addprefix $(obj)/,zlib.h) 37 #$(addprefix $(obj)/,main.o): $(addprefix $(obj)/,zlib.h)
38 38
39 src-boot := crt0.S string.S prom.c stdio.c main.c div64.S 39 src-boot := crt0.S string.S prom.c stdio.c main.c div64.S
40 src-boot += $(zlib) 40 src-boot += $(zlib)
41 src-boot := $(addprefix $(obj)/, $(src-boot)) 41 src-boot := $(addprefix $(obj)/, $(src-boot))
42 obj-boot := $(addsuffix .o, $(basename $(src-boot))) 42 obj-boot := $(addsuffix .o, $(basename $(src-boot)))
43 43
44 BOOTCFLAGS += -I$(obj) -I$(srctree)/$(obj) 44 BOOTCFLAGS += -I$(obj) -I$(srctree)/$(obj)
45 45
46 quiet_cmd_copy_zlib = COPY $@ 46 quiet_cmd_copy_zlib = COPY $@
47 cmd_copy_zlib = sed "s@__attribute_used__@@;s@<linux/\([^>]\+\).*@\"\1\"@" $< > $@ 47 cmd_copy_zlib = sed "s@__attribute_used__@@;s@<linux/\([^>]\+\).*@\"\1\"@" $< > $@
48 48
49 quiet_cmd_copy_zlibheader = COPY $@ 49 quiet_cmd_copy_zlibheader = COPY $@
50 cmd_copy_zlibheader = sed "s@<linux/\([^>]\+\).*@\"\1\"@" $< > $@ 50 cmd_copy_zlibheader = sed "s@<linux/\([^>]\+\).*@\"\1\"@" $< > $@
51 # stddef.h for NULL 51 # stddef.h for NULL
52 quiet_cmd_copy_zliblinuxheader = COPY $@ 52 quiet_cmd_copy_zliblinuxheader = COPY $@
53 cmd_copy_zliblinuxheader = sed "s@<linux/string.h>@\"string.h\"@;s@<linux/kernel.h>@<stddef.h>@;s@<linux/\([^>]\+\).*@\"\1\"@" $< > $@ 53 cmd_copy_zliblinuxheader = sed "s@<linux/string.h>@\"string.h\"@;s@<linux/kernel.h>@<stddef.h>@;s@<linux/\([^>]\+\).*@\"\1\"@" $< > $@
54 54
55 $(addprefix $(obj)/,$(zlib)): $(obj)/%: $(srctree)/lib/zlib_inflate/% 55 $(addprefix $(obj)/,$(zlib)): $(obj)/%: $(srctree)/lib/zlib_inflate/%
56 $(call cmd,copy_zlib) 56 $(call cmd,copy_zlib)
57 57
58 $(addprefix $(obj)/,$(zlibheader)): $(obj)/%: $(srctree)/lib/zlib_inflate/% 58 $(addprefix $(obj)/,$(zlibheader)): $(obj)/%: $(srctree)/lib/zlib_inflate/%
59 $(call cmd,copy_zlibheader) 59 $(call cmd,copy_zlibheader)
60 60
61 $(addprefix $(obj)/,$(zliblinuxheader)): $(obj)/%: $(srctree)/include/linux/% 61 $(addprefix $(obj)/,$(zliblinuxheader)): $(obj)/%: $(srctree)/include/linux/%
62 $(call cmd,copy_zliblinuxheader) 62 $(call cmd,copy_zliblinuxheader)
63 63
64 clean-files := $(zlib) $(zlibheader) $(zliblinuxheader) 64 clean-files := $(zlib) $(zlibheader) $(zliblinuxheader)
65 65
66 66
67 quiet_cmd_bootcc = BOOTCC $@ 67 quiet_cmd_bootcc = BOOTCC $@
68 cmd_bootcc = $(CROSS32CC) -Wp,-MD,$(depfile) $(BOOTCFLAGS) -c -o $@ $< 68 cmd_bootcc = $(CROSS32CC) -Wp,-MD,$(depfile) $(BOOTCFLAGS) -c -o $@ $<
69 69
70 quiet_cmd_bootas = BOOTAS $@ 70 quiet_cmd_bootas = BOOTAS $@
71 cmd_bootas = $(CROSS32CC) -Wp,-MD,$(depfile) $(BOOTAFLAGS) -c -o $@ $< 71 cmd_bootas = $(CROSS32CC) -Wp,-MD,$(depfile) $(BOOTAFLAGS) -c -o $@ $<
72 72
73 quiet_cmd_bootld = BOOTLD $@ 73 quiet_cmd_bootld = BOOTLD $@
74 cmd_bootld = $(CROSS32LD) -T $(srctree)/$(src)/$(3) -o $@ $(2) 74 cmd_bootld = $(CROSS32LD) -T $(srctree)/$(src)/$(3) -o $@ $(2)
75 75
76 $(patsubst %.c,%.o, $(filter %.c, $(src-boot))): %.o: %.c 76 $(patsubst %.c,%.o, $(filter %.c, $(src-boot))): %.o: %.c
77 $(call if_changed_dep,bootcc) 77 $(call if_changed_dep,bootcc)
78 $(patsubst %.S,%.o, $(filter %.S, $(src-boot))): %.o: %.S 78 $(patsubst %.S,%.o, $(filter %.S, $(src-boot))): %.o: %.S
79 $(call if_changed_dep,bootas) 79 $(call if_changed_dep,bootas)
80 80
81 #----------------------------------------------------------- 81 #-----------------------------------------------------------
82 # ELF sections within the zImage bootloader/wrapper 82 # ELF sections within the zImage bootloader/wrapper
83 #----------------------------------------------------------- 83 #-----------------------------------------------------------
84 required := vmlinux.strip 84 required := vmlinux.strip
85 initrd := initrd 85 initrd := initrd
86 86
87 obj-sec = $(foreach section, $(1), $(patsubst %,$(obj)/kernel-%.o, $(section))) 87 obj-sec = $(foreach section, $(1), $(patsubst %,$(obj)/kernel-%.o, $(section)))
88 src-sec = $(foreach section, $(1), $(patsubst %,$(obj)/kernel-%.c, $(section))) 88 src-sec = $(foreach section, $(1), $(patsubst %,$(obj)/kernel-%.c, $(section)))
89 gz-sec = $(foreach section, $(1), $(patsubst %,$(obj)/kernel-%.gz, $(section))) 89 gz-sec = $(foreach section, $(1), $(patsubst %,$(obj)/kernel-%.gz, $(section)))
90 90
91 hostprogs-y := addnote addRamDisk hack-coff 91 hostprogs-y := addnote addRamDisk hack-coff
92 92
93 targets += zImage.vmode zImage.initrd.vmode zImage zImage.initrd \ 93 targets += zImage.vmode zImage.initrd.vmode zImage zImage.initrd \
94 zImage.coff zImage.initrd.coff miboot.image miboot.initrd.image \ 94 zImage.coff zImage.initrd.coff miboot.image miboot.initrd.image \
95 $(patsubst $(obj)/%,%, $(call obj-sec, $(required) $(initrd))) \ 95 $(patsubst $(obj)/%,%, $(call obj-sec, $(required) $(initrd))) \
96 $(patsubst $(obj)/%,%, $(call src-sec, $(required) $(initrd))) \ 96 $(patsubst $(obj)/%,%, $(call src-sec, $(required) $(initrd))) \
97 $(patsubst $(obj)/%,%, $(call gz-sec, $(required) $(initrd))) \ 97 $(patsubst $(obj)/%,%, $(call gz-sec, $(required) $(initrd))) \
98 vmlinux.initrd dummy.o 98 vmlinux.initrd dummy.o
99 extra-y := initrd.o 99 extra-y := initrd.o
100 100
101 quiet_cmd_ramdisk = RAMDISK $@ 101 quiet_cmd_ramdisk = RAMDISK $@
102 cmd_ramdisk = $(obj)/addRamDisk $(obj)/ramdisk.image.gz $< $@ 102 cmd_ramdisk = $(obj)/addRamDisk $(obj)/ramdisk.image.gz $< $@
103 103
104 quiet_cmd_stripvm = STRIP $@ 104 quiet_cmd_stripvm = STRIP $@
105 cmd_stripvm = $(STRIP) -s -R .comment $< -o $@ 105 cmd_stripvm = $(STRIP) -s -R .comment $< -o $@
106 106
107 vmlinux.strip: vmlinux 107 vmlinux.strip: vmlinux
108 $(call if_changed,stripvm) 108 $(call if_changed,stripvm)
109 $(obj)/vmlinux.initrd: vmlinux.strip $(obj)/addRamDisk $(obj)/ramdisk.image.gz 109 $(obj)/vmlinux.initrd: vmlinux.strip $(obj)/addRamDisk $(obj)/ramdisk.image.gz
110 $(call if_changed,ramdisk) 110 $(call if_changed,ramdisk)
111 111
112 quiet_cmd_addsection = ADDSEC $@ 112 quiet_cmd_addsection = ADDSEC $@
113 cmd_addsection = $(CROSS32OBJCOPY) $@ \ 113 cmd_addsection = $(CROSS32OBJCOPY) $@ \
114 --add-section=.kernel:$(strip $(patsubst $(obj)/kernel-%.o,%, $@))=$(patsubst %.o,%.gz, $@) \ 114 --add-section=.kernel:$(strip $(patsubst $(obj)/kernel-%.o,%, $@))=$(patsubst %.o,%.gz, $@) \
115 --set-section-flags=.kernel:$(strip $(patsubst $(obj)/kernel-%.o,%, $@))=$(OBJCOPYFLAGS) 115 --set-section-flags=.kernel:$(strip $(patsubst $(obj)/kernel-%.o,%, $@))=$(OBJCOPYFLAGS)
116 116
117 quiet_cmd_addnote = ADDNOTE $@ 117 quiet_cmd_addnote = ADDNOTE $@
118 cmd_addnote = $(obj)/addnote $@ 118 cmd_addnote = $(obj)/addnote $@
119 119
120 quiet_cmd_gen-miboot = GEN $@ 120 quiet_cmd_gen-miboot = GEN $@
121 cmd_gen-miboot = $(OBJCOPY) $(OBJCOPY_MIB_ARGS) \ 121 cmd_gen-miboot = $(OBJCOPY) $(OBJCOPY_MIB_ARGS) \
122 --add-section=$1=$(word 2, $^) $< $@ 122 --add-section=$1=$(word 2, $^) $< $@
123 123
124 quiet_cmd_gencoff = COFF $@ 124 quiet_cmd_gencoff = COFF $@
125 cmd_gencoff = $(OBJCOPY) $(OBJCOPY_COFF_ARGS) $@ && \ 125 cmd_gencoff = $(OBJCOPY) $(OBJCOPY_COFF_ARGS) $@ && \
126 $(obj)/hack-coff $@ 126 $(obj)/hack-coff $@
127 127
128 $(call gz-sec, $(required)): $(obj)/kernel-%.gz: % 128 $(call gz-sec, $(required)): $(obj)/kernel-%.gz: %
129 $(call if_changed,gzip) 129 $(call if_changed,gzip)
130 130
131 $(obj)/kernel-initrd.gz: $(obj)/ramdisk.image.gz 131 $(obj)/kernel-initrd.gz: $(obj)/ramdisk.image.gz
132 cp -f $(obj)/ramdisk.image.gz $@ 132 cp -f $(obj)/ramdisk.image.gz $@
133 133
134 $(call src-sec, $(required) $(initrd)): $(obj)/kernel-%.c: $(obj)/kernel-%.gz 134 $(call src-sec, $(required) $(initrd)): $(obj)/kernel-%.c: $(obj)/kernel-%.gz
135 @touch $@ 135 @touch $@
136 136
137 $(call obj-sec, $(required) $(initrd)): $(obj)/kernel-%.o: $(obj)/kernel-%.c 137 $(call obj-sec, $(required) $(initrd)): $(obj)/kernel-%.o: $(obj)/kernel-%.c
138 $(call if_changed_dep,bootcc) 138 $(call if_changed_dep,bootcc)
139 $(call cmd,addsection) 139 $(call cmd,addsection)
140 140
141 $(obj)/zImage.vmode $(obj)/zImage.coff: obj-boot += $(call obj-sec, $(required)) 141 $(obj)/zImage.vmode $(obj)/zImage.coff: obj-boot += $(call obj-sec, $(required))
142 $(obj)/zImage.vmode: $(call obj-sec, $(required)) $(obj-boot) $(srctree)/$(src)/zImage.lds 142 $(obj)/zImage.vmode: $(call obj-sec, $(required)) $(obj-boot) $(srctree)/$(src)/zImage.lds
143 $(call cmd,bootld,$(obj-boot),zImage.lds) 143 $(call cmd,bootld,$(obj-boot),zImage.lds)
144 144
145 $(obj)/zImage.initrd.vmode $(obj)/zImage.initrd.coff: obj-boot += $(call obj-sec, $(required) $(initrd)) 145 $(obj)/zImage.initrd.vmode $(obj)/zImage.initrd.coff: obj-boot += $(call obj-sec, $(required) $(initrd))
146 $(obj)/zImage.initrd.vmode: $(call obj-sec, $(required) $(initrd)) $(obj-boot) $(srctree)/$(src)/zImage.lds 146 $(obj)/zImage.initrd.vmode: $(call obj-sec, $(required) $(initrd)) $(obj-boot) $(srctree)/$(src)/zImage.lds
147 $(call cmd,bootld,$(obj-boot),zImage.lds) 147 $(call cmd,bootld,$(obj-boot),zImage.lds)
148 148
149 # For 32-bit powermacs, build the COFF and miboot images 149 # For 32-bit powermacs, build the COFF and miboot images
150 # as well as the ELF images. 150 # as well as the ELF images.
151 coffimage-$(CONFIG_PPC_PMAC)-$(CONFIG_PPC32) := $(obj)/zImage.coff 151 coffimage-$(CONFIG_PPC_PMAC)-$(CONFIG_PPC32) := $(obj)/zImage.coff
152 coffrdimg-$(CONFIG_PPC_PMAC)-$(CONFIG_PPC32) := $(obj)/zImage.initrd.coff 152 coffrdimg-$(CONFIG_PPC_PMAC)-$(CONFIG_PPC32) := $(obj)/zImage.initrd.coff
153 mibootimg-$(CONFIG_PPC_PMAC)-$(CONFIG_PPC32) := $(obj)/miboot.image 153 mibootimg-$(CONFIG_PPC_PMAC)-$(CONFIG_PPC32) := $(obj)/miboot.image
154 mibrdimg-$(CONFIG_PPC_PMAC)-$(CONFIG_PPC32) := $(obj)/miboot.initrd.image 154 mibrdimg-$(CONFIG_PPC_PMAC)-$(CONFIG_PPC32) := $(obj)/miboot.initrd.image
155 155
156 $(obj)/zImage: $(obj)/zImage.vmode $(obj)/addnote $(coffimage-y-y) \ 156 $(obj)/zImage: $(obj)/zImage.vmode $(obj)/addnote $(coffimage-y-y) \
157 $(mibootimg-y-y) 157 $(mibootimg-y-y)
158 @cp -f $< $@ 158 @cp -f $< $@
159 $(call if_changed,addnote) 159 $(call if_changed,addnote)
160 160
161 $(obj)/zImage.initrd: $(obj)/zImage.initrd.vmode $(obj)/addnote \ 161 $(obj)/zImage.initrd: $(obj)/zImage.initrd.vmode $(obj)/addnote \
162 $(coffrdimg-y-y) $(mibrdimg-y-y) 162 $(coffrdimg-y-y) $(mibrdimg-y-y)
163 @cp -f $< $@ 163 @cp -f $< $@
164 $(call if_changed,addnote) 164 $(call if_changed,addnote)
165 165
166 $(obj)/zImage.coff: $(call obj-sec, $(required)) $(obj-boot) \ 166 $(obj)/zImage.coff: $(call obj-sec, $(required)) $(obj-boot) \
167 $(srctree)/$(src)/zImage.coff.lds $(obj)/hack-coff 167 $(srctree)/$(src)/zImage.coff.lds $(obj)/hack-coff
168 $(call cmd,bootld,$(obj-boot),zImage.coff.lds) 168 $(call cmd,bootld,$(obj-boot),zImage.coff.lds)
169 $(call cmd,gencoff) 169 $(call cmd,gencoff)
170 170
171 $(obj)/zImage.initrd.coff: $(call obj-sec, $(required) $(initrd)) $(obj-boot) \ 171 $(obj)/zImage.initrd.coff: $(call obj-sec, $(required) $(initrd)) $(obj-boot) \
172 $(srctree)/$(src)/zImage.coff.lds $(obj)/hack-coff 172 $(srctree)/$(src)/zImage.coff.lds $(obj)/hack-coff
173 $(call cmd,bootld,$(obj-boot),zImage.coff.lds) 173 $(call cmd,bootld,$(obj-boot),zImage.coff.lds)
174 $(call cmd,gencoff) 174 $(call cmd,gencoff)
175 175
176 $(obj)/miboot.image: $(obj)/dummy.o $(obj)/vmlinux.gz 176 $(obj)/miboot.image: $(obj)/dummy.o $(obj)/vmlinux.gz
177 $(call cmd,gen-miboot,image) 177 $(call cmd,gen-miboot,image)
178 178
179 $(obj)/miboot.initrd.image: $(obj)/miboot.image $(images)/ramdisk.image.gz 179 $(obj)/miboot.initrd.image: $(obj)/miboot.image $(images)/ramdisk.image.gz
180 $(call cmd,gen-miboot,initrd) 180 $(call cmd,gen-miboot,initrd)
181 181
182 #----------------------------------------------------------- 182 #-----------------------------------------------------------
183 # build u-boot images 183 # build u-boot images
184 #----------------------------------------------------------- 184 #-----------------------------------------------------------
185 quiet_cmd_mygzip = GZIP $@ 185 quiet_cmd_mygzip = GZIP $@
186 cmd_mygzip = gzip -f -9 < $< > $@.$$$$ && mv $@.$$$$ $@ 186 cmd_mygzip = gzip -f -9 < $< > $@.$$$$ && mv $@.$$$$ $@
187 187
188 quiet_cmd_objbin = OBJCOPY $@ 188 quiet_cmd_objbin = OBJCOPY $@
189 cmd_objbin = $(OBJCOPY) -O binary $< $@ 189 cmd_objbin = $(OBJCOPY) -O binary $< $@
190 190
191 quiet_cmd_uimage = UIMAGE $@ 191 quiet_cmd_uimage = UIMAGE $@
192 cmd_uimage = $(CONFIG_SHELL) $(MKIMAGE) -A ppc -O linux -T kernel \ 192 cmd_uimage = $(CONFIG_SHELL) $(MKIMAGE) -A ppc -O linux -T kernel \
193 -C gzip -a 00000000 -e 00000000 -n 'Linux-$(KERNELRELEASE)' \ 193 -C gzip -a 00000000 -e 00000000 -n 'Linux-$(KERNELRELEASE)' \
194 -d $< $@ 194 -d $< $@
195 195
196 MKIMAGE := $(srctree)/scripts/mkuboot.sh 196 MKIMAGE := $(srctree)/scripts/mkuboot.sh
197 targets += uImage 197 targets += uImage
198 extra-y += vmlinux.bin vmlinux.gz 198 extra-y += vmlinux.bin vmlinux.gz
199 199
200 $(obj)/vmlinux.bin: vmlinux FORCE 200 $(obj)/vmlinux.bin: vmlinux FORCE
201 $(call if_changed,objbin) 201 $(call if_changed,objbin)
202 202
203 $(obj)/vmlinux.gz: $(obj)/vmlinux.bin FORCE 203 $(obj)/vmlinux.gz: $(obj)/vmlinux.bin FORCE
204 $(call if_changed,mygzip) 204 $(call if_changed,mygzip)
205 205
206 $(obj)/uImage: $(obj)/vmlinux.gz 206 $(obj)/uImage: $(obj)/vmlinux.gz
207 $(Q)rm -f $@ 207 $(Q)rm -f $@
208 $(call cmd,uimage) 208 $(call cmd,uimage)
209 @echo -n ' Image: $@ ' 209 @echo -n ' Image: $@ '
210 @if [ -f $@ ]; then echo 'is ready' ; else echo 'not made'; fi 210 @if [ -f $@ ]; then echo 'is ready' ; else echo 'not made'; fi
211 211
212 install: $(CONFIGURE) $(BOOTIMAGE) 212 install: $(CONFIGURE) $(BOOTIMAGE)
213 sh -x $(srctree)/$(src)/install.sh "$(KERNELRELEASE)" vmlinux System.map "$(INSTALL_PATH)" "$(BOOTIMAGE)" 213 sh -x $(srctree)/$(src)/install.sh "$(KERNELRELEASE)" vmlinux System.map "$(INSTALL_PATH)" "$(BOOTIMAGE)"
214 214
215 clean-files += $(addprefix $(objtree)/, $(obj-boot) vmlinux.strip) 215 clean-files += $(addprefix $(objtree)/, $(obj-boot) vmlinux.strip)
216 216
arch/ppc/boot/lib/Makefile
1 # 1 #
2 # Makefile for some libs needed by zImage. 2 # Makefile for some libs needed by zImage.
3 # 3 #
4 4
5 CFLAGS_kbd.o := -Idrivers/char 5 CFLAGS_kbd.o := -Idrivers/char
6 CFLAGS_vreset.o := -Iarch/ppc/boot/include 6 CFLAGS_vreset.o := -Iarch/ppc/boot/include
7 7
8 zlib := infblock.c infcodes.c inffast.c inflate.c inftrees.c infutil.c 8 zlib := inffast.c inflate.c inftrees.c
9 9
10 lib-y += $(zlib:.c=.o) div64.o 10 lib-y += $(zlib:.c=.o) div64.o
11 lib-$(CONFIG_VGA_CONSOLE) += vreset.o kbd.o 11 lib-$(CONFIG_VGA_CONSOLE) += vreset.o kbd.o
12 12
13 13
14 # zlib files needs header from their original place 14 # zlib files needs header from their original place
15 EXTRA_CFLAGS += -Ilib/zlib_inflate 15 EXTRA_CFLAGS += -Ilib/zlib_inflate
16 16
17 quiet_cmd_copy_zlib = COPY $@ 17 quiet_cmd_copy_zlib = COPY $@
18 cmd_copy_zlib = cat $< > $@ 18 cmd_copy_zlib = cat $< > $@
19 19
20 $(addprefix $(obj)/,$(zlib)): $(obj)/%: $(srctree)/lib/zlib_inflate/% 20 $(addprefix $(obj)/,$(zlib)): $(obj)/%: $(srctree)/lib/zlib_inflate/%
21 $(call cmd,copy_zlib) 21 $(call cmd,copy_zlib)
22 22
23 clean-files := $(zlib) 23 clean-files := $(zlib)
24 24
arch/xtensa/boot/lib/Makefile
1 # 1 #
2 # Makefile for some libs needed by zImage. 2 # Makefile for some libs needed by zImage.
3 # 3 #
4 4
5 zlib := infblock.c infcodes.c inffast.c inflate.c inftrees.c infutil.c 5 zlib := inffast.c inflate.c inftrees.c
6 6
7 lib-y += $(zlib:.c=.o) zmem.o 7 lib-y += $(zlib:.c=.o) zmem.o
8 8
9 EXTRA_CFLAGS += -Ilib/zlib_inflate 9 EXTRA_CFLAGS += -Ilib/zlib_inflate
10 10
11 quiet_cmd_copy_zlib = COPY $@ 11 quiet_cmd_copy_zlib = COPY $@
12 cmd_copy_zlib = cat $< > $@ 12 cmd_copy_zlib = cat $< > $@
13 13
14 $(addprefix $(obj)/,$(zlib)): $(obj)/%: $(srctree)/lib/zlib_inflate/% 14 $(addprefix $(obj)/,$(zlib)): $(obj)/%: $(srctree)/lib/zlib_inflate/%
15 $(call cmd,copy_zlib) 15 $(call cmd,copy_zlib)
16 16
17 clean-files := $(zlib) 17 clean-files := $(zlib)
18 18
include/linux/zconf.h
1 /* zconf.h -- configuration of the zlib compression library 1 /* zconf.h -- configuration of the zlib compression library
2 * Copyright (C) 1995-1998 Jean-loup Gailly. 2 * Copyright (C) 1995-1998 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6 /* @(#) $Id$ */ 6 /* @(#) $Id$ */
7 7
8 #ifndef _ZCONF_H 8 #ifndef _ZCONF_H
9 #define _ZCONF_H 9 #define _ZCONF_H
10 10
11 /* The memory requirements for deflate are (in bytes): 11 /* The memory requirements for deflate are (in bytes):
12 (1 << (windowBits+2)) + (1 << (memLevel+9)) 12 (1 << (windowBits+2)) + (1 << (memLevel+9))
13 that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) 13 that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
14 plus a few kilobytes for small objects. For example, if you want to reduce 14 plus a few kilobytes for small objects. For example, if you want to reduce
15 the default memory requirements from 256K to 128K, compile with 15 the default memory requirements from 256K to 128K, compile with
16 make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" 16 make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
17 Of course this will generally degrade compression (there's no free lunch). 17 Of course this will generally degrade compression (there's no free lunch).
18 18
19 The memory requirements for inflate are (in bytes) 1 << windowBits 19 The memory requirements for inflate are (in bytes) 1 << windowBits
20 that is, 32K for windowBits=15 (default value) plus a few kilobytes 20 that is, 32K for windowBits=15 (default value) plus a few kilobytes
21 for small objects. 21 for small objects.
22 */ 22 */
23 23
24 /* Maximum value for memLevel in deflateInit2 */ 24 /* Maximum value for memLevel in deflateInit2 */
25 #ifndef MAX_MEM_LEVEL 25 #ifndef MAX_MEM_LEVEL
26 # define MAX_MEM_LEVEL 8 26 # define MAX_MEM_LEVEL 8
27 #endif 27 #endif
28 28
29 /* Maximum value for windowBits in deflateInit2 and inflateInit2. 29 /* Maximum value for windowBits in deflateInit2 and inflateInit2.
30 * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files 30 * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
31 * created by gzip. (Files created by minigzip can still be extracted by 31 * created by gzip. (Files created by minigzip can still be extracted by
32 * gzip.) 32 * gzip.)
33 */ 33 */
34 #ifndef MAX_WBITS 34 #ifndef MAX_WBITS
35 # define MAX_WBITS 15 /* 32K LZ77 window */ 35 # define MAX_WBITS 15 /* 32K LZ77 window */
36 #endif 36 #endif
37 37
38 /* default windowBits for decompression. MAX_WBITS is for compression only */
39 #ifndef DEF_WBITS
40 # define DEF_WBITS MAX_WBITS
41 #endif
42
43 /* default memLevel */
44 #if MAX_MEM_LEVEL >= 8
45 # define DEF_MEM_LEVEL 8
46 #else
47 # define DEF_MEM_LEVEL MAX_MEM_LEVEL
48 #endif
49
38 /* Type declarations */ 50 /* Type declarations */
39 51
40 typedef unsigned char Byte; /* 8 bits */ 52 typedef unsigned char Byte; /* 8 bits */
41 typedef unsigned int uInt; /* 16 bits or more */ 53 typedef unsigned int uInt; /* 16 bits or more */
42 typedef unsigned long uLong; /* 32 bits or more */ 54 typedef unsigned long uLong; /* 32 bits or more */
43 typedef void *voidp; 55 typedef void *voidp;
44 56
45 #endif /* _ZCONF_H */ 57 #endif /* _ZCONF_H */
46 58
include/linux/zlib.h
1 /* zlib.h -- interface of the 'zlib' general purpose compression library 1 /* zlib.h -- interface of the 'zlib' general purpose compression library
2 version 1.1.3, July 9th, 1998
3 2
4 Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler 3 Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler
5 4
6 This software is provided 'as-is', without any express or implied 5 This software is provided 'as-is', without any express or implied
7 warranty. In no event will the authors be held liable for any damages 6 warranty. In no event will the authors be held liable for any damages
8 arising from the use of this software. 7 arising from the use of this software.
9 8
10 Permission is granted to anyone to use this software for any purpose, 9 Permission is granted to anyone to use this software for any purpose,
11 including commercial applications, and to alter it and redistribute it 10 including commercial applications, and to alter it and redistribute it
12 freely, subject to the following restrictions: 11 freely, subject to the following restrictions:
13 12
14 1. The origin of this software must not be misrepresented; you must not 13 1. The origin of this software must not be misrepresented; you must not
15 claim that you wrote the original software. If you use this software 14 claim that you wrote the original software. If you use this software
16 in a product, an acknowledgment in the product documentation would be 15 in a product, an acknowledgment in the product documentation would be
17 appreciated but is not required. 16 appreciated but is not required.
18 2. Altered source versions must be plainly marked as such, and must not be 17 2. Altered source versions must be plainly marked as such, and must not be
19 misrepresented as being the original software. 18 misrepresented as being the original software.
20 3. This notice may not be removed or altered from any source distribution. 19 3. This notice may not be removed or altered from any source distribution.
21 20
22 Jean-loup Gailly Mark Adler 21 Jean-loup Gailly Mark Adler
23 jloup@gzip.org madler@alumni.caltech.edu 22 jloup@gzip.org madler@alumni.caltech.edu
24 23
25 24
26 The data format used by the zlib library is described by RFCs (Request for 25 The data format used by the zlib library is described by RFCs (Request for
27 Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt 26 Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt
28 (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). 27 (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
29 */ 28 */
30 29
31 #ifndef _ZLIB_H 30 #ifndef _ZLIB_H
32 #define _ZLIB_H 31 #define _ZLIB_H
33 32
34 #include <linux/zconf.h> 33 #include <linux/zconf.h>
35 34
36 #define ZLIB_VERSION "1.1.3" 35 /* zlib deflate based on ZLIB_VERSION "1.1.3" */
36 /* zlib inflate based on ZLIB_VERSION "1.2.3" */
37 37
38 /*
39 This is a modified version of zlib for use inside the Linux kernel.
40 The main changes are to perform all memory allocation in advance.
41
42 Inflation Changes:
43 * Z_PACKET_FLUSH is added and used by ppp_deflate. Before returning
44 this checks there is no more input data available and the next data
45 is a STORED block. It also resets the mode to be read for the next
46 data, all as per PPP requirements.
47 * Addition of zlib_inflateIncomp which copies incompressible data into
48 the history window and adjusts the accoutning without calling
49 zlib_inflate itself to inflate the data.
50 */
51
38 /* 52 /*
39 The 'zlib' compression library provides in-memory compression and 53 The 'zlib' compression library provides in-memory compression and
40 decompression functions, including integrity checks of the uncompressed 54 decompression functions, including integrity checks of the uncompressed
41 data. This version of the library supports only one compression method 55 data. This version of the library supports only one compression method
42 (deflation) but other algorithms will be added later and will have the same 56 (deflation) but other algorithms will be added later and will have the same
43 stream interface. 57 stream interface.
44 58
45 Compression can be done in a single step if the buffers are large 59 Compression can be done in a single step if the buffers are large
46 enough (for example if an input file is mmap'ed), or can be done by 60 enough (for example if an input file is mmap'ed), or can be done by
47 repeated calls of the compression function. In the latter case, the 61 repeated calls of the compression function. In the latter case, the
48 application must provide more input and/or consume the output 62 application must provide more input and/or consume the output
49 (providing more output space) before each call. 63 (providing more output space) before each call.
50 64
65 The compressed data format used by default by the in-memory functions is
66 the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
67 around a deflate stream, which is itself documented in RFC 1951.
68
51 The library also supports reading and writing files in gzip (.gz) format 69 The library also supports reading and writing files in gzip (.gz) format
52 with an interface similar to that of stdio. 70 with an interface similar to that of stdio.
53 71
72 The zlib format was designed to be compact and fast for use in memory
73 and on communications channels. The gzip format was designed for single-
74 file compression on file systems, has a larger header than zlib to maintain
75 directory information, and uses a different, slower check method than zlib.
76
54 The library does not install any signal handler. The decoder checks 77 The library does not install any signal handler. The decoder checks
55 the consistency of the compressed data, so the library should never 78 the consistency of the compressed data, so the library should never
56 crash even in case of corrupted input. 79 crash even in case of corrupted input.
57 */ 80 */
58 81
59 struct internal_state; 82 struct internal_state;
60 83
61 typedef struct z_stream_s { 84 typedef struct z_stream_s {
62 Byte *next_in; /* next input byte */ 85 Byte *next_in; /* next input byte */
63 uInt avail_in; /* number of bytes available at next_in */ 86 uInt avail_in; /* number of bytes available at next_in */
64 uLong total_in; /* total nb of input bytes read so far */ 87 uLong total_in; /* total nb of input bytes read so far */
65 88
66 Byte *next_out; /* next output byte should be put there */ 89 Byte *next_out; /* next output byte should be put there */
67 uInt avail_out; /* remaining free space at next_out */ 90 uInt avail_out; /* remaining free space at next_out */
68 uLong total_out; /* total nb of bytes output so far */ 91 uLong total_out; /* total nb of bytes output so far */
69 92
70 char *msg; /* last error message, NULL if no error */ 93 char *msg; /* last error message, NULL if no error */
71 struct internal_state *state; /* not visible by applications */ 94 struct internal_state *state; /* not visible by applications */
72 95
73 void *workspace; /* memory allocated for this stream */ 96 void *workspace; /* memory allocated for this stream */
74 97
75 int data_type; /* best guess about the data type: ascii or binary */ 98 int data_type; /* best guess about the data type: ascii or binary */
76 uLong adler; /* adler32 value of the uncompressed data */ 99 uLong adler; /* adler32 value of the uncompressed data */
77 uLong reserved; /* reserved for future use */ 100 uLong reserved; /* reserved for future use */
78 } z_stream; 101 } z_stream;
79 102
80 typedef z_stream *z_streamp; 103 typedef z_stream *z_streamp;
81 104
82 /* 105 /*
83 The application must update next_in and avail_in when avail_in has 106 The application must update next_in and avail_in when avail_in has
84 dropped to zero. It must update next_out and avail_out when avail_out 107 dropped to zero. It must update next_out and avail_out when avail_out
85 has dropped to zero. The application must initialize zalloc, zfree and 108 has dropped to zero. The application must initialize zalloc, zfree and
86 opaque before calling the init function. All other fields are set by the 109 opaque before calling the init function. All other fields are set by the
87 compression library and must not be updated by the application. 110 compression library and must not be updated by the application.
88 111
89 The opaque value provided by the application will be passed as the first 112 The opaque value provided by the application will be passed as the first
90 parameter for calls of zalloc and zfree. This can be useful for custom 113 parameter for calls of zalloc and zfree. This can be useful for custom
91 memory management. The compression library attaches no meaning to the 114 memory management. The compression library attaches no meaning to the
92 opaque value. 115 opaque value.
93 116
94 zalloc must return NULL if there is not enough memory for the object. 117 zalloc must return NULL if there is not enough memory for the object.
95 If zlib is used in a multi-threaded application, zalloc and zfree must be 118 If zlib is used in a multi-threaded application, zalloc and zfree must be
96 thread safe. 119 thread safe.
97 120
98 On 16-bit systems, the functions zalloc and zfree must be able to allocate 121 On 16-bit systems, the functions zalloc and zfree must be able to allocate
99 exactly 65536 bytes, but will not be required to allocate more than this 122 exactly 65536 bytes, but will not be required to allocate more than this
100 if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, 123 if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
101 pointers returned by zalloc for objects of exactly 65536 bytes *must* 124 pointers returned by zalloc for objects of exactly 65536 bytes *must*
102 have their offset normalized to zero. The default allocation function 125 have their offset normalized to zero. The default allocation function
103 provided by this library ensures this (see zutil.c). To reduce memory 126 provided by this library ensures this (see zutil.c). To reduce memory
104 requirements and avoid any allocation of 64K objects, at the expense of 127 requirements and avoid any allocation of 64K objects, at the expense of
105 compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). 128 compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
106 129
107 The fields total_in and total_out can be used for statistics or 130 The fields total_in and total_out can be used for statistics or
108 progress reports. After compression, total_in holds the total size of 131 progress reports. After compression, total_in holds the total size of
109 the uncompressed data and may be saved for use in the decompressor 132 the uncompressed data and may be saved for use in the decompressor
110 (particularly if the decompressor wants to decompress everything in 133 (particularly if the decompressor wants to decompress everything in
111 a single step). 134 a single step).
112 */ 135 */
113 136
114 /* constants */ 137 /* constants */
115 138
116 #define Z_NO_FLUSH 0 139 #define Z_NO_FLUSH 0
117 #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ 140 #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
118 #define Z_PACKET_FLUSH 2 141 #define Z_PACKET_FLUSH 2
119 #define Z_SYNC_FLUSH 3 142 #define Z_SYNC_FLUSH 3
120 #define Z_FULL_FLUSH 4 143 #define Z_FULL_FLUSH 4
121 #define Z_FINISH 5 144 #define Z_FINISH 5
122 /* Allowed flush values; see deflate() below for details */ 145 #define Z_BLOCK 6 /* Only for inflate at present */
146 /* Allowed flush values; see deflate() and inflate() below for details */
123 147
124 #define Z_OK 0 148 #define Z_OK 0
125 #define Z_STREAM_END 1 149 #define Z_STREAM_END 1
126 #define Z_NEED_DICT 2 150 #define Z_NEED_DICT 2
127 #define Z_ERRNO (-1) 151 #define Z_ERRNO (-1)
128 #define Z_STREAM_ERROR (-2) 152 #define Z_STREAM_ERROR (-2)
129 #define Z_DATA_ERROR (-3) 153 #define Z_DATA_ERROR (-3)
130 #define Z_MEM_ERROR (-4) 154 #define Z_MEM_ERROR (-4)
131 #define Z_BUF_ERROR (-5) 155 #define Z_BUF_ERROR (-5)
132 #define Z_VERSION_ERROR (-6) 156 #define Z_VERSION_ERROR (-6)
133 /* Return codes for the compression/decompression functions. Negative 157 /* Return codes for the compression/decompression functions. Negative
134 * values are errors, positive values are used for special but normal events. 158 * values are errors, positive values are used for special but normal events.
135 */ 159 */
136 160
137 #define Z_NO_COMPRESSION 0 161 #define Z_NO_COMPRESSION 0
138 #define Z_BEST_SPEED 1 162 #define Z_BEST_SPEED 1
139 #define Z_BEST_COMPRESSION 9 163 #define Z_BEST_COMPRESSION 9
140 #define Z_DEFAULT_COMPRESSION (-1) 164 #define Z_DEFAULT_COMPRESSION (-1)
141 /* compression levels */ 165 /* compression levels */
142 166
143 #define Z_FILTERED 1 167 #define Z_FILTERED 1
144 #define Z_HUFFMAN_ONLY 2 168 #define Z_HUFFMAN_ONLY 2
145 #define Z_DEFAULT_STRATEGY 0 169 #define Z_DEFAULT_STRATEGY 0
146 /* compression strategy; see deflateInit2() below for details */ 170 /* compression strategy; see deflateInit2() below for details */
147 171
148 #define Z_BINARY 0 172 #define Z_BINARY 0
149 #define Z_ASCII 1 173 #define Z_ASCII 1
150 #define Z_UNKNOWN 2 174 #define Z_UNKNOWN 2
151 /* Possible values of the data_type field */ 175 /* Possible values of the data_type field */
152 176
153 #define Z_DEFLATED 8 177 #define Z_DEFLATED 8
154 /* The deflate compression method (the only one supported in this version) */ 178 /* The deflate compression method (the only one supported in this version) */
155 179
156 /* basic functions */ 180 /* basic functions */
157 181
158 extern const char * zlib_zlibVersion (void);
159 /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
160 If the first character differs, the library code actually used is
161 not compatible with the zlib.h header file used by the application.
162 This check is automatically made by deflateInit and inflateInit.
163 */
164
165 extern int zlib_deflate_workspacesize (void); 182 extern int zlib_deflate_workspacesize (void);
166 /* 183 /*
167 Returns the number of bytes that needs to be allocated for a per- 184 Returns the number of bytes that needs to be allocated for a per-
168 stream workspace. A pointer to this number of bytes should be 185 stream workspace. A pointer to this number of bytes should be
169 returned in stream->workspace before calling zlib_deflateInit(). 186 returned in stream->workspace before calling zlib_deflateInit().
170 */ 187 */
171 188
172 /* 189 /*
173 extern int deflateInit (z_streamp strm, int level); 190 extern int deflateInit (z_streamp strm, int level);
174 191
175 Initializes the internal stream state for compression. The fields 192 Initializes the internal stream state for compression. The fields
176 zalloc, zfree and opaque must be initialized before by the caller. 193 zalloc, zfree and opaque must be initialized before by the caller.
177 If zalloc and zfree are set to NULL, deflateInit updates them to 194 If zalloc and zfree are set to NULL, deflateInit updates them to
178 use default allocation functions. 195 use default allocation functions.
179 196
180 The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 197 The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
181 1 gives best speed, 9 gives best compression, 0 gives no compression at 198 1 gives best speed, 9 gives best compression, 0 gives no compression at
182 all (the input data is simply copied a block at a time). 199 all (the input data is simply copied a block at a time).
183 Z_DEFAULT_COMPRESSION requests a default compromise between speed and 200 Z_DEFAULT_COMPRESSION requests a default compromise between speed and
184 compression (currently equivalent to level 6). 201 compression (currently equivalent to level 6).
185 202
186 deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not 203 deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
187 enough memory, Z_STREAM_ERROR if level is not a valid compression level, 204 enough memory, Z_STREAM_ERROR if level is not a valid compression level,
188 Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible 205 Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
189 with the version assumed by the caller (ZLIB_VERSION). 206 with the version assumed by the caller (ZLIB_VERSION).
190 msg is set to null if there is no error message. deflateInit does not 207 msg is set to null if there is no error message. deflateInit does not
191 perform any compression: this will be done by deflate(). 208 perform any compression: this will be done by deflate().
192 */ 209 */
193 210
194 211
195 extern int zlib_deflate (z_streamp strm, int flush); 212 extern int zlib_deflate (z_streamp strm, int flush);
196 /* 213 /*
197 deflate compresses as much data as possible, and stops when the input 214 deflate compresses as much data as possible, and stops when the input
198 buffer becomes empty or the output buffer becomes full. It may introduce some 215 buffer becomes empty or the output buffer becomes full. It may introduce some
199 output latency (reading input without producing any output) except when 216 output latency (reading input without producing any output) except when
200 forced to flush. 217 forced to flush.
201 218
202 The detailed semantics are as follows. deflate performs one or both of the 219 The detailed semantics are as follows. deflate performs one or both of the
203 following actions: 220 following actions:
204 221
205 - Compress more input starting at next_in and update next_in and avail_in 222 - Compress more input starting at next_in and update next_in and avail_in
206 accordingly. If not all input can be processed (because there is not 223 accordingly. If not all input can be processed (because there is not
207 enough room in the output buffer), next_in and avail_in are updated and 224 enough room in the output buffer), next_in and avail_in are updated and
208 processing will resume at this point for the next call of deflate(). 225 processing will resume at this point for the next call of deflate().
209 226
210 - Provide more output starting at next_out and update next_out and avail_out 227 - Provide more output starting at next_out and update next_out and avail_out
211 accordingly. This action is forced if the parameter flush is non zero. 228 accordingly. This action is forced if the parameter flush is non zero.
212 Forcing flush frequently degrades the compression ratio, so this parameter 229 Forcing flush frequently degrades the compression ratio, so this parameter
213 should be set only when necessary (in interactive applications). 230 should be set only when necessary (in interactive applications).
214 Some output may be provided even if flush is not set. 231 Some output may be provided even if flush is not set.
215 232
216 Before the call of deflate(), the application should ensure that at least 233 Before the call of deflate(), the application should ensure that at least
217 one of the actions is possible, by providing more input and/or consuming 234 one of the actions is possible, by providing more input and/or consuming
218 more output, and updating avail_in or avail_out accordingly; avail_out 235 more output, and updating avail_in or avail_out accordingly; avail_out
219 should never be zero before the call. The application can consume the 236 should never be zero before the call. The application can consume the
220 compressed output when it wants, for example when the output buffer is full 237 compressed output when it wants, for example when the output buffer is full
221 (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK 238 (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
222 and with zero avail_out, it must be called again after making room in the 239 and with zero avail_out, it must be called again after making room in the
223 output buffer because there might be more output pending. 240 output buffer because there might be more output pending.
224 241
225 If the parameter flush is set to Z_SYNC_FLUSH, all pending output is 242 If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
226 flushed to the output buffer and the output is aligned on a byte boundary, so 243 flushed to the output buffer and the output is aligned on a byte boundary, so
227 that the decompressor can get all input data available so far. (In particular 244 that the decompressor can get all input data available so far. (In particular
228 avail_in is zero after the call if enough output space has been provided 245 avail_in is zero after the call if enough output space has been provided
229 before the call.) Flushing may degrade compression for some compression 246 before the call.) Flushing may degrade compression for some compression
230 algorithms and so it should be used only when necessary. 247 algorithms and so it should be used only when necessary.
231 248
232 If flush is set to Z_FULL_FLUSH, all output is flushed as with 249 If flush is set to Z_FULL_FLUSH, all output is flushed as with
233 Z_SYNC_FLUSH, and the compression state is reset so that decompression can 250 Z_SYNC_FLUSH, and the compression state is reset so that decompression can
234 restart from this point if previous compressed data has been damaged or if 251 restart from this point if previous compressed data has been damaged or if
235 random access is desired. Using Z_FULL_FLUSH too often can seriously degrade 252 random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
236 the compression. 253 the compression.
237 254
238 If deflate returns with avail_out == 0, this function must be called again 255 If deflate returns with avail_out == 0, this function must be called again
239 with the same value of the flush parameter and more output space (updated 256 with the same value of the flush parameter and more output space (updated
240 avail_out), until the flush is complete (deflate returns with non-zero 257 avail_out), until the flush is complete (deflate returns with non-zero
241 avail_out). 258 avail_out).
242 259
243 If the parameter flush is set to Z_FINISH, pending input is processed, 260 If the parameter flush is set to Z_FINISH, pending input is processed,
244 pending output is flushed and deflate returns with Z_STREAM_END if there 261 pending output is flushed and deflate returns with Z_STREAM_END if there
245 was enough output space; if deflate returns with Z_OK, this function must be 262 was enough output space; if deflate returns with Z_OK, this function must be
246 called again with Z_FINISH and more output space (updated avail_out) but no 263 called again with Z_FINISH and more output space (updated avail_out) but no
247 more input data, until it returns with Z_STREAM_END or an error. After 264 more input data, until it returns with Z_STREAM_END or an error. After
248 deflate has returned Z_STREAM_END, the only possible operations on the 265 deflate has returned Z_STREAM_END, the only possible operations on the
249 stream are deflateReset or deflateEnd. 266 stream are deflateReset or deflateEnd.
250 267
251 Z_FINISH can be used immediately after deflateInit if all the compression 268 Z_FINISH can be used immediately after deflateInit if all the compression
252 is to be done in a single step. In this case, avail_out must be at least 269 is to be done in a single step. In this case, avail_out must be at least
253 0.1% larger than avail_in plus 12 bytes. If deflate does not return 270 0.1% larger than avail_in plus 12 bytes. If deflate does not return
254 Z_STREAM_END, then it must be called again as described above. 271 Z_STREAM_END, then it must be called again as described above.
255 272
256 deflate() sets strm->adler to the adler32 checksum of all input read 273 deflate() sets strm->adler to the adler32 checksum of all input read
257 so far (that is, total_in bytes). 274 so far (that is, total_in bytes).
258 275
259 deflate() may update data_type if it can make a good guess about 276 deflate() may update data_type if it can make a good guess about
260 the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered 277 the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
261 binary. This field is only for information purposes and does not affect 278 binary. This field is only for information purposes and does not affect
262 the compression algorithm in any manner. 279 the compression algorithm in any manner.
263 280
264 deflate() returns Z_OK if some progress has been made (more input 281 deflate() returns Z_OK if some progress has been made (more input
265 processed or more output produced), Z_STREAM_END if all input has been 282 processed or more output produced), Z_STREAM_END if all input has been
266 consumed and all output has been produced (only when flush is set to 283 consumed and all output has been produced (only when flush is set to
267 Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example 284 Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
268 if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible 285 if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
269 (for example avail_in or avail_out was zero). 286 (for example avail_in or avail_out was zero).
270 */ 287 */
271 288
272 289
273 extern int zlib_deflateEnd (z_streamp strm); 290 extern int zlib_deflateEnd (z_streamp strm);
274 /* 291 /*
275 All dynamically allocated data structures for this stream are freed. 292 All dynamically allocated data structures for this stream are freed.
276 This function discards any unprocessed input and does not flush any 293 This function discards any unprocessed input and does not flush any
277 pending output. 294 pending output.
278 295
279 deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the 296 deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
280 stream state was inconsistent, Z_DATA_ERROR if the stream was freed 297 stream state was inconsistent, Z_DATA_ERROR if the stream was freed
281 prematurely (some input or output was discarded). In the error case, 298 prematurely (some input or output was discarded). In the error case,
282 msg may be set but then points to a static string (which must not be 299 msg may be set but then points to a static string (which must not be
283 deallocated). 300 deallocated).
284 */ 301 */
285 302
286 303
287 extern int zlib_inflate_workspacesize (void); 304 extern int zlib_inflate_workspacesize (void);
288 /* 305 /*
289 Returns the number of bytes that needs to be allocated for a per- 306 Returns the number of bytes that needs to be allocated for a per-
290 stream workspace. A pointer to this number of bytes should be 307 stream workspace. A pointer to this number of bytes should be
291 returned in stream->workspace before calling zlib_inflateInit(). 308 returned in stream->workspace before calling zlib_inflateInit().
292 */ 309 */
293 310
294 /* 311 /*
295 extern int zlib_inflateInit (z_streamp strm); 312 extern int zlib_inflateInit (z_streamp strm);
296 313
297 Initializes the internal stream state for decompression. The fields 314 Initializes the internal stream state for decompression. The fields
298 next_in, avail_in, and workspace must be initialized before by 315 next_in, avail_in, and workspace must be initialized before by
299 the caller. If next_in is not NULL and avail_in is large enough (the exact 316 the caller. If next_in is not NULL and avail_in is large enough (the exact
300 value depends on the compression method), inflateInit determines the 317 value depends on the compression method), inflateInit determines the
301 compression method from the zlib header and allocates all data structures 318 compression method from the zlib header and allocates all data structures
302 accordingly; otherwise the allocation will be deferred to the first call of 319 accordingly; otherwise the allocation will be deferred to the first call of
303 inflate. If zalloc and zfree are set to NULL, inflateInit updates them to 320 inflate. If zalloc and zfree are set to NULL, inflateInit updates them to
304 use default allocation functions. 321 use default allocation functions.
305 322
306 inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough 323 inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
307 memory, Z_VERSION_ERROR if the zlib library version is incompatible with the 324 memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
308 version assumed by the caller. msg is set to null if there is no error 325 version assumed by the caller. msg is set to null if there is no error
309 message. inflateInit does not perform any decompression apart from reading 326 message. inflateInit does not perform any decompression apart from reading
310 the zlib header if present: this will be done by inflate(). (So next_in and 327 the zlib header if present: this will be done by inflate(). (So next_in and
311 avail_in may be modified, but next_out and avail_out are unchanged.) 328 avail_in may be modified, but next_out and avail_out are unchanged.)
312 */ 329 */
313 330
314 331
315 extern int zlib_inflate (z_streamp strm, int flush); 332 extern int zlib_inflate (z_streamp strm, int flush);
316 /* 333 /*
317 inflate decompresses as much data as possible, and stops when the input 334 inflate decompresses as much data as possible, and stops when the input
318 buffer becomes empty or the output buffer becomes full. It may some 335 buffer becomes empty or the output buffer becomes full. It may introduce
319 introduce some output latency (reading input without producing any output) 336 some output latency (reading input without producing any output) except when
320 except when forced to flush. 337 forced to flush.
321 338
322 The detailed semantics are as follows. inflate performs one or both of the 339 The detailed semantics are as follows. inflate performs one or both of the
323 following actions: 340 following actions:
324 341
325 - Decompress more input starting at next_in and update next_in and avail_in 342 - Decompress more input starting at next_in and update next_in and avail_in
326 accordingly. If not all input can be processed (because there is not 343 accordingly. If not all input can be processed (because there is not
327 enough room in the output buffer), next_in is updated and processing 344 enough room in the output buffer), next_in is updated and processing
328 will resume at this point for the next call of inflate(). 345 will resume at this point for the next call of inflate().
329 346
330 - Provide more output starting at next_out and update next_out and avail_out 347 - Provide more output starting at next_out and update next_out and avail_out
331 accordingly. inflate() provides as much output as possible, until there 348 accordingly. inflate() provides as much output as possible, until there
332 is no more input data or no more space in the output buffer (see below 349 is no more input data or no more space in the output buffer (see below
333 about the flush parameter). 350 about the flush parameter).
334 351
335 Before the call of inflate(), the application should ensure that at least 352 Before the call of inflate(), the application should ensure that at least
336 one of the actions is possible, by providing more input and/or consuming 353 one of the actions is possible, by providing more input and/or consuming
337 more output, and updating the next_* and avail_* values accordingly. 354 more output, and updating the next_* and avail_* values accordingly.
338 The application can consume the uncompressed output when it wants, for 355 The application can consume the uncompressed output when it wants, for
339 example when the output buffer is full (avail_out == 0), or after each 356 example when the output buffer is full (avail_out == 0), or after each
340 call of inflate(). If inflate returns Z_OK and with zero avail_out, it 357 call of inflate(). If inflate returns Z_OK and with zero avail_out, it
341 must be called again after making room in the output buffer because there 358 must be called again after making room in the output buffer because there
342 might be more output pending. 359 might be more output pending.
343 360
344 If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much 361 The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
345 output as possible to the output buffer. The flushing behavior of inflate is 362 Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
346 not specified for values of the flush parameter other than Z_SYNC_FLUSH 363 output as possible to the output buffer. Z_BLOCK requests that inflate() stop
347 and Z_FINISH, but the current implementation actually flushes as much output 364 if and when it gets to the next deflate block boundary. When decoding the
348 as possible anyway. 365 zlib or gzip format, this will cause inflate() to return immediately after
366 the header and before the first block. When doing a raw inflate, inflate()
367 will go ahead and process the first block, and will return when it gets to
368 the end of that block, or when it runs out of data.
349 369
370 The Z_BLOCK option assists in appending to or combining deflate streams.
371 Also to assist in this, on return inflate() will set strm->data_type to the
372 number of unused bits in the last byte taken from strm->next_in, plus 64
373 if inflate() is currently decoding the last block in the deflate stream,
374 plus 128 if inflate() returned immediately after decoding an end-of-block
375 code or decoding the complete header up to just before the first byte of the
376 deflate stream. The end-of-block will not be indicated until all of the
377 uncompressed data from that block has been written to strm->next_out. The
378 number of unused bits may in general be greater than seven, except when
379 bit 7 of data_type is set, in which case the number of unused bits will be
380 less than eight.
381
350 inflate() should normally be called until it returns Z_STREAM_END or an 382 inflate() should normally be called until it returns Z_STREAM_END or an
351 error. However if all decompression is to be performed in a single step 383 error. However if all decompression is to be performed in a single step
352 (a single call of inflate), the parameter flush should be set to 384 (a single call of inflate), the parameter flush should be set to
353 Z_FINISH. In this case all pending input is processed and all pending 385 Z_FINISH. In this case all pending input is processed and all pending
354 output is flushed; avail_out must be large enough to hold all the 386 output is flushed; avail_out must be large enough to hold all the
355 uncompressed data. (The size of the uncompressed data may have been saved 387 uncompressed data. (The size of the uncompressed data may have been saved
356 by the compressor for this purpose.) The next operation on this stream must 388 by the compressor for this purpose.) The next operation on this stream must
357 be inflateEnd to deallocate the decompression state. The use of Z_FINISH 389 be inflateEnd to deallocate the decompression state. The use of Z_FINISH
358 is never required, but can be used to inform inflate that a faster routine 390 is never required, but can be used to inform inflate that a faster approach
359 may be used for the single inflate() call. 391 may be used for the single inflate() call.
360 392
361 If a preset dictionary is needed at this point (see inflateSetDictionary 393 In this implementation, inflate() always flushes as much output as
362 below), inflate sets strm-adler to the adler32 checksum of the 394 possible to the output buffer, and always uses the faster approach on the
363 dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise 395 first call. So the only effect of the flush parameter in this implementation
364 it sets strm->adler to the adler32 checksum of all output produced 396 is on the return value of inflate(), as noted below, or when it returns early
365 so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or 397 because Z_BLOCK is used.
366 an error code as described below. At the end of the stream, inflate()
367 checks that its computed adler32 checksum is equal to that saved by the
368 compressor and returns Z_STREAM_END only if the checksum is correct.
369 398
399 If a preset dictionary is needed after this call (see inflateSetDictionary
400 below), inflate sets strm->adler to the adler32 checksum of the dictionary
401 chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
402 strm->adler to the adler32 checksum of all output produced so far (that is,
403 total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
404 below. At the end of the stream, inflate() checks that its computed adler32
405 checksum is equal to that saved by the compressor and returns Z_STREAM_END
406 only if the checksum is correct.
407
408 inflate() will decompress and check either zlib-wrapped or gzip-wrapped
409 deflate data. The header type is detected automatically. Any information
410 contained in the gzip header is not retained, so applications that need that
411 information should instead use raw inflate, see inflateInit2() below, or
412 inflateBack() and perform their own processing of the gzip header and
413 trailer.
414
370 inflate() returns Z_OK if some progress has been made (more input processed 415 inflate() returns Z_OK if some progress has been made (more input processed
371 or more output produced), Z_STREAM_END if the end of the compressed data has 416 or more output produced), Z_STREAM_END if the end of the compressed data has
372 been reached and all uncompressed output has been produced, Z_NEED_DICT if a 417 been reached and all uncompressed output has been produced, Z_NEED_DICT if a
373 preset dictionary is needed at this point, Z_DATA_ERROR if the input data was 418 preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
374 corrupted (input stream not conforming to the zlib format or incorrect 419 corrupted (input stream not conforming to the zlib format or incorrect check
375 adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent 420 value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
376 (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not 421 if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
377 enough memory, Z_BUF_ERROR if no progress is possible or if there was not 422 Z_BUF_ERROR if no progress is possible or if there was not enough room in the
378 enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR 423 output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
379 case, the application may then call inflateSync to look for a good 424 inflate() can be called again with more input and more output space to
380 compression block. 425 continue decompressing. If Z_DATA_ERROR is returned, the application may then
426 call inflateSync() to look for a good compression block if a partial recovery
427 of the data is desired.
381 */ 428 */
382 429
383 430
384 extern int zlib_inflateEnd (z_streamp strm); 431 extern int zlib_inflateEnd (z_streamp strm);
385 /* 432 /*
386 All dynamically allocated data structures for this stream are freed. 433 All dynamically allocated data structures for this stream are freed.
387 This function discards any unprocessed input and does not flush any 434 This function discards any unprocessed input and does not flush any
388 pending output. 435 pending output.
389 436
390 inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state 437 inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
391 was inconsistent. In the error case, msg may be set but then points to a 438 was inconsistent. In the error case, msg may be set but then points to a
392 static string (which must not be deallocated). 439 static string (which must not be deallocated).
393 */ 440 */
394 441
395 /* Advanced functions */ 442 /* Advanced functions */
396 443
397 /* 444 /*
398 The following functions are needed only in some special applications. 445 The following functions are needed only in some special applications.
399 */ 446 */
400 447
401 /* 448 /*
402 extern int deflateInit2 (z_streamp strm, 449 extern int deflateInit2 (z_streamp strm,
403 int level, 450 int level,
404 int method, 451 int method,
405 int windowBits, 452 int windowBits,
406 int memLevel, 453 int memLevel,
407 int strategy); 454 int strategy);
408 455
409 This is another version of deflateInit with more compression options. The 456 This is another version of deflateInit with more compression options. The
410 fields next_in, zalloc, zfree and opaque must be initialized before by 457 fields next_in, zalloc, zfree and opaque must be initialized before by
411 the caller. 458 the caller.
412 459
413 The method parameter is the compression method. It must be Z_DEFLATED in 460 The method parameter is the compression method. It must be Z_DEFLATED in
414 this version of the library. 461 this version of the library.
415 462
416 The windowBits parameter is the base two logarithm of the window size 463 The windowBits parameter is the base two logarithm of the window size
417 (the size of the history buffer). It should be in the range 8..15 for this 464 (the size of the history buffer). It should be in the range 8..15 for this
418 version of the library. Larger values of this parameter result in better 465 version of the library. Larger values of this parameter result in better
419 compression at the expense of memory usage. The default value is 15 if 466 compression at the expense of memory usage. The default value is 15 if
420 deflateInit is used instead. 467 deflateInit is used instead.
421 468
422 The memLevel parameter specifies how much memory should be allocated 469 The memLevel parameter specifies how much memory should be allocated
423 for the internal compression state. memLevel=1 uses minimum memory but 470 for the internal compression state. memLevel=1 uses minimum memory but
424 is slow and reduces compression ratio; memLevel=9 uses maximum memory 471 is slow and reduces compression ratio; memLevel=9 uses maximum memory
425 for optimal speed. The default value is 8. See zconf.h for total memory 472 for optimal speed. The default value is 8. See zconf.h for total memory
426 usage as a function of windowBits and memLevel. 473 usage as a function of windowBits and memLevel.
427 474
428 The strategy parameter is used to tune the compression algorithm. Use the 475 The strategy parameter is used to tune the compression algorithm. Use the
429 value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a 476 value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
430 filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no 477 filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no
431 string match). Filtered data consists mostly of small values with a 478 string match). Filtered data consists mostly of small values with a
432 somewhat random distribution. In this case, the compression algorithm is 479 somewhat random distribution. In this case, the compression algorithm is
433 tuned to compress them better. The effect of Z_FILTERED is to force more 480 tuned to compress them better. The effect of Z_FILTERED is to force more
434 Huffman coding and less string matching; it is somewhat intermediate 481 Huffman coding and less string matching; it is somewhat intermediate
435 between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects 482 between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects
436 the compression ratio but not the correctness of the compressed output even 483 the compression ratio but not the correctness of the compressed output even
437 if it is not set appropriately. 484 if it is not set appropriately.
438 485
439 deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough 486 deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
440 memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid 487 memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
441 method). msg is set to null if there is no error message. deflateInit2 does 488 method). msg is set to null if there is no error message. deflateInit2 does
442 not perform any compression: this will be done by deflate(). 489 not perform any compression: this will be done by deflate().
443 */ 490 */
444 491
445 #if 0 492 #if 0
446 extern int zlib_deflateSetDictionary (z_streamp strm, 493 extern int zlib_deflateSetDictionary (z_streamp strm,
447 const Byte *dictionary, 494 const Byte *dictionary,
448 uInt dictLength); 495 uInt dictLength);
449 #endif 496 #endif
450 /* 497 /*
451 Initializes the compression dictionary from the given byte sequence 498 Initializes the compression dictionary from the given byte sequence
452 without producing any compressed output. This function must be called 499 without producing any compressed output. This function must be called
453 immediately after deflateInit, deflateInit2 or deflateReset, before any 500 immediately after deflateInit, deflateInit2 or deflateReset, before any
454 call of deflate. The compressor and decompressor must use exactly the same 501 call of deflate. The compressor and decompressor must use exactly the same
455 dictionary (see inflateSetDictionary). 502 dictionary (see inflateSetDictionary).
456 503
457 The dictionary should consist of strings (byte sequences) that are likely 504 The dictionary should consist of strings (byte sequences) that are likely
458 to be encountered later in the data to be compressed, with the most commonly 505 to be encountered later in the data to be compressed, with the most commonly
459 used strings preferably put towards the end of the dictionary. Using a 506 used strings preferably put towards the end of the dictionary. Using a
460 dictionary is most useful when the data to be compressed is short and can be 507 dictionary is most useful when the data to be compressed is short and can be
461 predicted with good accuracy; the data can then be compressed better than 508 predicted with good accuracy; the data can then be compressed better than
462 with the default empty dictionary. 509 with the default empty dictionary.
463 510
464 Depending on the size of the compression data structures selected by 511 Depending on the size of the compression data structures selected by
465 deflateInit or deflateInit2, a part of the dictionary may in effect be 512 deflateInit or deflateInit2, a part of the dictionary may in effect be
466 discarded, for example if the dictionary is larger than the window size in 513 discarded, for example if the dictionary is larger than the window size in
467 deflate or deflate2. Thus the strings most likely to be useful should be 514 deflate or deflate2. Thus the strings most likely to be useful should be
468 put at the end of the dictionary, not at the front. 515 put at the end of the dictionary, not at the front.
469 516
470 Upon return of this function, strm->adler is set to the Adler32 value 517 Upon return of this function, strm->adler is set to the Adler32 value
471 of the dictionary; the decompressor may later use this value to determine 518 of the dictionary; the decompressor may later use this value to determine
472 which dictionary has been used by the compressor. (The Adler32 value 519 which dictionary has been used by the compressor. (The Adler32 value
473 applies to the whole dictionary even if only a subset of the dictionary is 520 applies to the whole dictionary even if only a subset of the dictionary is
474 actually used by the compressor.) 521 actually used by the compressor.)
475 522
476 deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a 523 deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
477 parameter is invalid (such as NULL dictionary) or the stream state is 524 parameter is invalid (such as NULL dictionary) or the stream state is
478 inconsistent (for example if deflate has already been called for this stream 525 inconsistent (for example if deflate has already been called for this stream
479 or if the compression method is bsort). deflateSetDictionary does not 526 or if the compression method is bsort). deflateSetDictionary does not
480 perform any compression: this will be done by deflate(). 527 perform any compression: this will be done by deflate().
481 */ 528 */
482 529
483 #if 0 530 #if 0
484 extern int zlib_deflateCopy (z_streamp dest, z_streamp source); 531 extern int zlib_deflateCopy (z_streamp dest, z_streamp source);
485 #endif 532 #endif
486 533
487 /* 534 /*
488 Sets the destination stream as a complete copy of the source stream. 535 Sets the destination stream as a complete copy of the source stream.
489 536
490 This function can be useful when several compression strategies will be 537 This function can be useful when several compression strategies will be
491 tried, for example when there are several ways of pre-processing the input 538 tried, for example when there are several ways of pre-processing the input
492 data with a filter. The streams that will be discarded should then be freed 539 data with a filter. The streams that will be discarded should then be freed
493 by calling deflateEnd. Note that deflateCopy duplicates the internal 540 by calling deflateEnd. Note that deflateCopy duplicates the internal
494 compression state which can be quite large, so this strategy is slow and 541 compression state which can be quite large, so this strategy is slow and
495 can consume lots of memory. 542 can consume lots of memory.
496 543
497 deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not 544 deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
498 enough memory, Z_STREAM_ERROR if the source stream state was inconsistent 545 enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
499 (such as zalloc being NULL). msg is left unchanged in both source and 546 (such as zalloc being NULL). msg is left unchanged in both source and
500 destination. 547 destination.
501 */ 548 */
502 549
503 extern int zlib_deflateReset (z_streamp strm); 550 extern int zlib_deflateReset (z_streamp strm);
504 /* 551 /*
505 This function is equivalent to deflateEnd followed by deflateInit, 552 This function is equivalent to deflateEnd followed by deflateInit,
506 but does not free and reallocate all the internal compression state. 553 but does not free and reallocate all the internal compression state.
507 The stream will keep the same compression level and any other attributes 554 The stream will keep the same compression level and any other attributes
508 that may have been set by deflateInit2. 555 that may have been set by deflateInit2.
509 556
510 deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source 557 deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
511 stream state was inconsistent (such as zalloc or state being NULL). 558 stream state was inconsistent (such as zalloc or state being NULL).
512 */ 559 */
513 560
514 static inline unsigned long deflateBound(unsigned long s) 561 static inline unsigned long deflateBound(unsigned long s)
515 { 562 {
516 return s + ((s + 7) >> 3) + ((s + 63) >> 6) + 11; 563 return s + ((s + 7) >> 3) + ((s + 63) >> 6) + 11;
517 } 564 }
518 565
519 #if 0 566 #if 0
520 extern int zlib_deflateParams (z_streamp strm, int level, int strategy); 567 extern int zlib_deflateParams (z_streamp strm, int level, int strategy);
521 #endif 568 #endif
522 /* 569 /*
523 Dynamically update the compression level and compression strategy. The 570 Dynamically update the compression level and compression strategy. The
524 interpretation of level and strategy is as in deflateInit2. This can be 571 interpretation of level and strategy is as in deflateInit2. This can be
525 used to switch between compression and straight copy of the input data, or 572 used to switch between compression and straight copy of the input data, or
526 to switch to a different kind of input data requiring a different 573 to switch to a different kind of input data requiring a different
527 strategy. If the compression level is changed, the input available so far 574 strategy. If the compression level is changed, the input available so far
528 is compressed with the old level (and may be flushed); the new level will 575 is compressed with the old level (and may be flushed); the new level will
529 take effect only at the next call of deflate(). 576 take effect only at the next call of deflate().
530 577
531 Before the call of deflateParams, the stream state must be set as for 578 Before the call of deflateParams, the stream state must be set as for
532 a call of deflate(), since the currently available input may have to 579 a call of deflate(), since the currently available input may have to
533 be compressed and flushed. In particular, strm->avail_out must be non-zero. 580 be compressed and flushed. In particular, strm->avail_out must be non-zero.
534 581
535 deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source 582 deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
536 stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR 583 stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
537 if strm->avail_out was zero. 584 if strm->avail_out was zero.
538 */ 585 */
539 586
540 /* 587 /*
541 extern int inflateInit2 (z_streamp strm, int windowBits); 588 extern int inflateInit2 (z_streamp strm, int windowBits);
542 589
543 This is another version of inflateInit with an extra parameter. The 590 This is another version of inflateInit with an extra parameter. The
544 fields next_in, avail_in, zalloc, zfree and opaque must be initialized 591 fields next_in, avail_in, zalloc, zfree and opaque must be initialized
545 before by the caller. 592 before by the caller.
546 593
547 The windowBits parameter is the base two logarithm of the maximum window 594 The windowBits parameter is the base two logarithm of the maximum window
548 size (the size of the history buffer). It should be in the range 8..15 for 595 size (the size of the history buffer). It should be in the range 8..15 for
549 this version of the library. The default value is 15 if inflateInit is used 596 this version of the library. The default value is 15 if inflateInit is used
550 instead. If a compressed stream with a larger window size is given as 597 instead. windowBits must be greater than or equal to the windowBits value
551 input, inflate() will return with the error code Z_DATA_ERROR instead of 598 provided to deflateInit2() while compressing, or it must be equal to 15 if
552 trying to allocate a larger window. 599 deflateInit2() was not used. If a compressed stream with a larger window
600 size is given as input, inflate() will return with the error code
601 Z_DATA_ERROR instead of trying to allocate a larger window.
553 602
554 inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough 603 windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
555 memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative 604 determines the window size. inflate() will then process raw deflate data,
556 memLevel). msg is set to null if there is no error message. inflateInit2 605 not looking for a zlib or gzip header, not generating a check value, and not
557 does not perform any decompression apart from reading the zlib header if 606 looking for any check values for comparison at the end of the stream. This
558 present: this will be done by inflate(). (So next_in and avail_in may be 607 is for use with other formats that use the deflate compressed data format
559 modified, but next_out and avail_out are unchanged.) 608 such as zip. Those formats provide their own check values. If a custom
609 format is developed using the raw deflate format for compressed data, it is
610 recommended that a check value such as an adler32 or a crc32 be applied to
611 the uncompressed data as is done in the zlib, gzip, and zip formats. For
612 most applications, the zlib format should be used as is. Note that comments
613 above on the use in deflateInit2() applies to the magnitude of windowBits.
614
615 windowBits can also be greater than 15 for optional gzip decoding. Add
616 32 to windowBits to enable zlib and gzip decoding with automatic header
617 detection, or add 16 to decode only the gzip format (the zlib format will
618 return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
619 a crc32 instead of an adler32.
620
621 inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
622 memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
623 is set to null if there is no error message. inflateInit2 does not perform
624 any decompression apart from reading the zlib header if present: this will
625 be done by inflate(). (So next_in and avail_in may be modified, but next_out
626 and avail_out are unchanged.)
560 */ 627 */
561 628
562 extern int zlib_inflateSetDictionary (z_streamp strm, 629 extern int zlib_inflateSetDictionary (z_streamp strm,
563 const Byte *dictionary, 630 const Byte *dictionary,
564 uInt dictLength); 631 uInt dictLength);
565 /* 632 /*
566 Initializes the decompression dictionary from the given uncompressed byte 633 Initializes the decompression dictionary from the given uncompressed byte
567 sequence. This function must be called immediately after a call of inflate 634 sequence. This function must be called immediately after a call of inflate,
568 if this call returned Z_NEED_DICT. The dictionary chosen by the compressor 635 if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
569 can be determined from the Adler32 value returned by this call of 636 can be determined from the adler32 value returned by that call of inflate.
570 inflate. The compressor and decompressor must use exactly the same 637 The compressor and decompressor must use exactly the same dictionary (see
571 dictionary (see deflateSetDictionary). 638 deflateSetDictionary). For raw inflate, this function can be called
639 immediately after inflateInit2() or inflateReset() and before any call of
640 inflate() to set the dictionary. The application must insure that the
641 dictionary that was used for compression is provided.
572 642
573 inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a 643 inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
574 parameter is invalid (such as NULL dictionary) or the stream state is 644 parameter is invalid (such as NULL dictionary) or the stream state is
575 inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the 645 inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
576 expected one (incorrect Adler32 value). inflateSetDictionary does not 646 expected one (incorrect adler32 value). inflateSetDictionary does not
577 perform any decompression: this will be done by subsequent calls of 647 perform any decompression: this will be done by subsequent calls of
578 inflate(). 648 inflate().
579 */ 649 */
580 650
581 #if 0 651 #if 0
582 extern int zlib_inflateSync (z_streamp strm); 652 extern int zlib_inflateSync (z_streamp strm);
583 #endif 653 #endif
584 /* 654 /*
585 Skips invalid compressed data until a full flush point (see above the 655 Skips invalid compressed data until a full flush point (see above the
586 description of deflate with Z_FULL_FLUSH) can be found, or until all 656 description of deflate with Z_FULL_FLUSH) can be found, or until all
587 available input is skipped. No output is provided. 657 available input is skipped. No output is provided.
588 658
589 inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR 659 inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
590 if no more input was provided, Z_DATA_ERROR if no flush point has been found, 660 if no more input was provided, Z_DATA_ERROR if no flush point has been found,
591 or Z_STREAM_ERROR if the stream structure was inconsistent. In the success 661 or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
592 case, the application may save the current current value of total_in which 662 case, the application may save the current current value of total_in which
593 indicates where valid compressed data was found. In the error case, the 663 indicates where valid compressed data was found. In the error case, the
594 application may repeatedly call inflateSync, providing more input each time, 664 application may repeatedly call inflateSync, providing more input each time,
595 until success or end of the input data. 665 until success or end of the input data.
596 */ 666 */
597 667
598 extern int zlib_inflateReset (z_streamp strm); 668 extern int zlib_inflateReset (z_streamp strm);
599 /* 669 /*
600 This function is equivalent to inflateEnd followed by inflateInit, 670 This function is equivalent to inflateEnd followed by inflateInit,
601 but does not free and reallocate all the internal decompression state. 671 but does not free and reallocate all the internal decompression state.
602 The stream will keep attributes that may have been set by inflateInit2. 672 The stream will keep attributes that may have been set by inflateInit2.
603 673
604 inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source 674 inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
605 stream state was inconsistent (such as zalloc or state being NULL). 675 stream state was inconsistent (such as zalloc or state being NULL).
606 */ 676 */
607 677
608 extern int zlib_inflateIncomp (z_stream *strm); 678 extern int zlib_inflateIncomp (z_stream *strm);
609 /* 679 /*
610 This function adds the data at next_in (avail_in bytes) to the output 680 This function adds the data at next_in (avail_in bytes) to the output
611 history without performing any output. There must be no pending output, 681 history without performing any output. There must be no pending output,
612 and the decompressor must be expecting to see the start of a block. 682 and the decompressor must be expecting to see the start of a block.
613 Calling this function is equivalent to decompressing a stored block 683 Calling this function is equivalent to decompressing a stored block
614 containing the data at next_in (except that the data is not output). 684 containing the data at next_in (except that the data is not output).
615 */ 685 */
616 686
617 /* various hacks, don't look :) */
618
619 /* deflateInit and inflateInit are macros to allow checking the zlib version
620 * and the compiler's view of z_stream:
621 */
622 extern int zlib_deflateInit_ (z_streamp strm, int level,
include/linux/zutil.h
1 /* zutil.h -- internal interface and configuration of the compression library 1 /* zutil.h -- internal interface and configuration of the compression library
2 * Copyright (C) 1995-1998 Jean-loup Gailly. 2 * Copyright (C) 1995-1998 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6 /* WARNING: this file should *not* be used by applications. It is 6 /* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is 7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h. 8 subject to change. Applications should only use zlib.h.
9 */ 9 */
10 10
11 /* @(#) $Id: zutil.h,v 1.1 2000/01/01 03:32:23 davem Exp $ */ 11 /* @(#) $Id: zutil.h,v 1.1 2000/01/01 03:32:23 davem Exp $ */
12 12
13 #ifndef _Z_UTIL_H 13 #ifndef _Z_UTIL_H
14 #define _Z_UTIL_H 14 #define _Z_UTIL_H
15 15
16 #include <linux/zlib.h> 16 #include <linux/zlib.h>
17 #include <linux/string.h> 17 #include <linux/string.h>
18 #include <linux/kernel.h> 18 #include <linux/kernel.h>
19 19
20 typedef unsigned char uch; 20 typedef unsigned char uch;
21 typedef unsigned short ush; 21 typedef unsigned short ush;
22 typedef unsigned long ulg; 22 typedef unsigned long ulg;
23 23
24 /* common constants */ 24 /* common constants */
25 25
26 #ifndef DEF_WBITS
27 # define DEF_WBITS MAX_WBITS
28 #endif
29 /* default windowBits for decompression. MAX_WBITS is for compression only */
30
31 #if MAX_MEM_LEVEL >= 8
32 # define DEF_MEM_LEVEL 8
33 #else
34 # define DEF_MEM_LEVEL MAX_MEM_LEVEL
35 #endif
36 /* default memLevel */
37
38 #define STORED_BLOCK 0 26 #define STORED_BLOCK 0
39 #define STATIC_TREES 1 27 #define STATIC_TREES 1
40 #define DYN_TREES 2 28 #define DYN_TREES 2
41 /* The three kinds of block type */ 29 /* The three kinds of block type */
42 30
43 #define MIN_MATCH 3 31 #define MIN_MATCH 3
44 #define MAX_MATCH 258 32 #define MAX_MATCH 258
45 /* The minimum and maximum match lengths */ 33 /* The minimum and maximum match lengths */
46 34
47 #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ 35 #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
48 36
49 /* target dependencies */ 37 /* target dependencies */
50 38
51 /* Common defaults */ 39 /* Common defaults */
52 40
53 #ifndef OS_CODE 41 #ifndef OS_CODE
54 # define OS_CODE 0x03 /* assume Unix */ 42 # define OS_CODE 0x03 /* assume Unix */
55 #endif 43 #endif
56 44
57 /* functions */ 45 /* functions */
58 46
59 typedef uLong (*check_func) (uLong check, const Byte *buf, 47 typedef uLong (*check_func) (uLong check, const Byte *buf,
60 uInt len); 48 uInt len);
61 49
62 50
63 /* checksum functions */ 51 /* checksum functions */
64 52
65 #define BASE 65521L /* largest prime smaller than 65536 */ 53 #define BASE 65521L /* largest prime smaller than 65536 */
66 #define NMAX 5552 54 #define NMAX 5552
67 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ 55 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
68 56
69 #define DO1(buf,i) {s1 += buf[i]; s2 += s1;} 57 #define DO1(buf,i) {s1 += buf[i]; s2 += s1;}
70 #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); 58 #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
71 #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); 59 #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
72 #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); 60 #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
73 #define DO16(buf) DO8(buf,0); DO8(buf,8); 61 #define DO16(buf) DO8(buf,0); DO8(buf,8);
74 62
75 /* ========================================================================= */ 63 /* ========================================================================= */
76 /* 64 /*
77 Update a running Adler-32 checksum with the bytes buf[0..len-1] and 65 Update a running Adler-32 checksum with the bytes buf[0..len-1] and
78 return the updated checksum. If buf is NULL, this function returns 66 return the updated checksum. If buf is NULL, this function returns
79 the required initial value for the checksum. 67 the required initial value for the checksum.
80 An Adler-32 checksum is almost as reliable as a CRC32 but can be computed 68 An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
81 much faster. Usage example: 69 much faster. Usage example:
82 70
83 uLong adler = adler32(0L, NULL, 0); 71 uLong adler = adler32(0L, NULL, 0);
84 72
85 while (read_buffer(buffer, length) != EOF) { 73 while (read_buffer(buffer, length) != EOF) {
86 adler = adler32(adler, buffer, length); 74 adler = adler32(adler, buffer, length);
87 } 75 }
88 if (adler != original_adler) error(); 76 if (adler != original_adler) error();
89 */ 77 */
90 static inline uLong zlib_adler32(uLong adler, 78 static inline uLong zlib_adler32(uLong adler,
91 const Byte *buf, 79 const Byte *buf,
92 uInt len) 80 uInt len)
93 { 81 {
94 unsigned long s1 = adler & 0xffff; 82 unsigned long s1 = adler & 0xffff;
95 unsigned long s2 = (adler >> 16) & 0xffff; 83 unsigned long s2 = (adler >> 16) & 0xffff;
96 int k; 84 int k;
97 85
98 if (buf == NULL) return 1L; 86 if (buf == NULL) return 1L;
99 87
100 while (len > 0) { 88 while (len > 0) {
101 k = len < NMAX ? len : NMAX; 89 k = len < NMAX ? len : NMAX;
102 len -= k; 90 len -= k;
103 while (k >= 16) { 91 while (k >= 16) {
104 DO16(buf); 92 DO16(buf);
105 buf += 16; 93 buf += 16;
106 k -= 16; 94 k -= 16;
107 } 95 }
108 if (k != 0) do { 96 if (k != 0) do {
109 s1 += *buf++; 97 s1 += *buf++;
110 s2 += s1; 98 s2 += s1;
111 } while (--k); 99 } while (--k);
112 s1 %= BASE; 100 s1 %= BASE;
113 s2 %= BASE; 101 s2 %= BASE;
114 } 102 }
115 return (s2 << 16) | s1; 103 return (s2 << 16) | s1;
116 } 104 }
117 105
118 #endif /* _Z_UTIL_H */ 106 #endif /* _Z_UTIL_H */
119 107
lib/zlib_deflate/deflate.c
1 /* +++ deflate.c */ 1 /* +++ deflate.c */
2 /* deflate.c -- compress data using the deflation algorithm 2 /* deflate.c -- compress data using the deflation algorithm
3 * Copyright (C) 1995-1996 Jean-loup Gailly. 3 * Copyright (C) 1995-1996 Jean-loup Gailly.
4 * For conditions of distribution and use, see copyright notice in zlib.h 4 * For conditions of distribution and use, see copyright notice in zlib.h
5 */ 5 */
6 6
7 /* 7 /*
8 * ALGORITHM 8 * ALGORITHM
9 * 9 *
10 * The "deflation" process depends on being able to identify portions 10 * The "deflation" process depends on being able to identify portions
11 * of the input text which are identical to earlier input (within a 11 * of the input text which are identical to earlier input (within a
12 * sliding window trailing behind the input currently being processed). 12 * sliding window trailing behind the input currently being processed).
13 * 13 *
14 * The most straightforward technique turns out to be the fastest for 14 * The most straightforward technique turns out to be the fastest for
15 * most input files: try all possible matches and select the longest. 15 * most input files: try all possible matches and select the longest.
16 * The key feature of this algorithm is that insertions into the string 16 * The key feature of this algorithm is that insertions into the string
17 * dictionary are very simple and thus fast, and deletions are avoided 17 * dictionary are very simple and thus fast, and deletions are avoided
18 * completely. Insertions are performed at each input character, whereas 18 * completely. Insertions are performed at each input character, whereas
19 * string matches are performed only when the previous match ends. So it 19 * string matches are performed only when the previous match ends. So it
20 * is preferable to spend more time in matches to allow very fast string 20 * is preferable to spend more time in matches to allow very fast string
21 * insertions and avoid deletions. The matching algorithm for small 21 * insertions and avoid deletions. The matching algorithm for small
22 * strings is inspired from that of Rabin & Karp. A brute force approach 22 * strings is inspired from that of Rabin & Karp. A brute force approach
23 * is used to find longer strings when a small match has been found. 23 * is used to find longer strings when a small match has been found.
24 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze 24 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
25 * (by Leonid Broukhis). 25 * (by Leonid Broukhis).
26 * A previous version of this file used a more sophisticated algorithm 26 * A previous version of this file used a more sophisticated algorithm
27 * (by Fiala and Greene) which is guaranteed to run in linear amortized 27 * (by Fiala and Greene) which is guaranteed to run in linear amortized
28 * time, but has a larger average cost, uses more memory and is patented. 28 * time, but has a larger average cost, uses more memory and is patented.
29 * However the F&G algorithm may be faster for some highly redundant 29 * However the F&G algorithm may be faster for some highly redundant
30 * files if the parameter max_chain_length (described below) is too large. 30 * files if the parameter max_chain_length (described below) is too large.
31 * 31 *
32 * ACKNOWLEDGEMENTS 32 * ACKNOWLEDGEMENTS
33 * 33 *
34 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and 34 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
35 * I found it in 'freeze' written by Leonid Broukhis. 35 * I found it in 'freeze' written by Leonid Broukhis.
36 * Thanks to many people for bug reports and testing. 36 * Thanks to many people for bug reports and testing.
37 * 37 *
38 * REFERENCES 38 * REFERENCES
39 * 39 *
40 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". 40 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
41 * Available in ftp://ds.internic.net/rfc/rfc1951.txt 41 * Available in ftp://ds.internic.net/rfc/rfc1951.txt
42 * 42 *
43 * A description of the Rabin and Karp algorithm is given in the book 43 * A description of the Rabin and Karp algorithm is given in the book
44 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. 44 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
45 * 45 *
46 * Fiala,E.R., and Greene,D.H. 46 * Fiala,E.R., and Greene,D.H.
47 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 47 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
48 * 48 *
49 */ 49 */
50 50
51 #include <linux/module.h> 51 #include <linux/module.h>
52 #include <linux/zutil.h> 52 #include <linux/zutil.h>
53 #include "defutil.h" 53 #include "defutil.h"
54 54
55 55
56 /* =========================================================================== 56 /* ===========================================================================
57 * Function prototypes. 57 * Function prototypes.
58 */ 58 */
59 typedef enum { 59 typedef enum {
60 need_more, /* block not completed, need more input or more output */ 60 need_more, /* block not completed, need more input or more output */
61 block_done, /* block flush performed */ 61 block_done, /* block flush performed */
62 finish_started, /* finish started, need only more output at next deflate */ 62 finish_started, /* finish started, need only more output at next deflate */
63 finish_done /* finish done, accept no more input or output */ 63 finish_done /* finish done, accept no more input or output */
64 } block_state; 64 } block_state;
65 65
66 typedef block_state (*compress_func) (deflate_state *s, int flush); 66 typedef block_state (*compress_func) (deflate_state *s, int flush);
67 /* Compression function. Returns the block state after the call. */ 67 /* Compression function. Returns the block state after the call. */
68 68
69 static void fill_window (deflate_state *s); 69 static void fill_window (deflate_state *s);
70 static block_state deflate_stored (deflate_state *s, int flush); 70 static block_state deflate_stored (deflate_state *s, int flush);
71 static block_state deflate_fast (deflate_state *s, int flush); 71 static block_state deflate_fast (deflate_state *s, int flush);
72 static block_state deflate_slow (deflate_state *s, int flush); 72 static block_state deflate_slow (deflate_state *s, int flush);
73 static void lm_init (deflate_state *s); 73 static void lm_init (deflate_state *s);
74 static void putShortMSB (deflate_state *s, uInt b); 74 static void putShortMSB (deflate_state *s, uInt b);
75 static void flush_pending (z_streamp strm); 75 static void flush_pending (z_streamp strm);
76 static int read_buf (z_streamp strm, Byte *buf, unsigned size); 76 static int read_buf (z_streamp strm, Byte *buf, unsigned size);
77 static uInt longest_match (deflate_state *s, IPos cur_match); 77 static uInt longest_match (deflate_state *s, IPos cur_match);
78 78
79 #ifdef DEBUG_ZLIB 79 #ifdef DEBUG_ZLIB
80 static void check_match (deflate_state *s, IPos start, IPos match, 80 static void check_match (deflate_state *s, IPos start, IPos match,
81 int length); 81 int length);
82 #endif 82 #endif
83 83
84 /* =========================================================================== 84 /* ===========================================================================
85 * Local data 85 * Local data
86 */ 86 */
87 87
88 #define NIL 0 88 #define NIL 0
89 /* Tail of hash chains */ 89 /* Tail of hash chains */
90 90
91 #ifndef TOO_FAR 91 #ifndef TOO_FAR
92 # define TOO_FAR 4096 92 # define TOO_FAR 4096
93 #endif 93 #endif
94 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ 94 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
95 95
96 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) 96 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
97 /* Minimum amount of lookahead, except at the end of the input file. 97 /* Minimum amount of lookahead, except at the end of the input file.
98 * See deflate.c for comments about the MIN_MATCH+1. 98 * See deflate.c for comments about the MIN_MATCH+1.
99 */ 99 */
100 100
101 /* Values for max_lazy_match, good_match and max_chain_length, depending on 101 /* Values for max_lazy_match, good_match and max_chain_length, depending on
102 * the desired pack level (0..9). The values given below have been tuned to 102 * the desired pack level (0..9). The values given below have been tuned to
103 * exclude worst case performance for pathological files. Better values may be 103 * exclude worst case performance for pathological files. Better values may be
104 * found for specific files. 104 * found for specific files.
105 */ 105 */
106 typedef struct config_s { 106 typedef struct config_s {
107 ush good_length; /* reduce lazy search above this match length */ 107 ush good_length; /* reduce lazy search above this match length */
108 ush max_lazy; /* do not perform lazy search above this match length */ 108 ush max_lazy; /* do not perform lazy search above this match length */
109 ush nice_length; /* quit search above this match length */ 109 ush nice_length; /* quit search above this match length */
110 ush max_chain; 110 ush max_chain;
111 compress_func func; 111 compress_func func;
112 } config; 112 } config;
113 113
114 static const config configuration_table[10] = { 114 static const config configuration_table[10] = {
115 /* good lazy nice chain */ 115 /* good lazy nice chain */
116 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ 116 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
117 /* 1 */ {4, 4, 8, 4, deflate_fast}, /* maximum speed, no lazy matches */ 117 /* 1 */ {4, 4, 8, 4, deflate_fast}, /* maximum speed, no lazy matches */
118 /* 2 */ {4, 5, 16, 8, deflate_fast}, 118 /* 2 */ {4, 5, 16, 8, deflate_fast},
119 /* 3 */ {4, 6, 32, 32, deflate_fast}, 119 /* 3 */ {4, 6, 32, 32, deflate_fast},
120 120
121 /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ 121 /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
122 /* 5 */ {8, 16, 32, 32, deflate_slow}, 122 /* 5 */ {8, 16, 32, 32, deflate_slow},
123 /* 6 */ {8, 16, 128, 128, deflate_slow}, 123 /* 6 */ {8, 16, 128, 128, deflate_slow},
124 /* 7 */ {8, 32, 128, 256, deflate_slow}, 124 /* 7 */ {8, 32, 128, 256, deflate_slow},
125 /* 8 */ {32, 128, 258, 1024, deflate_slow}, 125 /* 8 */ {32, 128, 258, 1024, deflate_slow},
126 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */ 126 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */
127 127
128 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 128 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
129 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different 129 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
130 * meaning. 130 * meaning.
131 */ 131 */
132 132
133 #define EQUAL 0 133 #define EQUAL 0
134 /* result of memcmp for equal strings */ 134 /* result of memcmp for equal strings */
135 135
136 /* =========================================================================== 136 /* ===========================================================================
137 * Update a hash value with the given input byte 137 * Update a hash value with the given input byte
138 * IN assertion: all calls to to UPDATE_HASH are made with consecutive 138 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
139 * input characters, so that a running hash key can be computed from the 139 * input characters, so that a running hash key can be computed from the
140 * previous key instead of complete recalculation each time. 140 * previous key instead of complete recalculation each time.
141 */ 141 */
142 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask) 142 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
143 143
144 144
145 /* =========================================================================== 145 /* ===========================================================================
146 * Insert string str in the dictionary and set match_head to the previous head 146 * Insert string str in the dictionary and set match_head to the previous head
147 * of the hash chain (the most recent string with same hash key). Return 147 * of the hash chain (the most recent string with same hash key). Return
148 * the previous length of the hash chain. 148 * the previous length of the hash chain.
149 * IN assertion: all calls to to INSERT_STRING are made with consecutive 149 * IN assertion: all calls to to INSERT_STRING are made with consecutive
150 * input characters and the first MIN_MATCH bytes of str are valid 150 * input characters and the first MIN_MATCH bytes of str are valid
151 * (except for the last MIN_MATCH-1 bytes of the input file). 151 * (except for the last MIN_MATCH-1 bytes of the input file).
152 */ 152 */
153 #define INSERT_STRING(s, str, match_head) \ 153 #define INSERT_STRING(s, str, match_head) \
154 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ 154 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
155 s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \ 155 s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
156 s->head[s->ins_h] = (Pos)(str)) 156 s->head[s->ins_h] = (Pos)(str))
157 157
158 /* =========================================================================== 158 /* ===========================================================================
159 * Initialize the hash table (avoiding 64K overflow for 16 bit systems). 159 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
160 * prev[] will be initialized on the fly. 160 * prev[] will be initialized on the fly.
161 */ 161 */
162 #define CLEAR_HASH(s) \ 162 #define CLEAR_HASH(s) \
163 s->head[s->hash_size-1] = NIL; \ 163 s->head[s->hash_size-1] = NIL; \
164 memset((char *)s->head, 0, (unsigned)(s->hash_size-1)*sizeof(*s->head)); 164 memset((char *)s->head, 0, (unsigned)(s->hash_size-1)*sizeof(*s->head));
165 165
166 /* ========================================================================= */ 166 /* ========================================================================= */
167 int zlib_deflateInit_( 167 int zlib_deflateInit2(
168 z_streamp strm, 168 z_streamp strm,
169 int level,
170 const char *version,
171 int stream_size
172 )
173 {
174 return zlib_deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS,
175 DEF_MEM_LEVEL,
176 Z_DEFAULT_STRATEGY, version, stream_size);
177 /* To do: ignore strm->next_in if we use it as window */
178 }
179
180 /* ========================================================================= */
181 int zlib_deflateInit2_(
182 z_streamp strm,
183 int level, 169 int level,
184 int method, 170 int method,
185 int windowBits, 171 int windowBits,
186 int memLevel, 172 int memLevel,
187 int strategy, 173 int strategy
188 const char *version,
189 int stream_size
190 ) 174 )
191 { 175 {
192 deflate_state *s; 176 deflate_state *s;
193 int noheader = 0; 177 int noheader = 0;
194 static char* my_version = ZLIB_VERSION;
195 deflate_workspace *mem; 178 deflate_workspace *mem;
196 179
197 ush *overlay; 180 ush *overlay;
198 /* We overlay pending_buf and d_buf+l_buf. This works since the average 181 /* We overlay pending_buf and d_buf+l_buf. This works since the average
199 * output size for (length,distance) codes is <= 24 bits. 182 * output size for (length,distance) codes is <= 24 bits.
200 */ 183 */
201 184
202 if (version == NULL || version[0] != my_version[0] ||
203 stream_size != sizeof(z_stream)) {
204 return Z_VERSION_ERROR;
205 }
206 if (strm == NULL) return Z_STREAM_ERROR; 185 if (strm == NULL) return Z_STREAM_ERROR;
207 186
208 strm->msg = NULL; 187 strm->msg = NULL;
209 188
210 if (level == Z_DEFAULT_COMPRESSION) level = 6; 189 if (level == Z_DEFAULT_COMPRESSION) level = 6;
211 190
212 mem = (deflate_workspace *) strm->workspace; 191 mem = (deflate_workspace *) strm->workspace;
213 192
214 if (windowBits < 0) { /* undocumented feature: suppress zlib header */ 193 if (windowBits < 0) { /* undocumented feature: suppress zlib header */
215 noheader = 1; 194 noheader = 1;
216 windowBits = -windowBits; 195 windowBits = -windowBits;
217 } 196 }
218 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || 197 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
219 windowBits < 9 || windowBits > 15 || level < 0 || level > 9 || 198 windowBits < 9 || windowBits > 15 || level < 0 || level > 9 ||
220 strategy < 0 || strategy > Z_HUFFMAN_ONLY) { 199 strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
221 return Z_STREAM_ERROR; 200 return Z_STREAM_ERROR;
222 } 201 }
223 s = (deflate_state *) &(mem->deflate_memory); 202 s = (deflate_state *) &(mem->deflate_memory);
224 strm->state = (struct internal_state *)s; 203 strm->state = (struct internal_state *)s;
225 s->strm = strm; 204 s->strm = strm;
226 205
227 s->noheader = noheader; 206 s->noheader = noheader;
228 s->w_bits = windowBits; 207 s->w_bits = windowBits;
229 s->w_size = 1 << s->w_bits; 208 s->w_size = 1 << s->w_bits;
230 s->w_mask = s->w_size - 1; 209 s->w_mask = s->w_size - 1;
231 210
232 s->hash_bits = memLevel + 7; 211 s->hash_bits = memLevel + 7;
233 s->hash_size = 1 << s->hash_bits; 212 s->hash_size = 1 << s->hash_bits;
234 s->hash_mask = s->hash_size - 1; 213 s->hash_mask = s->hash_size - 1;
235 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); 214 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
236 215
237 s->window = (Byte *) mem->window_memory; 216 s->window = (Byte *) mem->window_memory;
238 s->prev = (Pos *) mem->prev_memory; 217 s->prev = (Pos *) mem->prev_memory;
239 s->head = (Pos *) mem->head_memory; 218 s->head = (Pos *) mem->head_memory;
240 219
241 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ 220 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
242 221
243 overlay = (ush *) mem->overlay_memory; 222 overlay = (ush *) mem->overlay_memory;
244 s->pending_buf = (uch *) overlay; 223 s->pending_buf = (uch *) overlay;
245 s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); 224 s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
246 225
247 s->d_buf = overlay + s->lit_bufsize/sizeof(ush); 226 s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
248 s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; 227 s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
249 228
250 s->level = level; 229 s->level = level;
251 s->strategy = strategy; 230 s->strategy = strategy;
252 s->method = (Byte)method; 231 s->method = (Byte)method;
253 232
254 return zlib_deflateReset(strm); 233 return zlib_deflateReset(strm);
255 } 234 }
256 235
257 /* ========================================================================= */ 236 /* ========================================================================= */
258 #if 0 237 #if 0
259 int zlib_deflateSetDictionary( 238 int zlib_deflateSetDictionary(
260 z_streamp strm, 239 z_streamp strm,
261 const Byte *dictionary, 240 const Byte *dictionary,
262 uInt dictLength 241 uInt dictLength
263 ) 242 )
264 { 243 {
265 deflate_state *s; 244 deflate_state *s;
266 uInt length = dictLength; 245 uInt length = dictLength;
267 uInt n; 246 uInt n;
268 IPos hash_head = 0; 247 IPos hash_head = 0;
269 248
270 if (strm == NULL || strm->state == NULL || dictionary == NULL) 249 if (strm == NULL || strm->state == NULL || dictionary == NULL)
271 return Z_STREAM_ERROR; 250 return Z_STREAM_ERROR;
272 251
273 s = (deflate_state *) strm->state; 252 s = (deflate_state *) strm->state;
274 if (s->status != INIT_STATE) return Z_STREAM_ERROR; 253 if (s->status != INIT_STATE) return Z_STREAM_ERROR;
275 254
276 strm->adler = zlib_adler32(strm->adler, dictionary, dictLength); 255 strm->adler = zlib_adler32(strm->adler, dictionary, dictLength);
277 256
278 if (length < MIN_MATCH) return Z_OK; 257 if (length < MIN_MATCH) return Z_OK;
279 if (length > MAX_DIST(s)) { 258 if (length > MAX_DIST(s)) {
280 length = MAX_DIST(s); 259 length = MAX_DIST(s);
281 #ifndef USE_DICT_HEAD 260 #ifndef USE_DICT_HEAD
282 dictionary += dictLength - length; /* use the tail of the dictionary */ 261 dictionary += dictLength - length; /* use the tail of the dictionary */
283 #endif 262 #endif
284 } 263 }
285 memcpy((char *)s->window, dictionary, length); 264 memcpy((char *)s->window, dictionary, length);
286 s->strstart = length; 265 s->strstart = length;
287 s->block_start = (long)length; 266 s->block_start = (long)length;
288 267
289 /* Insert all strings in the hash table (except for the last two bytes). 268 /* Insert all strings in the hash table (except for the last two bytes).
290 * s->lookahead stays null, so s->ins_h will be recomputed at the next 269 * s->lookahead stays null, so s->ins_h will be recomputed at the next
291 * call of fill_window. 270 * call of fill_window.
292 */ 271 */
293 s->ins_h = s->window[0]; 272 s->ins_h = s->window[0];
294 UPDATE_HASH(s, s->ins_h, s->window[1]); 273 UPDATE_HASH(s, s->ins_h, s->window[1]);
295 for (n = 0; n <= length - MIN_MATCH; n++) { 274 for (n = 0; n <= length - MIN_MATCH; n++) {
296 INSERT_STRING(s, n, hash_head); 275 INSERT_STRING(s, n, hash_head);
297 } 276 }
298 if (hash_head) hash_head = 0; /* to make compiler happy */ 277 if (hash_head) hash_head = 0; /* to make compiler happy */
299 return Z_OK; 278 return Z_OK;
300 } 279 }
301 #endif /* 0 */ 280 #endif /* 0 */
302 281
303 /* ========================================================================= */ 282 /* ========================================================================= */
304 int zlib_deflateReset( 283 int zlib_deflateReset(
305 z_streamp strm 284 z_streamp strm
306 ) 285 )
307 { 286 {
308 deflate_state *s; 287 deflate_state *s;
309 288
310 if (strm == NULL || strm->state == NULL) 289 if (strm == NULL || strm->state == NULL)
311 return Z_STREAM_ERROR; 290 return Z_STREAM_ERROR;
312 291
313 strm->total_in = strm->total_out = 0; 292 strm->total_in = strm->total_out = 0;
314 strm->msg = NULL; 293 strm->msg = NULL;
315 strm->data_type = Z_UNKNOWN; 294 strm->data_type = Z_UNKNOWN;
316 295
317 s = (deflate_state *)strm->state; 296 s = (deflate_state *)strm->state;
318 s->pending = 0; 297 s->pending = 0;
319 s->pending_out = s->pending_buf; 298 s->pending_out = s->pending_buf;
320 299
321 if (s->noheader < 0) { 300 if (s->noheader < 0) {
322 s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */ 301 s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */
323 } 302 }
324 s->status = s->noheader ? BUSY_STATE : INIT_STATE; 303 s->status = s->noheader ? BUSY_STATE : INIT_STATE;
325 strm->adler = 1; 304 strm->adler = 1;
326 s->last_flush = Z_NO_FLUSH; 305 s->last_flush = Z_NO_FLUSH;
327 306
328 zlib_tr_init(s); 307 zlib_tr_init(s);
329 lm_init(s); 308 lm_init(s);
330 309
331 return Z_OK; 310 return Z_OK;
332 } 311 }
333 312
334 /* ========================================================================= */ 313 /* ========================================================================= */
335 #if 0 314 #if 0
336 int zlib_deflateParams( 315 int zlib_deflateParams(
337 z_streamp strm, 316 z_streamp strm,
338 int level, 317 int level,
339 int strategy 318 int strategy
340 ) 319 )
341 { 320 {
342 deflate_state *s; 321 deflate_state *s;
343 compress_func func; 322 compress_func func;
344 int err = Z_OK; 323 int err = Z_OK;
345 324
346 if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR; 325 if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR;
347 s = (deflate_state *) strm->state; 326 s = (deflate_state *) strm->state;
348 327
349 if (level == Z_DEFAULT_COMPRESSION) { 328 if (level == Z_DEFAULT_COMPRESSION) {
350 level = 6; 329 level = 6;
351 } 330 }
352 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) { 331 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
353 return Z_STREAM_ERROR; 332 return Z_STREAM_ERROR;
354 } 333 }
355 func = configuration_table[s->level].func; 334 func = configuration_table[s->level].func;
356 335
357 if (func != configuration_table[level].func && strm->total_in != 0) { 336 if (func != configuration_table[level].func && strm->total_in != 0) {
358 /* Flush the last buffer: */ 337 /* Flush the last buffer: */
359 err = zlib_deflate(strm, Z_PARTIAL_FLUSH); 338 err = zlib_deflate(strm, Z_PARTIAL_FLUSH);
360 } 339 }
361 if (s->level != level) { 340 if (s->level != level) {
362 s->level = level; 341 s->level = level;
363 s->max_lazy_match = configuration_table[level].max_lazy; 342 s->max_lazy_match = configuration_table[level].max_lazy;
364 s->good_match = configuration_table[level].good_length; 343 s->good_match = configuration_table[level].good_length;
365 s->nice_match = configuration_table[level].nice_length; 344 s->nice_match = configuration_table[level].nice_length;
366 s->max_chain_length = configuration_table[level].max_chain; 345 s->max_chain_length = configuration_table[level].max_chain;
367 } 346 }
368 s->strategy = strategy; 347 s->strategy = strategy;
369 return err; 348 return err;
370 } 349 }
371 #endif /* 0 */ 350 #endif /* 0 */
372 351
373 /* ========================================================================= 352 /* =========================================================================
374 * Put a short in the pending buffer. The 16-bit value is put in MSB order. 353 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
375 * IN assertion: the stream state is correct and there is enough room in 354 * IN assertion: the stream state is correct and there is enough room in
376 * pending_buf. 355 * pending_buf.
377 */ 356 */
378 static void putShortMSB( 357 static void putShortMSB(
379 deflate_state *s, 358 deflate_state *s,
380 uInt b 359 uInt b
381 ) 360 )
382 { 361 {
383 put_byte(s, (Byte)(b >> 8)); 362 put_byte(s, (Byte)(b >> 8));
384 put_byte(s, (Byte)(b & 0xff)); 363 put_byte(s, (Byte)(b & 0xff));
385 } 364 }
386 365
387 /* ========================================================================= 366 /* =========================================================================
388 * Flush as much pending output as possible. All deflate() output goes 367 * Flush as much pending output as possible. All deflate() output goes
389 * through this function so some applications may wish to modify it 368 * through this function so some applications may wish to modify it
390 * to avoid allocating a large strm->next_out buffer and copying into it. 369 * to avoid allocating a large strm->next_out buffer and copying into it.
391 * (See also read_buf()). 370 * (See also read_buf()).
392 */ 371 */
393 static void flush_pending( 372 static void flush_pending(
394 z_streamp strm 373 z_streamp strm
395 ) 374 )
396 { 375 {
397 deflate_state *s = (deflate_state *) strm->state; 376 deflate_state *s = (deflate_state *) strm->state;
398 unsigned len = s->pending; 377 unsigned len = s->pending;
399 378
400 if (len > strm->avail_out) len = strm->avail_out; 379 if (len > strm->avail_out) len = strm->avail_out;
401 if (len == 0) return; 380 if (len == 0) return;
402 381
403 if (strm->next_out != NULL) { 382 if (strm->next_out != NULL) {
404 memcpy(strm->next_out, s->pending_out, len); 383 memcpy(strm->next_out, s->pending_out, len);
405 strm->next_out += len; 384 strm->next_out += len;
406 } 385 }
407 s->pending_out += len; 386 s->pending_out += len;
408 strm->total_out += len; 387 strm->total_out += len;
409 strm->avail_out -= len; 388 strm->avail_out -= len;
410 s->pending -= len; 389 s->pending -= len;
411 if (s->pending == 0) { 390 if (s->pending == 0) {
412 s->pending_out = s->pending_buf; 391 s->pending_out = s->pending_buf;
413 } 392 }
414 } 393 }
415 394
416 /* ========================================================================= */ 395 /* ========================================================================= */
417 int zlib_deflate( 396 int zlib_deflate(
418 z_streamp strm, 397 z_streamp strm,
419 int flush 398 int flush
420 ) 399 )
421 { 400 {
422 int old_flush; /* value of flush param for previous deflate call */ 401 int old_flush; /* value of flush param for previous deflate call */
423 deflate_state *s; 402 deflate_state *s;
424 403
425 if (strm == NULL || strm->state == NULL || 404 if (strm == NULL || strm->state == NULL ||
426 flush > Z_FINISH || flush < 0) { 405 flush > Z_FINISH || flush < 0) {
427 return Z_STREAM_ERROR; 406 return Z_STREAM_ERROR;
428 } 407 }
429 s = (deflate_state *) strm->state; 408 s = (deflate_state *) strm->state;
430 409
431 if ((strm->next_in == NULL && strm->avail_in != 0) || 410 if ((strm->next_in == NULL && strm->avail_in != 0) ||
432 (s->status == FINISH_STATE && flush != Z_FINISH)) { 411 (s->status == FINISH_STATE && flush != Z_FINISH)) {
433 return Z_STREAM_ERROR; 412 return Z_STREAM_ERROR;
434 } 413 }
435 if (strm->avail_out == 0) return Z_BUF_ERROR; 414 if (strm->avail_out == 0) return Z_BUF_ERROR;
436 415
437 s->strm = strm; /* just in case */ 416 s->strm = strm; /* just in case */
438 old_flush = s->last_flush; 417 old_flush = s->last_flush;
439 s->last_flush = flush; 418 s->last_flush = flush;
440 419
441 /* Write the zlib header */ 420 /* Write the zlib header */
442 if (s->status == INIT_STATE) { 421 if (s->status == INIT_STATE) {
443 422
444 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; 423 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
445 uInt level_flags = (s->level-1) >> 1; 424 uInt level_flags = (s->level-1) >> 1;
446 425
447 if (level_flags > 3) level_flags = 3; 426 if (level_flags > 3) level_flags = 3;
448 header |= (level_flags << 6); 427 header |= (level_flags << 6);
449 if (s->strstart != 0) header |= PRESET_DICT; 428 if (s->strstart != 0) header |= PRESET_DICT;
450 header += 31 - (header % 31); 429 header += 31 - (header % 31);
451 430
452 s->status = BUSY_STATE; 431 s->status = BUSY_STATE;
453 putShortMSB(s, header); 432 putShortMSB(s, header);
454 433
455 /* Save the adler32 of the preset dictionary: */ 434 /* Save the adler32 of the preset dictionary: */
456 if (s->strstart != 0) { 435 if (s->strstart != 0) {
457 putShortMSB(s, (uInt)(strm->adler >> 16)); 436 putShortMSB(s, (uInt)(strm->adler >> 16));
458 putShortMSB(s, (uInt)(strm->adler & 0xffff)); 437 putShortMSB(s, (uInt)(strm->adler & 0xffff));
459 } 438 }
460 strm->adler = 1L; 439 strm->adler = 1L;
461 } 440 }
462 441
463 /* Flush as much pending output as possible */ 442 /* Flush as much pending output as possible */
464 if (s->pending != 0) { 443 if (s->pending != 0) {
465 flush_pending(strm); 444 flush_pending(strm);
466 if (strm->avail_out == 0) { 445 if (strm->avail_out == 0) {
467 /* Since avail_out is 0, deflate will be called again with 446 /* Since avail_out is 0, deflate will be called again with
468 * more output space, but possibly with both pending and 447 * more output space, but possibly with both pending and
469 * avail_in equal to zero. There won't be anything to do, 448 * avail_in equal to zero. There won't be anything to do,
470 * but this is not an error situation so make sure we 449 * but this is not an error situation so make sure we
471 * return OK instead of BUF_ERROR at next call of deflate: 450 * return OK instead of BUF_ERROR at next call of deflate:
472 */ 451 */
473 s->last_flush = -1; 452 s->last_flush = -1;
474 return Z_OK; 453 return Z_OK;
475 } 454 }
476 455
477 /* Make sure there is something to do and avoid duplicate consecutive 456 /* Make sure there is something to do and avoid duplicate consecutive
478 * flushes. For repeated and useless calls with Z_FINISH, we keep 457 * flushes. For repeated and useless calls with Z_FINISH, we keep
479 * returning Z_STREAM_END instead of Z_BUFF_ERROR. 458 * returning Z_STREAM_END instead of Z_BUFF_ERROR.
480 */ 459 */
481 } else if (strm->avail_in == 0 && flush <= old_flush && 460 } else if (strm->avail_in == 0 && flush <= old_flush &&
482 flush != Z_FINISH) { 461 flush != Z_FINISH) {
483 return Z_BUF_ERROR; 462 return Z_BUF_ERROR;
484 } 463 }
485 464
486 /* User must not provide more input after the first FINISH: */ 465 /* User must not provide more input after the first FINISH: */
487 if (s->status == FINISH_STATE && strm->avail_in != 0) { 466 if (s->status == FINISH_STATE && strm->avail_in != 0) {
488 return Z_BUF_ERROR; 467 return Z_BUF_ERROR;
489 } 468 }
490 469
491 /* Start a new block or continue the current one. 470 /* Start a new block or continue the current one.
492 */ 471 */
493 if (strm->avail_in != 0 || s->lookahead != 0 || 472 if (strm->avail_in != 0 || s->lookahead != 0 ||
494 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { 473 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
495 block_state bstate; 474 block_state bstate;
496 475
497 bstate = (*(configuration_table[s->level].func))(s, flush); 476 bstate = (*(configuration_table[s->level].func))(s, flush);
498 477
499 if (bstate == finish_started || bstate == finish_done) { 478 if (bstate == finish_started || bstate == finish_done) {
500 s->status = FINISH_STATE; 479 s->status = FINISH_STATE;
501 } 480 }
502 if (bstate == need_more || bstate == finish_started) { 481 if (bstate == need_more || bstate == finish_started) {
503 if (strm->avail_out == 0) { 482 if (strm->avail_out == 0) {
504 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ 483 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
505 } 484 }
506 return Z_OK; 485 return Z_OK;
507 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call 486 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
508 * of deflate should use the same flush parameter to make sure 487 * of deflate should use the same flush parameter to make sure
509 * that the flush is complete. So we don't have to output an 488 * that the flush is complete. So we don't have to output an
510 * empty block here, this will be done at next call. This also 489 * empty block here, this will be done at next call. This also
511 * ensures that for a very small output buffer, we emit at most 490 * ensures that for a very small output buffer, we emit at most
512 * one empty block. 491 * one empty block.
513 */ 492 */
514 } 493 }
515 if (bstate == block_done) { 494 if (bstate == block_done) {
516 if (flush == Z_PARTIAL_FLUSH) { 495 if (flush == Z_PARTIAL_FLUSH) {
517 zlib_tr_align(s); 496 zlib_tr_align(s);
518 } else if (flush == Z_PACKET_FLUSH) { 497 } else if (flush == Z_PACKET_FLUSH) {
519 /* Output just the 3-bit `stored' block type value, 498 /* Output just the 3-bit `stored' block type value,
520 but not a zero length. */ 499 but not a zero length. */
521 zlib_tr_stored_type_only(s); 500 zlib_tr_stored_type_only(s);
522 } else { /* FULL_FLUSH or SYNC_FLUSH */ 501 } else { /* FULL_FLUSH or SYNC_FLUSH */
523 zlib_tr_stored_block(s, (char*)0, 0L, 0); 502 zlib_tr_stored_block(s, (char*)0, 0L, 0);
524 /* For a full flush, this empty block will be recognized 503 /* For a full flush, this empty block will be recognized
525 * as a special marker by inflate_sync(). 504 * as a special marker by inflate_sync().
526 */ 505 */
527 if (flush == Z_FULL_FLUSH) { 506 if (flush == Z_FULL_FLUSH) {
528 CLEAR_HASH(s); /* forget history */ 507 CLEAR_HASH(s); /* forget history */
529 } 508 }
530 } 509 }
531 flush_pending(strm); 510 flush_pending(strm);
532 if (strm->avail_out == 0) { 511 if (strm->avail_out == 0) {
533 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ 512 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
534 return Z_OK; 513 return Z_OK;
535 } 514 }
536 } 515 }
537 } 516 }
538 Assert(strm->avail_out > 0, "bug2"); 517 Assert(strm->avail_out > 0, "bug2");
539 518
540 if (flush != Z_FINISH) return Z_OK; 519 if (flush != Z_FINISH) return Z_OK;
541 if (s->noheader) return Z_STREAM_END; 520 if (s->noheader) return Z_STREAM_END;
542 521
543 /* Write the zlib trailer (adler32) */ 522 /* Write the zlib trailer (adler32) */
544 putShortMSB(s, (uInt)(strm->adler >> 16)); 523 putShortMSB(s, (uInt)(strm->adler >> 16));
545 putShortMSB(s, (uInt)(strm->adler & 0xffff)); 524 putShortMSB(s, (uInt)(strm->adler & 0xffff));
546 flush_pending(strm); 525 flush_pending(strm);
547 /* If avail_out is zero, the application will call deflate again 526 /* If avail_out is zero, the application will call deflate again
548 * to flush the rest. 527 * to flush the rest.
549 */ 528 */
550 s->noheader = -1; /* write the trailer only once! */ 529 s->noheader = -1; /* write the trailer only once! */
551 return s->pending != 0 ? Z_OK : Z_STREAM_END; 530 return s->pending != 0 ? Z_OK : Z_STREAM_END;
552 } 531 }
553 532
554 /* ========================================================================= */ 533 /* ========================================================================= */
555 int zlib_deflateEnd( 534 int zlib_deflateEnd(
556 z_streamp strm 535 z_streamp strm
557 ) 536 )
558 { 537 {
559 int status; 538 int status;
560 deflate_state *s; 539 deflate_state *s;
561 540
562 if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR; 541 if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR;
563 s = (deflate_state *) strm->state; 542 s = (deflate_state *) strm->state;
564 543
565 status = s->status; 544 status = s->status;
566 if (status != INIT_STATE && status != BUSY_STATE && 545 if (status != INIT_STATE && status != BUSY_STATE &&
567 status != FINISH_STATE) { 546 status != FINISH_STATE) {
568 return Z_STREAM_ERROR; 547 return Z_STREAM_ERROR;
569 } 548 }
570 549
571 strm->state = NULL; 550 strm->state = NULL;
572 551
573 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; 552 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
574 } 553 }
575 554
576 /* ========================================================================= 555 /* =========================================================================
577 * Copy the source state to the destination state. 556 * Copy the source state to the destination state.
578 */ 557 */
579 #if 0 558 #if 0
580 int zlib_deflateCopy ( 559 int zlib_deflateCopy (
581 z_streamp dest, 560 z_streamp dest,
582 z_streamp source 561 z_streamp source
583 ) 562 )
584 { 563 {
585 #ifdef MAXSEG_64K 564 #ifdef MAXSEG_64K
586 return Z_STREAM_ERROR; 565 return Z_STREAM_ERROR;
587 #else 566 #else
588 deflate_state *ds; 567 deflate_state *ds;
589 deflate_state *ss; 568 deflate_state *ss;
590 ush *overlay; 569 ush *overlay;
591 deflate_workspace *mem; 570 deflate_workspace *mem;
592 571
593 572
594 if (source == NULL || dest == NULL || source->state == NULL) { 573 if (source == NULL || dest == NULL || source->state == NULL) {
595 return Z_STREAM_ERROR; 574 return Z_STREAM_ERROR;
596 } 575 }
597 576
598 ss = (deflate_state *) source->state; 577 ss = (deflate_state *) source->state;
599 578
600 *dest = *source; 579 *dest = *source;
601 580
602 mem = (deflate_workspace *) dest->workspace; 581 mem = (deflate_workspace *) dest->workspace;
603 582
604 ds = &(mem->deflate_memory); 583 ds = &(mem->deflate_memory);
605 584
606 dest->state = (struct internal_state *) ds; 585 dest->state = (struct internal_state *) ds;
607 *ds = *ss; 586 *ds = *ss;
608 ds->strm = dest; 587 ds->strm = dest;
609 588
610 ds->window = (Byte *) mem->window_memory; 589 ds->window = (Byte *) mem->window_memory;
611 ds->prev = (Pos *) mem->prev_memory; 590 ds->prev = (Pos *) mem->prev_memory;
612 ds->head = (Pos *) mem->head_memory; 591 ds->head = (Pos *) mem->head_memory;
613 overlay = (ush *) mem->overlay_memory; 592 overlay = (ush *) mem->overlay_memory;
614 ds->pending_buf = (uch *) overlay; 593 ds->pending_buf = (uch *) overlay;
615 594
616 memcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); 595 memcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
617 memcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); 596 memcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
618 memcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); 597 memcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
619 memcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); 598 memcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
620 599
621 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); 600 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
622 ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); 601 ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
623 ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; 602 ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
624 603
625 ds->l_desc.dyn_tree = ds->dyn_ltree; 604 ds->l_desc.dyn_tree = ds->dyn_ltree;
626 ds->d_desc.dyn_tree = ds->dyn_dtree; 605 ds->d_desc.dyn_tree = ds->dyn_dtree;
627 ds->bl_desc.dyn_tree = ds->bl_tree; 606 ds->bl_desc.dyn_tree = ds->bl_tree;
628 607
629 return Z_OK; 608 return Z_OK;
630 #endif 609 #endif
631 } 610 }
632 #endif /* 0 */ 611 #endif /* 0 */
633 612
634 /* =========================================================================== 613 /* ===========================================================================
635 * Read a new buffer from the current input stream, update the adler32 614 * Read a new buffer from the current input stream, update the adler32
636 * and total number of bytes read. All deflate() input goes through 615 * and total number of bytes read. All deflate() input goes through
637 * this function so some applications may wish to modify it to avoid 616 * this function so some applications may wish to modify it to avoid
638 * allocating a large strm->next_in buffer and copying from it. 617 * allocating a large strm->next_in buffer and copying from it.
639 * (See also flush_pending()). 618 * (See also flush_pending()).
640 */ 619 */
641 static int read_buf( 620 static int read_buf(
642 z_streamp strm, 621 z_streamp strm,
643 Byte *buf, 622 Byte *buf,
644 unsigned size 623 unsigned size
645 ) 624 )
646 { 625 {
647 unsigned len = strm->avail_in; 626 unsigned len = strm->avail_in;
648 627
649 if (len > size) len = size; 628 if (len > size) len = size;
650 if (len == 0) return 0; 629 if (len == 0) return 0;
651 630
652 strm->avail_in -= len; 631 strm->avail_in -= len;
653 632
654 if (!((deflate_state *)(strm->state))->noheader) { 633 if (!((deflate_state *)(strm->state))->noheader) {
655 strm->adler = zlib_adler32(strm->adler, strm->next_in, len); 634 strm->adler = zlib_adler32(strm->adler, strm->next_in, len);
656 } 635 }
657 memcpy(buf, strm->next_in, len); 636 memcpy(buf, strm->next_in, len);
658 strm->next_in += len; 637 strm->next_in += len;
659 strm->total_in += len; 638 strm->total_in += len;
660 639
661 return (int)len; 640 return (int)len;
662 } 641 }
663 642
664 /* =========================================================================== 643 /* ===========================================================================
665 * Initialize the "longest match" routines for a new zlib stream 644 * Initialize the "longest match" routines for a new zlib stream
666 */ 645 */
667 static void lm_init( 646 static void lm_init(
668 deflate_state *s 647 deflate_state *s
669 ) 648 )
670 { 649 {
671 s->window_size = (ulg)2L*s->w_size; 650 s->window_size = (ulg)2L*s->w_size;
672 651
673 CLEAR_HASH(s); 652 CLEAR_HASH(s);
674 653
675 /* Set the default configuration parameters: 654 /* Set the default configuration parameters:
676 */ 655 */
677 s->max_lazy_match = configuration_table[s->level].max_lazy; 656 s->max_lazy_match = configuration_table[s->level].max_lazy;
678 s->good_match = configuration_table[s->level].good_length; 657 s->good_match = configuration_table[s->level].good_length;
679 s->nice_match = configuration_table[s->level].nice_length; 658 s->nice_match = configuration_table[s->level].nice_length;
680 s->max_chain_length = configuration_table[s->level].max_chain; 659 s->max_chain_length = configuration_table[s->level].max_chain;
681 660
682 s->strstart = 0; 661 s->strstart = 0;
683 s->block_start = 0L; 662 s->block_start = 0L;
684 s->lookahead = 0; 663 s->lookahead = 0;
685 s->match_length = s->prev_length = MIN_MATCH-1; 664 s->match_length = s->prev_length = MIN_MATCH-1;
686 s->match_available = 0; 665 s->match_available = 0;
687 s->ins_h = 0; 666 s->ins_h = 0;
688 } 667 }
689 668
690 /* =========================================================================== 669 /* ===========================================================================
691 * Set match_start to the longest match starting at the given string and 670 * Set match_start to the longest match starting at the given string and
692 * return its length. Matches shorter or equal to prev_length are discarded, 671 * return its length. Matches shorter or equal to prev_length are discarded,
693 * in which case the result is equal to prev_length and match_start is 672 * in which case the result is equal to prev_length and match_start is
694 * garbage. 673 * garbage.
695 * IN assertions: cur_match is the head of the hash chain for the current 674 * IN assertions: cur_match is the head of the hash chain for the current
696 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 675 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
697 * OUT assertion: the match length is not greater than s->lookahead. 676 * OUT assertion: the match length is not greater than s->lookahead.
698 */ 677 */
699 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or 678 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
700 * match.S. The code will be functionally equivalent. 679 * match.S. The code will be functionally equivalent.
701 */ 680 */
702 static uInt longest_match( 681 static uInt longest_match(
703 deflate_state *s, 682 deflate_state *s,
704 IPos cur_match /* current match */ 683 IPos cur_match /* current match */
705 ) 684 )
706 { 685 {
707 unsigned chain_length = s->max_chain_length;/* max hash chain length */ 686 unsigned chain_length = s->max_chain_length;/* max hash chain length */
708 register Byte *scan = s->window + s->strstart; /* current string */ 687 register Byte *scan = s->window + s->strstart; /* current string */
709 register Byte *match; /* matched string */ 688 register Byte *match; /* matched string */
710 register int len; /* length of current match */ 689 register int len; /* length of current match */
711 int best_len = s->prev_length; /* best match length so far */ 690 int best_len = s->prev_length; /* best match length so far */
712 int nice_match = s->nice_match; /* stop if match long enough */ 691 int nice_match = s->nice_match; /* stop if match long enough */
713 IPos limit = s->strstart > (IPos)MAX_DIST(s) ? 692 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
714 s->strstart - (IPos)MAX_DIST(s) : NIL; 693 s->strstart - (IPos)MAX_DIST(s) : NIL;
715 /* Stop when cur_match becomes <= limit. To simplify the code, 694 /* Stop when cur_match becomes <= limit. To simplify the code,
716 * we prevent matches with the string of window index 0. 695 * we prevent matches with the string of window index 0.
717 */ 696 */
718 Pos *prev = s->prev; 697 Pos *prev = s->prev;
719 uInt wmask = s->w_mask; 698 uInt wmask = s->w_mask;
720 699
721 #ifdef UNALIGNED_OK 700 #ifdef UNALIGNED_OK
722 /* Compare two bytes at a time. Note: this is not always beneficial. 701 /* Compare two bytes at a time. Note: this is not always beneficial.
723 * Try with and without -DUNALIGNED_OK to check. 702 * Try with and without -DUNALIGNED_OK to check.
724 */ 703 */
725 register Byte *strend = s->window + s->strstart + MAX_MATCH - 1; 704 register Byte *strend = s->window + s->strstart + MAX_MATCH - 1;
726 register ush scan_start = *(ush*)scan; 705 register ush scan_start = *(ush*)scan;
727 register ush scan_end = *(ush*)(scan+best_len-1); 706 register ush scan_end = *(ush*)(scan+best_len-1);
728 #else 707 #else
729 register Byte *strend = s->window + s->strstart + MAX_MATCH; 708 register Byte *strend = s->window + s->strstart + MAX_MATCH;
730 register Byte scan_end1 = scan[best_len-1]; 709 register Byte scan_end1 = scan[best_len-1];
731 register Byte scan_end = scan[best_len]; 710 register Byte scan_end = scan[best_len];
732 #endif 711 #endif
733 712
734 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. 713 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
735 * It is easy to get rid of this optimization if necessary. 714 * It is easy to get rid of this optimization if necessary.
736 */ 715 */
737 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); 716 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
738 717
739 /* Do not waste too much time if we already have a good match: */ 718 /* Do not waste too much time if we already have a good match: */
740 if (s->prev_length >= s->good_match) { 719 if (s->prev_length >= s->good_match) {
741 chain_length >>= 2; 720 chain_length >>= 2;
742 } 721 }
743 /* Do not look for matches beyond the end of the input. This is necessary 722 /* Do not look for matches beyond the end of the input. This is necessary
744 * to make deflate deterministic. 723 * to make deflate deterministic.
745 */ 724 */
746 if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; 725 if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
747 726
748 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); 727 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
749 728
750 do { 729 do {
751 Assert(cur_match < s->strstart, "no future"); 730 Assert(cur_match < s->strstart, "no future");
752 match = s->window + cur_match; 731 match = s->window + cur_match;
753 732
754 /* Skip to next match if the match length cannot increase 733 /* Skip to next match if the match length cannot increase
755 * or if the match length is less than 2: 734 * or if the match length is less than 2:
756 */ 735 */
757 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258) 736 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
758 /* This code assumes sizeof(unsigned short) == 2. Do not use 737 /* This code assumes sizeof(unsigned short) == 2. Do not use
759 * UNALIGNED_OK if your compiler uses a different size. 738 * UNALIGNED_OK if your compiler uses a different size.
760 */ 739 */
761 if (*(ush*)(match+best_len-1) != scan_end || 740 if (*(ush*)(match+best_len-1) != scan_end ||
762 *(ush*)match != scan_start) continue; 741 *(ush*)match != scan_start) continue;
763 742
764 /* It is not necessary to compare scan[2] and match[2] since they are 743 /* It is not necessary to compare scan[2] and match[2] since they are
765 * always equal when the other bytes match, given that the hash keys 744 * always equal when the other bytes match, given that the hash keys
766 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at 745 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
767 * strstart+3, +5, ... up to strstart+257. We check for insufficient 746 * strstart+3, +5, ... up to strstart+257. We check for insufficient
768 * lookahead only every 4th comparison; the 128th check will be made 747 * lookahead only every 4th comparison; the 128th check will be made
769 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is 748 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
770 * necessary to put more guard bytes at the end of the window, or 749 * necessary to put more guard bytes at the end of the window, or
771 * to check more often for insufficient lookahead. 750 * to check more often for insufficient lookahead.
772 */ 751 */
773 Assert(scan[2] == match[2], "scan[2]?"); 752 Assert(scan[2] == match[2], "scan[2]?");
774 scan++, match++; 753 scan++, match++;
775 do { 754 do {
776 } while (*(ush*)(scan+=2) == *(ush*)(match+=2) && 755 } while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
777 *(ush*)(scan+=2) == *(ush*)(match+=2) && 756 *(ush*)(scan+=2) == *(ush*)(match+=2) &&
778 *(ush*)(scan+=2) == *(ush*)(match+=2) && 757 *(ush*)(scan+=2) == *(ush*)(match+=2) &&
779 *(ush*)(scan+=2) == *(ush*)(match+=2) && 758 *(ush*)(scan+=2) == *(ush*)(match+=2) &&
780 scan < strend); 759 scan < strend);
781 /* The funny "do {}" generates better code on most compilers */ 760 /* The funny "do {}" generates better code on most compilers */
782 761
783 /* Here, scan <= window+strstart+257 */ 762 /* Here, scan <= window+strstart+257 */
784 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); 763 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
785 if (*scan == *match) scan++; 764 if (*scan == *match) scan++;
786 765
787 len = (MAX_MATCH - 1) - (int)(strend-scan); 766 len = (MAX_MATCH - 1) - (int)(strend-scan);
788 scan = strend - (MAX_MATCH-1); 767 scan = strend - (MAX_MATCH-1);
789 768
790 #else /* UNALIGNED_OK */ 769 #else /* UNALIGNED_OK */
791 770
792 if (match[best_len] != scan_end || 771 if (match[best_len] != scan_end ||
793 match[best_len-1] != scan_end1 || 772 match[best_len-1] != scan_end1 ||
794 *match != *scan || 773 *match != *scan ||
795 *++match != scan[1]) continue; 774 *++match != scan[1]) continue;
796 775
797 /* The check at best_len-1 can be removed because it will be made 776 /* The check at best_len-1 can be removed because it will be made
798 * again later. (This heuristic is not always a win.) 777 * again later. (This heuristic is not always a win.)
799 * It is not necessary to compare scan[2] and match[2] since they 778 * It is not necessary to compare scan[2] and match[2] since they
800 * are always equal when the other bytes match, given that 779 * are always equal when the other bytes match, given that
801 * the hash keys are equal and that HASH_BITS >= 8. 780 * the hash keys are equal and that HASH_BITS >= 8.
802 */ 781 */
803 scan += 2, match++; 782 scan += 2, match++;
804 Assert(*scan == *match, "match[2]?"); 783 Assert(*scan == *match, "match[2]?");
805 784
806 /* We check for insufficient lookahead only every 8th comparison; 785 /* We check for insufficient lookahead only every 8th comparison;
807 * the 256th check will be made at strstart+258. 786 * the 256th check will be made at strstart+258.
808 */ 787 */
809 do { 788 do {
810 } while (*++scan == *++match && *++scan == *++match && 789 } while (*++scan == *++match && *++scan == *++match &&
811 *++scan == *++match && *++scan == *++match && 790 *++scan == *++match && *++scan == *++match &&
812 *++scan == *++match && *++scan == *++match && 791 *++scan == *++match && *++scan == *++match &&
813 *++scan == *++match && *++scan == *++match && 792 *++scan == *++match && *++scan == *++match &&
814 scan < strend); 793 scan < strend);
815 794
816 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); 795 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
817 796
818 len = MAX_MATCH - (int)(strend - scan); 797 len = MAX_MATCH - (int)(strend - scan);
819 scan = strend - MAX_MATCH; 798 scan = strend - MAX_MATCH;
820 799
821 #endif /* UNALIGNED_OK */ 800 #endif /* UNALIGNED_OK */
822 801
823 if (len > best_len) { 802 if (len > best_len) {
824 s->match_start = cur_match; 803 s->match_start = cur_match;
825 best_len = len; 804 best_len = len;
826 if (len >= nice_match) break; 805 if (len >= nice_match) break;
827 #ifdef UNALIGNED_OK 806 #ifdef UNALIGNED_OK
828 scan_end = *(ush*)(scan+best_len-1); 807 scan_end = *(ush*)(scan+best_len-1);
829 #else 808 #else
830 scan_end1 = scan[best_len-1]; 809 scan_end1 = scan[best_len-1];
831 scan_end = scan[best_len]; 810 scan_end = scan[best_len];
832 #endif 811 #endif
833 } 812 }
834 } while ((cur_match = prev[cur_match & wmask]) > limit 813 } while ((cur_match = prev[cur_match & wmask]) > limit
835 && --chain_length != 0); 814 && --chain_length != 0);
836 815
837 if ((uInt)best_len <= s->lookahead) return best_len; 816 if ((uInt)best_len <= s->lookahead) return best_len;
838 return s->lookahead; 817 return s->lookahead;
839 } 818 }
840 819
841 #ifdef DEBUG_ZLIB 820 #ifdef DEBUG_ZLIB
842 /* =========================================================================== 821 /* ===========================================================================
843 * Check that the match at match_start is indeed a match. 822 * Check that the match at match_start is indeed a match.
844 */ 823 */
845 static void check_match( 824 static void check_match(
846 deflate_state *s, 825 deflate_state *s,
847 IPos start, 826 IPos start,
848 IPos match, 827 IPos match,
849 int length 828 int length
850 ) 829 )
851 { 830 {
852 /* check that the match is indeed a match */ 831 /* check that the match is indeed a match */
853 if (memcmp((char *)s->window + match, 832 if (memcmp((char *)s->window + match,
854 (char *)s->window + start, length) != EQUAL) { 833 (char *)s->window + start, length) != EQUAL) {
855 fprintf(stderr, " start %u, match %u, length %d\n", 834 fprintf(stderr, " start %u, match %u, length %d\n",
856 start, match, length); 835 start, match, length);
857 do { 836 do {
858 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); 837 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
859 } while (--length != 0); 838 } while (--length != 0);
860 z_error("invalid match"); 839 z_error("invalid match");
861 } 840 }
862 if (z_verbose > 1) { 841 if (z_verbose > 1) {
863 fprintf(stderr,"\\[%d,%d]", start-match, length); 842 fprintf(stderr,"\\[%d,%d]", start-match, length);
864 do { putc(s->window[start++], stderr); } while (--length != 0); 843 do { putc(s->window[start++], stderr); } while (--length != 0);
865 } 844 }
866 } 845 }
867 #else 846 #else
868 # define check_match(s, start, match, length) 847 # define check_match(s, start, match, length)
869 #endif 848 #endif
870 849
871 /* =========================================================================== 850 /* ===========================================================================
872 * Fill the window when the lookahead becomes insufficient. 851 * Fill the window when the lookahead becomes insufficient.
873 * Updates strstart and lookahead. 852 * Updates strstart and lookahead.
874 * 853 *
875 * IN assertion: lookahead < MIN_LOOKAHEAD 854 * IN assertion: lookahead < MIN_LOOKAHEAD
876 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD 855 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
877 * At least one byte has been read, or avail_in == 0; reads are 856 * At least one byte has been read, or avail_in == 0; reads are
878 * performed for at least two bytes (required for the zip translate_eol 857 * performed for at least two bytes (required for the zip translate_eol
879 * option -- not supported here). 858 * option -- not supported here).
880 */ 859 */
881 static void fill_window( 860 static void fill_window(
882 deflate_state *s 861 deflate_state *s
883 ) 862 )
884 { 863 {
885 register unsigned n, m; 864 register unsigned n, m;
886 register Pos *p; 865 register Pos *p;
887 unsigned more; /* Amount of free space at the end of the window. */ 866 unsigned more; /* Amount of free space at the end of the window. */
888 uInt wsize = s->w_size; 867 uInt wsize = s->w_size;
889 868
890 do { 869 do {
891 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); 870 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
892 871
893 /* Deal with !@#$% 64K limit: */ 872 /* Deal with !@#$% 64K limit: */
894 if (more == 0 && s->strstart == 0 && s->lookahead == 0) { 873 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
895 more = wsize; 874 more = wsize;
896 875
897 } else if (more == (unsigned)(-1)) { 876 } else if (more == (unsigned)(-1)) {
898 /* Very unlikely, but possible on 16 bit machine if strstart == 0 877 /* Very unlikely, but possible on 16 bit machine if strstart == 0
899 * and lookahead == 1 (input done one byte at time) 878 * and lookahead == 1 (input done one byte at time)
900 */ 879 */
901 more--; 880 more--;
902 881
903 /* If the window is almost full and there is insufficient lookahead, 882 /* If the window is almost full and there is insufficient lookahead,
904 * move the upper half to the lower one to make room in the upper half. 883 * move the upper half to the lower one to make room in the upper half.
905 */ 884 */
906 } else if (s->strstart >= wsize+MAX_DIST(s)) { 885 } else if (s->strstart >= wsize+MAX_DIST(s)) {
907 886
908 memcpy((char *)s->window, (char *)s->window+wsize, 887 memcpy((char *)s->window, (char *)s->window+wsize,
909 (unsigned)wsize); 888 (unsigned)wsize);
910 s->match_start -= wsize; 889 s->match_start -= wsize;
911 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ 890 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
912 s->block_start -= (long) wsize; 891 s->block_start -= (long) wsize;
913 892
914 /* Slide the hash table (could be avoided with 32 bit values 893 /* Slide the hash table (could be avoided with 32 bit values
915 at the expense of memory usage). We slide even when level == 0 894 at the expense of memory usage). We slide even when level == 0
916 to keep the hash table consistent if we switch back to level > 0 895 to keep the hash table consistent if we switch back to level > 0
917 later. (Using level 0 permanently is not an optimal usage of 896 later. (Using level 0 permanently is not an optimal usage of
918 zlib, so we don't care about this pathological case.) 897 zlib, so we don't care about this pathological case.)
919 */ 898 */
920 n = s->hash_size; 899 n = s->hash_size;
921 p = &s->head[n]; 900 p = &s->head[n];
922 do { 901 do {
923 m = *--p; 902 m = *--p;
924 *p = (Pos)(m >= wsize ? m-wsize : NIL); 903 *p = (Pos)(m >= wsize ? m-wsize : NIL);
925 } while (--n); 904 } while (--n);
926 905
927 n = wsize; 906 n = wsize;
928 p = &s->prev[n]; 907 p = &s->prev[n];
929 do { 908 do {
930 m = *--p; 909 m = *--p;
931 *p = (Pos)(m >= wsize ? m-wsize : NIL); 910 *p = (Pos)(m >= wsize ? m-wsize : NIL);
932 /* If n is not on any hash chain, prev[n] is garbage but 911 /* If n is not on any hash chain, prev[n] is garbage but
933 * its value will never be used. 912 * its value will never be used.
934 */ 913 */
935 } while (--n); 914 } while (--n);
936 more += wsize; 915 more += wsize;
937 } 916 }
938 if (s->strm->avail_in == 0) return; 917 if (s->strm->avail_in == 0) return;
939 918
940 /* If there was no sliding: 919 /* If there was no sliding:
941 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && 920 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
942 * more == window_size - lookahead - strstart 921 * more == window_size - lookahead - strstart
943 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) 922 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
944 * => more >= window_size - 2*WSIZE + 2 923 * => more >= window_size - 2*WSIZE + 2
945 * In the BIG_MEM or MMAP case (not yet supported), 924 * In the BIG_MEM or MMAP case (not yet supported),
946 * window_size == input_size + MIN_LOOKAHEAD && 925 * window_size == input_size + MIN_LOOKAHEAD &&
947 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. 926 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
948 * Otherwise, window_size == 2*WSIZE so more >= 2. 927 * Otherwise, window_size == 2*WSIZE so more >= 2.
949 * If there was sliding, more >= WSIZE. So in all cases, more >= 2. 928 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
950 */ 929 */
951 Assert(more >= 2, "more < 2"); 930 Assert(more >= 2, "more < 2");
952 931
953 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); 932 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
954 s->lookahead += n; 933 s->lookahead += n;
955 934
956 /* Initialize the hash value now that we have some input: */ 935 /* Initialize the hash value now that we have some input: */
957 if (s->lookahead >= MIN_MATCH) { 936 if (s->lookahead >= MIN_MATCH) {
958 s->ins_h = s->window[s->strstart]; 937 s->ins_h = s->window[s->strstart];
959 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); 938 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
960 #if MIN_MATCH != 3 939 #if MIN_MATCH != 3
961 Call UPDATE_HASH() MIN_MATCH-3 more times 940 Call UPDATE_HASH() MIN_MATCH-3 more times
962 #endif 941 #endif
963 } 942 }
964 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, 943 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
965 * but this is not important since only literal bytes will be emitted. 944 * but this is not important since only literal bytes will be emitted.
966 */ 945 */
967 946
968 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); 947 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
969 } 948 }
970 949
971 /* =========================================================================== 950 /* ===========================================================================
972 * Flush the current block, with given end-of-file flag. 951 * Flush the current block, with given end-of-file flag.
973 * IN assertion: strstart is set to the end of the current match. 952 * IN assertion: strstart is set to the end of the current match.
974 */ 953 */
975 #define FLUSH_BLOCK_ONLY(s, eof) { \ 954 #define FLUSH_BLOCK_ONLY(s, eof) { \
976 zlib_tr_flush_block(s, (s->block_start >= 0L ? \ 955 zlib_tr_flush_block(s, (s->block_start >= 0L ? \
977 (char *)&s->window[(unsigned)s->block_start] : \ 956 (char *)&s->window[(unsigned)s->block_start] : \
978 NULL), \ 957 NULL), \
979 (ulg)((long)s->strstart - s->block_start), \ 958 (ulg)((long)s->strstart - s->block_start), \
980 (eof)); \ 959 (eof)); \
981 s->block_start = s->strstart; \ 960 s->block_start = s->strstart; \
982 flush_pending(s->strm); \ 961 flush_pending(s->strm); \
983 Tracev((stderr,"[FLUSH]")); \ 962 Tracev((stderr,"[FLUSH]")); \
984 } 963 }
985 964
986 /* Same but force premature exit if necessary. */ 965 /* Same but force premature exit if necessary. */
987 #define FLUSH_BLOCK(s, eof) { \ 966 #define FLUSH_BLOCK(s, eof) { \
988 FLUSH_BLOCK_ONLY(s, eof); \ 967 FLUSH_BLOCK_ONLY(s, eof); \
989 if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \ 968 if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
990 } 969 }
991 970
992 /* =========================================================================== 971 /* ===========================================================================
993 * Copy without compression as much as possible from the input stream, return 972 * Copy without compression as much as possible from the input stream, return
994 * the current block state. 973 * the current block state.
995 * This function does not insert new strings in the dictionary since 974 * This function does not insert new strings in the dictionary since
996 * uncompressible data is probably not useful. This function is used 975 * uncompressible data is probably not useful. This function is used
997 * only for the level=0 compression option. 976 * only for the level=0 compression option.
998 * NOTE: this function should be optimized to avoid extra copying from 977 * NOTE: this function should be optimized to avoid extra copying from
999 * window to pending_buf. 978 * window to pending_buf.
1000 */ 979 */
1001 static block_state deflate_stored( 980 static block_state deflate_stored(
1002 deflate_state *s, 981 deflate_state *s,
1003 int flush 982 int flush
1004 ) 983 )
1005 { 984 {
1006 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited 985 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1007 * to pending_buf_size, and each stored block has a 5 byte header: 986 * to pending_buf_size, and each stored block has a 5 byte header:
1008 */ 987 */
1009 ulg max_block_size = 0xffff; 988 ulg max_block_size = 0xffff;
1010 ulg max_start; 989 ulg max_start;
1011 990
1012 if (max_block_size > s->pending_buf_size - 5) { 991 if (max_block_size > s->pending_buf_size - 5) {
1013 max_block_size = s->pending_buf_size - 5; 992 max_block_size = s->pending_buf_size - 5;
1014 } 993 }
1015 994
1016 /* Copy as much as possible from input to output: */ 995 /* Copy as much as possible from input to output: */
1017 for (;;) { 996 for (;;) {
1018 /* Fill the window as much as possible: */ 997 /* Fill the window as much as possible: */
1019 if (s->lookahead <= 1) { 998 if (s->lookahead <= 1) {
1020 999
1021 Assert(s->strstart < s->w_size+MAX_DIST(s) || 1000 Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1022 s->block_start >= (long)s->w_size, "slide too late"); 1001 s->block_start >= (long)s->w_size, "slide too late");
1023 1002
1024 fill_window(s); 1003 fill_window(s);
1025 if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; 1004 if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
1026 1005
1027 if (s->lookahead == 0) break; /* flush the current block */ 1006 if (s->lookahead == 0) break; /* flush the current block */
1028 } 1007 }
1029 Assert(s->block_start >= 0L, "block gone"); 1008 Assert(s->block_start >= 0L, "block gone");
1030 1009
1031 s->strstart += s->lookahead; 1010 s->strstart += s->lookahead;
1032 s->lookahead = 0; 1011 s->lookahead = 0;
1033 1012
1034 /* Emit a stored block if pending_buf will be full: */ 1013 /* Emit a stored block if pending_buf will be full: */
1035 max_start = s->block_start + max_block_size; 1014 max_start = s->block_start + max_block_size;
1036 if (s->strstart == 0 || (ulg)s->strstart >= max_start) { 1015 if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
1037 /* strstart == 0 is possible when wraparound on 16-bit machine */ 1016 /* strstart == 0 is possible when wraparound on 16-bit machine */
1038 s->lookahead = (uInt)(s->strstart - max_start); 1017 s->lookahead = (uInt)(s->strstart - max_start);
1039 s->strstart = (uInt)max_start; 1018 s->strstart = (uInt)max_start;
1040 FLUSH_BLOCK(s, 0); 1019 FLUSH_BLOCK(s, 0);
1041 } 1020 }
1042 /* Flush if we may have to slide, otherwise block_start may become 1021 /* Flush if we may have to slide, otherwise block_start may become
1043 * negative and the data will be gone: 1022 * negative and the data will be gone:
1044 */ 1023 */
1045 if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { 1024 if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
1046 FLUSH_BLOCK(s, 0); 1025 FLUSH_BLOCK(s, 0);
1047 } 1026 }
1048 } 1027 }
1049 FLUSH_BLOCK(s, flush == Z_FINISH); 1028 FLUSH_BLOCK(s, flush == Z_FINISH);
1050 return flush == Z_FINISH ? finish_done : block_done; 1029 return flush == Z_FINISH ? finish_done : block_done;
1051 } 1030 }
1052 1031
1053 /* =========================================================================== 1032 /* ===========================================================================
1054 * Compress as much as possible from the input stream, return the current 1033 * Compress as much as possible from the input stream, return the current
1055 * block state. 1034 * block state.
1056 * This function does not perform lazy evaluation of matches and inserts 1035 * This function does not perform lazy evaluation of matches and inserts
1057 * new strings in the dictionary only for unmatched strings or for short 1036 * new strings in the dictionary only for unmatched strings or for short
1058 * matches. It is used only for the fast compression options. 1037 * matches. It is used only for the fast compression options.
1059 */ 1038 */
1060 static block_state deflate_fast( 1039 static block_state deflate_fast(
1061 deflate_state *s, 1040 deflate_state *s,
1062 int flush 1041 int flush
1063 ) 1042 )
1064 { 1043 {
1065 IPos hash_head = NIL; /* head of the hash chain */ 1044 IPos hash_head = NIL; /* head of the hash chain */
1066 int bflush; /* set if current block must be flushed */ 1045 int bflush; /* set if current block must be flushed */
1067 1046
1068 for (;;) { 1047 for (;;) {
1069 /* Make sure that we always have enough lookahead, except 1048 /* Make sure that we always have enough lookahead, except
1070 * at the end of the input file. We need MAX_MATCH bytes 1049 * at the end of the input file. We need MAX_MATCH bytes
1071 * for the next match, plus MIN_MATCH bytes to insert the 1050 * for the next match, plus MIN_MATCH bytes to insert the
1072 * string following the next match. 1051 * string following the next match.
1073 */ 1052 */
1074 if (s->lookahead < MIN_LOOKAHEAD) { 1053 if (s->lookahead < MIN_LOOKAHEAD) {
1075 fill_window(s); 1054 fill_window(s);
1076 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { 1055 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1077 return need_more; 1056 return need_more;
1078 } 1057 }
1079 if (s->lookahead == 0) break; /* flush the current block */ 1058 if (s->lookahead == 0) break; /* flush the current block */
1080 } 1059 }
1081 1060
1082 /* Insert the string window[strstart .. strstart+2] in the 1061 /* Insert the string window[strstart .. strstart+2] in the
1083 * dictionary, and set hash_head to the head of the hash chain: 1062 * dictionary, and set hash_head to the head of the hash chain:
1084 */ 1063 */
1085 if (s->lookahead >= MIN_MATCH) { 1064 if (s->lookahead >= MIN_MATCH) {
1086 INSERT_STRING(s, s->strstart, hash_head); 1065 INSERT_STRING(s, s->strstart, hash_head);
1087 } 1066 }
1088 1067
1089 /* Find the longest match, discarding those <= prev_length. 1068 /* Find the longest match, discarding those <= prev_length.
1090 * At this point we have always match_length < MIN_MATCH 1069 * At this point we have always match_length < MIN_MATCH
1091 */ 1070 */
1092 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { 1071 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1093 /* To simplify the code, we prevent matches with the string 1072 /* To simplify the code, we prevent matches with the string
1094 * of window index 0 (in particular we have to avoid a match 1073 * of window index 0 (in particular we have to avoid a match
1095 * of the string with itself at the start of the input file). 1074 * of the string with itself at the start of the input file).
1096 */ 1075 */
1097 if (s->strategy != Z_HUFFMAN_ONLY) { 1076 if (s->strategy != Z_HUFFMAN_ONLY) {
1098 s->match_length = longest_match (s, hash_head); 1077 s->match_length = longest_match (s, hash_head);
1099 } 1078 }
1100 /* longest_match() sets match_start */ 1079 /* longest_match() sets match_start */
1101 } 1080 }
1102 if (s->match_length >= MIN_MATCH) { 1081 if (s->match_length >= MIN_MATCH) {
1103 check_match(s, s->strstart, s->match_start, s->match_length); 1082 check_match(s, s->strstart, s->match_start, s->match_length);
1104 1083
1105 bflush = zlib_tr_tally(s, s->strstart - s->match_start, 1084 bflush = zlib_tr_tally(s, s->strstart - s->match_start,
1106 s->match_length - MIN_MATCH); 1085 s->match_length - MIN_MATCH);
1107 1086
1108 s->lookahead -= s->match_length; 1087 s->lookahead -= s->match_length;
1109 1088
1110 /* Insert new strings in the hash table only if the match length 1089 /* Insert new strings in the hash table only if the match length
1111 * is not too large. This saves time but degrades compression. 1090 * is not too large. This saves time but degrades compression.
1112 */ 1091 */
1113 if (s->match_length <= s->max_insert_length && 1092 if (s->match_length <= s->max_insert_length &&
1114 s->lookahead >= MIN_MATCH) { 1093 s->lookahead >= MIN_MATCH) {
1115 s->match_length--; /* string at strstart already in hash table */ 1094 s->match_length--; /* string at strstart already in hash table */
1116 do { 1095 do {
1117 s->strstart++; 1096 s->strstart++;
1118 INSERT_STRING(s, s->strstart, hash_head); 1097 INSERT_STRING(s, s->strstart, hash_head);
1119 /* strstart never exceeds WSIZE-MAX_MATCH, so there are 1098 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1120 * always MIN_MATCH bytes ahead. 1099 * always MIN_MATCH bytes ahead.
1121 */ 1100 */
1122 } while (--s->match_length != 0); 1101 } while (--s->match_length != 0);
1123 s->strstart++; 1102 s->strstart++;
1124 } else { 1103 } else {
1125 s->strstart += s->match_length; 1104 s->strstart += s->match_length;
1126 s->match_length = 0; 1105 s->match_length = 0;
1127 s->ins_h = s->window[s->strstart]; 1106 s->ins_h = s->window[s->strstart];
1128 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); 1107 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1129 #if MIN_MATCH != 3 1108 #if MIN_MATCH != 3
1130 Call UPDATE_HASH() MIN_MATCH-3 more times 1109 Call UPDATE_HASH() MIN_MATCH-3 more times
1131 #endif 1110 #endif
1132 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not 1111 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1133 * matter since it will be recomputed at next deflate call. 1112 * matter since it will be recomputed at next deflate call.
1134 */ 1113 */
1135 } 1114 }
1136 } else { 1115 } else {
1137 /* No match, output a literal byte */ 1116 /* No match, output a literal byte */
1138 Tracevv((stderr,"%c", s->window[s->strstart])); 1117 Tracevv((stderr,"%c", s->window[s->strstart]));
1139 bflush = zlib_tr_tally (s, 0, s->window[s->strstart]); 1118 bflush = zlib_tr_tally (s, 0, s->window[s->strstart]);
1140 s->lookahead--; 1119 s->lookahead--;
1141 s->strstart++; 1120 s->strstart++;
1142 } 1121 }
1143 if (bflush) FLUSH_BLOCK(s, 0); 1122 if (bflush) FLUSH_BLOCK(s, 0);
1144 } 1123 }
1145 FLUSH_BLOCK(s, flush == Z_FINISH); 1124 FLUSH_BLOCK(s, flush == Z_FINISH);
1146 return flush == Z_FINISH ? finish_done : block_done; 1125 return flush == Z_FINISH ? finish_done : block_done;
1147 } 1126 }
1148 1127
1149 /* =========================================================================== 1128 /* ===========================================================================
1150 * Same as above, but achieves better compression. We use a lazy 1129 * Same as above, but achieves better compression. We use a lazy
1151 * evaluation for matches: a match is finally adopted only if there is 1130 * evaluation for matches: a match is finally adopted only if there is
1152 * no better match at the next window position. 1131 * no better match at the next window position.
1153 */ 1132 */
1154 static block_state deflate_slow( 1133 static block_state deflate_slow(
1155 deflate_state *s, 1134 deflate_state *s,
1156 int flush 1135 int flush
1157 ) 1136 )
1158 { 1137 {
1159 IPos hash_head = NIL; /* head of hash chain */ 1138 IPos hash_head = NIL; /* head of hash chain */
1160 int bflush; /* set if current block must be flushed */ 1139 int bflush; /* set if current block must be flushed */
1161 1140
1162 /* Process the input block. */ 1141 /* Process the input block. */
1163 for (;;) { 1142 for (;;) {
1164 /* Make sure that we always have enough lookahead, except 1143 /* Make sure that we always have enough lookahead, except
1165 * at the end of the input file. We need MAX_MATCH bytes 1144 * at the end of the input file. We need MAX_MATCH bytes
1166 * for the next match, plus MIN_MATCH bytes to insert the 1145 * for the next match, plus MIN_MATCH bytes to insert the
1167 * string following the next match. 1146 * string following the next match.
1168 */ 1147 */
1169 if (s->lookahead < MIN_LOOKAHEAD) { 1148 if (s->lookahead < MIN_LOOKAHEAD) {
1170 fill_window(s); 1149 fill_window(s);
1171 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { 1150 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1172 return need_more; 1151 return need_more;
1173 } 1152 }
1174 if (s->lookahead == 0) break; /* flush the current block */ 1153 if (s->lookahead == 0) break; /* flush the current block */
1175 } 1154 }
1176 1155
1177 /* Insert the string window[strstart .. strstart+2] in the 1156 /* Insert the string window[strstart .. strstart+2] in the
1178 * dictionary, and set hash_head to the head of the hash chain: 1157 * dictionary, and set hash_head to the head of the hash chain:
1179 */ 1158 */
1180 if (s->lookahead >= MIN_MATCH) { 1159 if (s->lookahead >= MIN_MATCH) {
1181 INSERT_STRING(s, s->strstart, hash_head); 1160 INSERT_STRING(s, s->strstart, hash_head);
1182 } 1161 }
1183 1162
1184 /* Find the longest match, discarding those <= prev_length. 1163 /* Find the longest match, discarding those <= prev_length.
1185 */ 1164 */
1186 s->prev_length = s->match_length, s->prev_match = s->match_start; 1165 s->prev_length = s->match_length, s->prev_match = s->match_start;
1187 s->match_length = MIN_MATCH-1; 1166 s->match_length = MIN_MATCH-1;
1188 1167
1189 if (hash_head != NIL && s->prev_length < s->max_lazy_match && 1168 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1190 s->strstart - hash_head <= MAX_DIST(s)) { 1169 s->strstart - hash_head <= MAX_DIST(s)) {
1191 /* To simplify the code, we prevent matches with the string 1170 /* To simplify the code, we prevent matches with the string
1192 * of window index 0 (in particular we have to avoid a match 1171 * of window index 0 (in particular we have to avoid a match
1193 * of the string with itself at the start of the input file). 1172 * of the string with itself at the start of the input file).
1194 */ 1173 */
1195 if (s->strategy != Z_HUFFMAN_ONLY) { 1174 if (s->strategy != Z_HUFFMAN_ONLY) {
1196 s->match_length = longest_match (s, hash_head); 1175 s->match_length = longest_match (s, hash_head);
1197 } 1176 }
1198 /* longest_match() sets match_start */ 1177 /* longest_match() sets match_start */
1199 1178
1200 if (s->match_length <= 5 && (s->strategy == Z_FILTERED || 1179 if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
1201 (s->match_length == MIN_MATCH && 1180 (s->match_length == MIN_MATCH &&
1202 s->strstart - s->match_start > TOO_FAR))) { 1181 s->strstart - s->match_start > TOO_FAR))) {
1203 1182
1204 /* If prev_match is also MIN_MATCH, match_start is garbage 1183 /* If prev_match is also MIN_MATCH, match_start is garbage
1205 * but we will ignore the current match anyway. 1184 * but we will ignore the current match anyway.
1206 */ 1185 */
1207 s->match_length = MIN_MATCH-1; 1186 s->match_length = MIN_MATCH-1;
1208 } 1187 }
1209 } 1188 }
1210 /* If there was a match at the previous step and the current 1189 /* If there was a match at the previous step and the current
1211 * match is not better, output the previous match: 1190 * match is not better, output the previous match:
1212 */ 1191 */
1213 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { 1192 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1214 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; 1193 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1215 /* Do not insert strings in hash table beyond this. */ 1194 /* Do not insert strings in hash table beyond this. */
1216 1195
1217 check_match(s, s->strstart-1, s->prev_match, s->prev_length); 1196 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1218 1197
1219 bflush = zlib_tr_tally(s, s->strstart -1 - s->prev_match, 1198 bflush = zlib_tr_tally(s, s->strstart -1 - s->prev_match,
1220 s->prev_length - MIN_MATCH); 1199 s->prev_length - MIN_MATCH);
1221 1200
1222 /* Insert in hash table all strings up to the end of the match. 1201 /* Insert in hash table all strings up to the end of the match.
1223 * strstart-1 and strstart are already inserted. If there is not 1202 * strstart-1 and strstart are already inserted. If there is not
1224 * enough lookahead, the last two strings are not inserted in 1203 * enough lookahead, the last two strings are not inserted in
1225 * the hash table. 1204 * the hash table.
1226 */ 1205 */
1227 s->lookahead -= s->prev_length-1; 1206 s->lookahead -= s->prev_length-1;
1228 s->prev_length -= 2; 1207 s->prev_length -= 2;
1229 do { 1208 do {
1230 if (++s->strstart <= max_insert) { 1209 if (++s->strstart <= max_insert) {
1231 INSERT_STRING(s, s->strstart, hash_head); 1210 INSERT_STRING(s, s->strstart, hash_head);
1232 } 1211 }
1233 } while (--s->prev_length != 0); 1212 } while (--s->prev_length != 0);
1234 s->match_available = 0; 1213 s->match_available = 0;
1235 s->match_length = MIN_MATCH-1; 1214 s->match_length = MIN_MATCH-1;
1236 s->strstart++; 1215 s->strstart++;
1237 1216
1238 if (bflush) FLUSH_BLOCK(s, 0); 1217 if (bflush) FLUSH_BLOCK(s, 0);
1239 1218
1240 } else if (s->match_available) { 1219 } else if (s->match_available) {
1241 /* If there was no match at the previous position, output a 1220 /* If there was no match at the previous position, output a
1242 * single literal. If there was a match but the current match 1221 * single literal. If there was a match but the current match
1243 * is longer, truncate the previous match to a single literal. 1222 * is longer, truncate the previous match to a single literal.
1244 */ 1223 */
1245 Tracevv((stderr,"%c", s->window[s->strstart-1])); 1224 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1246 if (zlib_tr_tally (s, 0, s->window[s->strstart-1])) { 1225 if (zlib_tr_tally (s, 0, s->window[s->strstart-1])) {
1247 FLUSH_BLOCK_ONLY(s, 0); 1226 FLUSH_BLOCK_ONLY(s, 0);
1248 } 1227 }
1249 s->strstart++; 1228 s->strstart++;
1250 s->lookahead--; 1229 s->lookahead--;
1251 if (s->strm->avail_out == 0) return need_more; 1230 if (s->strm->avail_out == 0) return need_more;
1252 } else { 1231 } else {
1253 /* There is no previous match to compare with, wait for 1232 /* There is no previous match to compare with, wait for
1254 * the next step to decide. 1233 * the next step to decide.
1255 */ 1234 */
1256 s->match_available = 1; 1235 s->match_available = 1;
1257 s->strstart++; 1236 s->strstart++;
1258 s->lookahead--; 1237 s->lookahead--;
1259 } 1238 }
1260 } 1239 }
1261 Assert (flush != Z_NO_FLUSH, "no flush?"); 1240 Assert (flush != Z_NO_FLUSH, "no flush?");
1262 if (s->match_available) { 1241 if (s->match_available) {
1263 Tracevv((stderr,"%c", s->window[s->strstart-1])); 1242 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1264 zlib_tr_tally (s, 0, s->window[s->strstart-1]); 1243 zlib_tr_tally (s, 0, s->window[s->strstart-1]);
1265 s->match_available = 0; 1244 s->match_available = 0;
1266 } 1245 }
1267 FLUSH_BLOCK(s, flush == Z_FINISH); 1246 FLUSH_BLOCK(s, flush == Z_FINISH);
1268 return flush == Z_FINISH ? finish_done : block_done; 1247 return flush == Z_FINISH ? finish_done : block_done;
1269 } 1248 }
1270 1249
1271 int zlib_deflate_workspacesize(void) 1250 int zlib_deflate_workspacesize(void)
1272 { 1251 {
1273 return sizeof(deflate_workspace); 1252 return sizeof(deflate_workspace);
1274 } 1253 }
1275 1254
lib/zlib_deflate/deflate_syms.c
1 /* 1 /*
2 * linux/lib/zlib_deflate/deflate_syms.c 2 * linux/lib/zlib_deflate/deflate_syms.c
3 * 3 *
4 * Exported symbols for the deflate functionality. 4 * Exported symbols for the deflate functionality.
5 * 5 *
6 */ 6 */
7 7
8 #include <linux/module.h> 8 #include <linux/module.h>
9 #include <linux/init.h> 9 #include <linux/init.h>
10 10
11 #include <linux/zlib.h> 11 #include <linux/zlib.h>
12 12
13 EXPORT_SYMBOL(zlib_deflate_workspacesize); 13 EXPORT_SYMBOL(zlib_deflate_workspacesize);
14 EXPORT_SYMBOL(zlib_deflate); 14 EXPORT_SYMBOL(zlib_deflate);
15 EXPORT_SYMBOL(zlib_deflateInit_); 15 EXPORT_SYMBOL(zlib_deflateInit2);
16 EXPORT_SYMBOL(zlib_deflateInit2_);
17 EXPORT_SYMBOL(zlib_deflateEnd); 16 EXPORT_SYMBOL(zlib_deflateEnd);
18 EXPORT_SYMBOL(zlib_deflateReset); 17 EXPORT_SYMBOL(zlib_deflateReset);
19 MODULE_LICENSE("GPL"); 18 MODULE_LICENSE("GPL");
20 19
lib/zlib_inflate/Makefile
1 # 1 #
2 # This is a modified version of zlib, which does all memory 2 # This is a modified version of zlib, which does all memory
3 # allocation ahead of time. 3 # allocation ahead of time.
4 # 4 #
5 # This is only the decompression, see zlib_deflate for the 5 # This is only the decompression, see zlib_deflate for the
6 # the compression 6 # the compression
7 # 7 #
8 # Decompression needs to be serialized for each memory 8 # Decompression needs to be serialized for each memory
9 # allocation. 9 # allocation.
10 # 10 #
11 # (The upsides of the simplification is that you can't get in 11 # (The upsides of the simplification is that you can't get in
12 # any nasty situations wrt memory management, and that the 12 # any nasty situations wrt memory management, and that the
13 # uncompression can be done without blocking on allocation). 13 # uncompression can be done without blocking on allocation).
14 # 14 #
15 15
16 obj-$(CONFIG_ZLIB_INFLATE) += zlib_inflate.o 16 obj-$(CONFIG_ZLIB_INFLATE) += zlib_inflate.o
17 17
18 zlib_inflate-objs := infblock.o infcodes.o inffast.o inflate.o \ 18 zlib_inflate-objs := inffast.o inflate.o \
19 inflate_sync.o inftrees.o infutil.o inflate_syms.o 19 inftrees.o inflate_syms.o
20 20
lib/zlib_inflate/infblock.c
1 /* infblock.c -- interpret and process block types to last block File was deleted
2 * Copyright (C) 1995-1998 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6 #include <linux/zutil.h>
7 #include "infblock.h"
8 #include "inftrees.h"
9 #include "infcodes.h"
10 #include "infutil.h"
11
12 struct inflate_codes_state;
13
14 /* simplify the use of the inflate_huft type with some defines */
15 #define exop word.what.Exop
16 #define bits word.what.Bits
17
18 /* Table for deflate from PKZIP's appnote.txt. */
19 static const uInt border[] = { /* Order of the bit length code lengths */
20 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
21
22 /*
23 Notes beyond the 1.93a appnote.txt:
24
25 1. Distance pointers never point before the beginning of the output
26 stream.
27 2. Distance pointers can point back across blocks, up to 32k away.
28 3. There is an implied maximum of 7 bits for the bit length table and
29 15 bits for the actual data.
30 4. If only one code exists, then it is encoded using one bit. (Zero
31 would be more efficient, but perhaps a little confusing.) If two
32 codes exist, they are coded using one bit each (0 and 1).
33 5. There is no way of sending zero distance codes--a dummy must be
34 sent if there are none. (History: a pre 2.0 version of PKZIP would
35 store blocks with no distance codes, but this was discovered to be
36 too harsh a criterion.) Valid only for 1.93a. 2.04c does allow
37 zero distance codes, which is sent as one code of zero bits in
38 length.
39 6. There are up to 286 literal/length codes. Code 256 represents the
40 end-of-block. Note however that the static length tree defines
41 288 codes just to fill out the Huffman codes. Codes 286 and 287
42 cannot be used though, since there is no length base or extra bits
43 defined for them. Similarily, there are up to 30 distance codes.
44 However, static trees define 32 codes (all 5 bits) to fill out the
45 Huffman codes, but the last two had better not show up in the data.
46 7. Unzip can check dynamic Huffman blocks for complete code sets.
47 The exception is that a single code would not be complete (see #4).
48 8. The five bits following the block type is really the number of
49 literal codes sent minus 257.
50 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
51 (1+6+6). Therefore, to output three times the length, you output
52 three codes (1+1+1), whereas to output four times the same length,
53 you only need two codes (1+3). Hmm.
54 10. In the tree reconstruction algorithm, Code = Code + Increment
55 only if BitLength(i) is not zero. (Pretty obvious.)
56 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19)
57 12. Note: length code 284 can represent 227-258, but length code 285
58 really is 258. The last length deserves its own, short code
59 since it gets used a lot in very redundant files. The length
60 258 is special since 258 - 3 (the min match length) is 255.
61 13. The literal/length and distance code bit lengths are read as a
62 single stream of lengths. It is possible (and advantageous) for
63 a repeat code (16, 17, or 18) to go across the boundary between
64 the two sets of lengths.
65 */
66
67
68 void zlib_inflate_blocks_reset(
69 inflate_blocks_statef *s,
70 z_streamp z,
71 uLong *c
72 )
73 {
74 if (c != NULL)
75 *c = s->check;
76 if (s->mode == CODES)
77 zlib_inflate_codes_free(s->sub.decode.codes, z);
78 s->mode = TYPE;
79 s->bitk = 0;
80 s->bitb = 0;
81 s->read = s->write = s->window;
82 if (s->checkfn != NULL)
83 z->adler = s->check = (*s->checkfn)(0L, NULL, 0);
84 }
85
86 inflate_blocks_statef *zlib_inflate_blocks_new(
87 z_streamp z,
88 check_func c,
89 uInt w
90 )
91 {
92 inflate_blocks_statef *s;
93
94 s = &WS(z)->working_blocks_state;
95 s->hufts = WS(z)->working_hufts;
96 s->window = WS(z)->working_window;
97 s->end = s->window + w;
98 s->checkfn = c;
99 s->mode = TYPE;
100 zlib_inflate_blocks_reset(s, z, NULL);
101 return s;
102 }
103
104
105 int zlib_inflate_blocks(
106 inflate_blocks_statef *s,
107 z_streamp z,
108 int r
109 )
110 {
111 uInt t; /* temporary storage */
112 uLong b; /* bit buffer */
113 uInt k; /* bits in bit buffer */
114 Byte *p; /* input data pointer */
115 uInt n; /* bytes available there */
116 Byte *q; /* output window write pointer */
117 uInt m; /* bytes to end of window or read pointer */
118
119 /* copy input/output information to locals (UPDATE macro restores) */
120 LOAD
121
122 /* process input based on current state */
123 while (1) switch (s->mode)
124 {
125 case TYPE:
126 NEEDBITS(3)
127 t = (uInt)b & 7;
128 s->last = t & 1;
129 switch (t >> 1)
130 {
131 case 0: /* stored */
132 DUMPBITS(3)
133 t = k & 7; /* go to byte boundary */
134 DUMPBITS(t)
135 s->mode = LENS; /* get length of stored block */
136 break;
137 case 1: /* fixed */
138 {
139 uInt bl, bd;
140 inflate_huft *tl, *td;
141
142 zlib_inflate_trees_fixed(&bl, &bd, &tl, &td, s->hufts, z);
143 s->sub.decode.codes = zlib_inflate_codes_new(bl, bd, tl, td, z);
144 if (s->sub.decode.codes == NULL)
145 {
146 r = Z_MEM_ERROR;
147 LEAVE
148 }
149 }
150 DUMPBITS(3)
151 s->mode = CODES;
152 break;
153 case 2: /* dynamic */
154 DUMPBITS(3)
155 s->mode = TABLE;
156 break;
157 case 3: /* illegal */
158 DUMPBITS(3)
159 s->mode = B_BAD;
160 z->msg = (char*)"invalid block type";
161 r = Z_DATA_ERROR;
162 LEAVE
163 }
164 break;
165 case LENS:
166 NEEDBITS(32)
167 if ((((~b) >> 16) & 0xffff) != (b & 0xffff))
168 {
169 s->mode = B_BAD;
170 z->msg = (char*)"invalid stored block lengths";
171 r = Z_DATA_ERROR;
172 LEAVE
173 }
174 s->sub.left = (uInt)b & 0xffff;
175 b = k = 0; /* dump bits */
176 s->mode = s->sub.left ? STORED : (s->last ? DRY : TYPE);
177 break;
178 case STORED:
179 if (n == 0)
180 LEAVE
181 NEEDOUT
182 t = s->sub.left;
183 if (t > n) t = n;
184 if (t > m) t = m;
185 memcpy(q, p, t);
186 p += t; n -= t;
187 q += t; m -= t;
188 if ((s->sub.left -= t) != 0)
189 break;
190 s->mode = s->last ? DRY : TYPE;
191 break;
192 case TABLE:
193 NEEDBITS(14)
194 s->sub.trees.table = t = (uInt)b & 0x3fff;
195 #ifndef PKZIP_BUG_WORKAROUND
196 if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
197 {
198 s->mode = B_BAD;
199 z->msg = (char*)"too many length or distance symbols";
200 r = Z_DATA_ERROR;
201 LEAVE
202 }
203 #endif
204 {
205 s->sub.trees.blens = WS(z)->working_blens;
206 }
207 DUMPBITS(14)
208 s->sub.trees.index = 0;
209 s->mode = BTREE;
210 case BTREE:
211 while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10))
212 {
213 NEEDBITS(3)
214 s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7;
215 DUMPBITS(3)
216 }
217 while (s->sub.trees.index < 19)
218 s->sub.trees.blens[border[s->sub.trees.index++]] = 0;
219 s->sub.trees.bb = 7;
220 t = zlib_inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb,
221 &s->sub.trees.tb, s->hufts, z);
222 if (t != Z_OK)
223 {
224 r = t;
225 if (r == Z_DATA_ERROR)
226 s->mode = B_BAD;
227 LEAVE
228 }
229 s->sub.trees.index = 0;
230 s->mode = DTREE;
231 case DTREE:
232 while (t = s->sub.trees.table,
233 s->sub.trees.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))
234 {
235 inflate_huft *h;
236 uInt i, j, c;
237
238 t = s->sub.trees.bb;
239 NEEDBITS(t)
240 h = s->sub.trees.tb + ((uInt)b & zlib_inflate_mask[t]);
241 t = h->bits;
242 c = h->base;
243 if (c < 16)
244 {
245 DUMPBITS(t)
246 s->sub.trees.blens[s->sub.trees.index++] = c;
247 }
248 else /* c == 16..18 */
249 {
250 i = c == 18 ? 7 : c - 14;
251 j = c == 18 ? 11 : 3;
252 NEEDBITS(t + i)
253 DUMPBITS(t)
254 j += (uInt)b & zlib_inflate_mask[i];
255 DUMPBITS(i)
256 i = s->sub.trees.index;
257 t = s->sub.trees.table;
258 if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||
259 (c == 16 && i < 1))
260 {
261 s->mode = B_BAD;
262 z->msg = (char*)"invalid bit length repeat";
263 r = Z_DATA_ERROR;
264 LEAVE
265 }
266 c = c == 16 ? s->sub.trees.blens[i - 1] : 0;
267 do {
268 s->sub.trees.blens[i++] = c;
269 } while (--j);
270 s->sub.trees.index = i;
271 }
272 }
273 s->sub.trees.tb = NULL;
274 {
275 uInt bl, bd;
276 inflate_huft *tl, *td;
277 inflate_codes_statef *c;
278
279 bl = 9; /* must be <= 9 for lookahead assumptions */
280 bd = 6; /* must be <= 9 for lookahead assumptions */
281 t = s->sub.trees.table;
282 t = zlib_inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f),
283 s->sub.trees.blens, &bl, &bd, &tl, &td,
284 s->hufts, z);
285 if (t != Z_OK)
286 {
287 if (t == (uInt)Z_DATA_ERROR)
288 s->mode = B_BAD;
289 r = t;
290 LEAVE
291 }
292 if ((c = zlib_inflate_codes_new(bl, bd, tl, td, z)) == NULL)
293 {
294 r = Z_MEM_ERROR;
295 LEAVE
296 }
297 s->sub.decode.codes = c;
298 }
299 s->mode = CODES;
300 case CODES:
301 UPDATE
302 if ((r = zlib_inflate_codes(s, z, r)) != Z_STREAM_END)
303 return zlib_inflate_flush(s, z, r);
304 r = Z_OK;
305 zlib_inflate_codes_free(s->sub.decode.codes, z);
306 LOAD
307 if (!s->last)
308 {
309 s->mode = TYPE;
310 break;
311 }
312 s->mode = DRY;
313 case DRY:
314 FLUSH
315 if (s->read != s->write)
316 LEAVE
317 s->mode = B_DONE;
318 case B_DONE:
319 r = Z_STREAM_END;
320 LEAVE
321 case B_BAD:
322 r = Z_DATA_ERROR;
323 LEAVE
324 default:
325 r = Z_STREAM_ERROR;
326 LEAVE
327 }
328 }
329
330
331 int zlib_inflate_blocks_free(
332 inflate_blocks_statef *s,
333 z_streamp z
334 )
335 {
336 zlib_inflate_blocks_reset(s, z, NULL);
337 return Z_OK;
338 }
339
340
341 #if 0
342 void zlib_inflate_set_dictionary(
343 inflate_blocks_statef *s,
344 const Byte *d,
345 uInt n
346 )
347 {
348 memcpy(s->window, d, n);
349 s->read = s->write = s->window + n;
350 }
351 #endif /* 0 */
352
353
354 /* Returns true if inflate is currently at the end of a block generated
355 * by Z_SYNC_FLUSH or Z_FULL_FLUSH.
356 * IN assertion: s != NULL
357 */
358 #if 0
359 int zlib_inflate_blocks_sync_point(
360 inflate_blocks_statef *s
361 )
362 {
363 return s->mode == LENS;
364 }
365 #endif /* 0 */
366 1 /* infblock.c -- interpret and process block types to last block
lib/zlib_inflate/infblock.h
1 /* infblock.h -- header to use infblock.c File was deleted
2 * Copyright (C) 1995-1998 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6 /* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h.
9 */
10
11 #ifndef _INFBLOCK_H
12 #define _INFBLOCK_H
13
14 struct inflate_blocks_state;
15 typedef struct inflate_blocks_state inflate_blocks_statef;
16
17 extern inflate_blocks_statef * zlib_inflate_blocks_new (
18 z_streamp z,
19 check_func c, /* check function */
20 uInt w); /* window size */
21
22 extern int zlib_inflate_blocks (
23 inflate_blocks_statef *,
24 z_streamp ,
25 int); /* initial return code */
26
27 extern void zlib_inflate_blocks_reset (
28 inflate_blocks_statef *,
29 z_streamp ,
30 uLong *); /* check value on output */
31
32 extern int zlib_inflate_blocks_free (
33 inflate_blocks_statef *,
34 z_streamp);
35
36 #if 0
37 extern void zlib_inflate_set_dictionary (
38 inflate_blocks_statef *s,
39 const Byte *d, /* dictionary */
40 uInt n); /* dictionary length */
41 #endif /* 0 */
42
43 #if 0
44 extern int zlib_inflate_blocks_sync_point (
45 inflate_blocks_statef *s);
46 #endif /* 0 */
47
48 #endif /* _INFBLOCK_H */
49 1 /* infblock.h -- header to use infblock.c
lib/zlib_inflate/infcodes.c
1 /* infcodes.c -- process literals and length/distance pairs File was deleted
2 * Copyright (C) 1995-1998 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6 #include <linux/zutil.h>
7 #include "inftrees.h"
8 #include "infblock.h"
9 #include "infcodes.h"
10 #include "infutil.h"
11 #include "inffast.h"
12
13 /* simplify the use of the inflate_huft type with some defines */
14 #define exop word.what.Exop
15 #define bits word.what.Bits
16
17 inflate_codes_statef *zlib_inflate_codes_new(
18 uInt bl,
19 uInt bd,
20 inflate_huft *tl,
21 inflate_huft *td, /* need separate declaration for Borland C++ */
22 z_streamp z
23 )
24 {
25 inflate_codes_statef *c;
26
27 c = &WS(z)->working_state;
28 {
29 c->mode = START;
30 c->lbits = (Byte)bl;
31 c->dbits = (Byte)bd;
32 c->ltree = tl;
33 c->dtree = td;
34 }
35 return c;
36 }
37
38
39 int zlib_inflate_codes(
40 inflate_blocks_statef *s,
41 z_streamp z,
42 int r
43 )
44 {
45 uInt j; /* temporary storage */
46 inflate_huft *t; /* temporary pointer */
47 uInt e; /* extra bits or operation */
48 uLong b; /* bit buffer */
49 uInt k; /* bits in bit buffer */
50 Byte *p; /* input data pointer */
51 uInt n; /* bytes available there */
52 Byte *q; /* output window write pointer */
53 uInt m; /* bytes to end of window or read pointer */
54 Byte *f; /* pointer to copy strings from */
55 inflate_codes_statef *c = s->sub.decode.codes; /* codes state */
56
57 /* copy input/output information to locals (UPDATE macro restores) */
58 LOAD
59
60 /* process input and output based on current state */
61 while (1) switch (c->mode)
62 { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
63 case START: /* x: set up for LEN */
64 #ifndef SLOW
65 if (m >= 258 && n >= 10)
66 {
67 UPDATE
68 r = zlib_inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z);
69 LOAD
70 if (r != Z_OK)
71 {
72 c->mode = r == Z_STREAM_END ? WASH : BADCODE;
73 break;
74 }
75 }
76 #endif /* !SLOW */
77 c->sub.code.need = c->lbits;
78 c->sub.code.tree = c->ltree;
79 c->mode = LEN;
80 case LEN: /* i: get length/literal/eob next */
81 j = c->sub.code.need;
82 NEEDBITS(j)
83 t = c->sub.code.tree + ((uInt)b & zlib_inflate_mask[j]);
84 DUMPBITS(t->bits)
85 e = (uInt)(t->exop);
86 if (e == 0) /* literal */
87 {
88 c->sub.lit = t->base;
89 c->mode = LIT;
90 break;
91 }
92 if (e & 16) /* length */
93 {
94 c->sub.copy.get = e & 15;
95 c->len = t->base;
96 c->mode = LENEXT;
97 break;
98 }
99 if ((e & 64) == 0) /* next table */
100 {
101 c->sub.code.need = e;
102 c->sub.code.tree = t + t->base;
103 break;
104 }
105 if (e & 32) /* end of block */
106 {
107 c->mode = WASH;
108 break;
109 }
110 c->mode = BADCODE; /* invalid code */
111 z->msg = (char*)"invalid literal/length code";
112 r = Z_DATA_ERROR;
113 LEAVE
114 case LENEXT: /* i: getting length extra (have base) */
115 j = c->sub.copy.get;
116 NEEDBITS(j)
117 c->len += (uInt)b & zlib_inflate_mask[j];
118 DUMPBITS(j)
119 c->sub.code.need = c->dbits;
120 c->sub.code.tree = c->dtree;
121 c->mode = DIST;
122 case DIST: /* i: get distance next */
123 j = c->sub.code.need;
124 NEEDBITS(j)
125 t = c->sub.code.tree + ((uInt)b & zlib_inflate_mask[j]);
126 DUMPBITS(t->bits)
127 e = (uInt)(t->exop);
128 if (e & 16) /* distance */
129 {
130 c->sub.copy.get = e & 15;
131 c->sub.copy.dist = t->base;
132 c->mode = DISTEXT;
133 break;
134 }
135 if ((e & 64) == 0) /* next table */
136 {
137 c->sub.code.need = e;
138 c->sub.code.tree = t + t->base;
139 break;
140 }
141 c->mode = BADCODE; /* invalid code */
142 z->msg = (char*)"invalid distance code";
143 r = Z_DATA_ERROR;
144 LEAVE
145 case DISTEXT: /* i: getting distance extra */
146 j = c->sub.copy.get;
147 NEEDBITS(j)
148 c->sub.copy.dist += (uInt)b & zlib_inflate_mask[j];
149 DUMPBITS(j)
150 c->mode = COPY;
151 case COPY: /* o: copying bytes in window, waiting for space */
152 f = q - c->sub.copy.dist;
153 while (f < s->window) /* modulo window size-"while" instead */
154 f += s->end - s->window; /* of "if" handles invalid distances */
155 while (c->len)
156 {
157 NEEDOUT
158 OUTBYTE(*f++)
159 if (f == s->end)
160 f = s->window;
161 c->len--;
162 }
163 c->mode = START;
164 break;
165 case LIT: /* o: got literal, waiting for output space */
166 NEEDOUT
167 OUTBYTE(c->sub.lit)
168 c->mode = START;
169 break;
170 case WASH: /* o: got eob, possibly more output */
171 if (k > 7) /* return unused byte, if any */
172 {
173 k -= 8;
174 n++;
175 p--; /* can always return one */
176 }
177 FLUSH
178 if (s->read != s->write)
179 LEAVE
180 c->mode = END;
181 case END:
182 r = Z_STREAM_END;
183 LEAVE
184 case BADCODE: /* x: got error */
185 r = Z_DATA_ERROR;
186 LEAVE
187 default:
188 r = Z_STREAM_ERROR;
189 LEAVE
190 }
191 #ifdef NEED_DUMMY_RETURN
192 return Z_STREAM_ERROR; /* Some dumb compilers complain without this */
193 #endif
194 }
195
196
197 void zlib_inflate_codes_free(
198 inflate_codes_statef *c,
199 z_streamp z
200 )
201 {
202 }
203 1 /* infcodes.c -- process literals and length/distance pairs
lib/zlib_inflate/infcodes.h
1 /* infcodes.h -- header to use infcodes.c File was deleted
2 * Copyright (C) 1995-1998 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6 /* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h.
9 */
10
11 #ifndef _INFCODES_H
12 #define _INFCODES_H
13
14 #include "infblock.h"
15
16 struct inflate_codes_state;
17 typedef struct inflate_codes_state inflate_codes_statef;
18
19 extern inflate_codes_statef *zlib_inflate_codes_new (
20 uInt, uInt,
21 inflate_huft *, inflate_huft *,
22 z_streamp );
23
24 extern int zlib_inflate_codes (
25 inflate_blocks_statef *,
26 z_streamp ,
27 int);
28
29 extern void zlib_inflate_codes_free (
30 inflate_codes_statef *,
31 z_streamp );
32
33 #endif /* _INFCODES_H */
34 1 /* infcodes.h -- header to use infcodes.c
lib/zlib_inflate/inffast.c
1 /* inffast.c -- process literals and length/distance pairs fast 1 /* inffast.c -- fast decoding
2 * Copyright (C) 1995-1998 Mark Adler 2 * Copyright (C) 1995-2004 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6 #include <linux/zutil.h> 6 #include <linux/zutil.h>
7 #include "inftrees.h" 7 #include "inftrees.h"
8 #include "infblock.h" 8 #include "inflate.h"
9 #include "infcodes.h"
10 #include "infutil.h"
11 #include "inffast.h" 9 #include "inffast.h"
12 10
13 struct inflate_codes_state; 11 #ifndef ASMINF
14 12
15 /* simplify the use of the inflate_huft type with some defines */ 13 /* Allow machine dependent optimization for post-increment or pre-increment.
16 #define exop word.what.Exop 14 Based on testing to date,
17 #define bits word.what.Bits 15 Pre-increment preferred for:
16 - PowerPC G3 (Adler)
17 - MIPS R5000 (Randers-Pehrson)
18 Post-increment preferred for:
19 - none
20 No measurable difference:
21 - Pentium III (Anderson)
22 - M68060 (Nikl)
23 */
24 #ifdef POSTINC
25 # define OFF 0
26 # define PUP(a) *(a)++
27 #else
28 # define OFF 1
29 # define PUP(a) *++(a)
30 #endif
18 31
19 /* macros for bit input with no checking and for returning unused bytes */ 32 /*
20 #define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<<k;k+=8;}} 33 Decode literal, length, and distance codes and write out the resulting
21 #define UNGRAB {c=z->avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;} 34 literal and match bytes until either not enough input or output is
35 available, an end-of-block is encountered, or a data error is encountered.
36 When large enough input and output buffers are supplied to inflate(), for
37 example, a 16K input buffer and a 64K output buffer, more than 95% of the
38 inflate execution time is spent in this routine.
22 39
23 /* Called with number of bytes left to write in window at least 258 40 Entry assumptions:
24 (the maximum string length) and number of input bytes available
25 at least ten. The ten bytes are six bytes for the longest length/
26 distance pair plus four bytes for overloading the bit buffer. */
27 41
28 int zlib_inflate_fast( 42 state->mode == LEN
29 uInt bl, 43 strm->avail_in >= 6
30 uInt bd, 44 strm->avail_out >= 258
31 inflate_huft *tl, 45 start >= strm->avail_out
32 inflate_huft *td, /* need separate declaration for Borland C++ */ 46 state->bits < 8
33 inflate_blocks_statef *s,
34 z_streamp z
35 )
36 {
37 inflate_huft *t; /* temporary pointer */
38 uInt e; /* extra bits or operation */
39 uLong b; /* bit buffer */
40 uInt k; /* bits in bit buffer */
41 Byte *p; /* input data pointer */
42 uInt n; /* bytes available there */
43 Byte *q; /* output window write pointer */
44 uInt m; /* bytes to end of window or read pointer */
45 uInt ml; /* mask for literal/length tree */
46 uInt md; /* mask for distance tree */
47 uInt c; /* bytes to copy */
48 uInt d; /* distance back to copy from */
49 Byte *r; /* copy source pointer */
50 47
51 /* load input, output, bit values */ 48 On return, state->mode is one of:
52 LOAD
53 49
54 /* initialize masks */ 50 LEN -- ran out of enough output space or enough available input
55 ml = zlib_inflate_mask[bl]; 51 TYPE -- reached end of block code, inflate() to interpret next block
56 md = zlib_inflate_mask[bd]; 52 BAD -- error in block data
57 53
58 /* do until not enough input or output space for fast loop */ 54 Notes:
59 do { /* assume called with m >= 258 && n >= 10 */
60 /* get literal/length code */
61 GRABBITS(20) /* max bits for literal/length code */
62 if ((e = (t = tl + ((uInt)b & ml))->exop) == 0)
63 {
64 DUMPBITS(t->bits)
65 *q++ = (Byte)t->base;
66 m--;
67 continue;
68 }
69 do {
70 DUMPBITS(t->bits)
71 if (e & 16)
72 {
73 /* get extra bits for length */
74 e &= 15;
75 c = t->base + ((uInt)b & zlib_inflate_mask[e]);
76 DUMPBITS(e)
77 55
78 /* decode distance base of block to copy */ 56 - The maximum input bits used by a length/distance pair is 15 bits for the
79 GRABBITS(15); /* max bits for distance code */ 57 length code, 5 bits for the length extra, 15 bits for the distance code,
80 e = (t = td + ((uInt)b & md))->exop; 58 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
81 do { 59 Therefore if strm->avail_in >= 6, then there is enough input to avoid
82 DUMPBITS(t->bits) 60 checking for available input while decoding.
83 if (e & 16)
84 {
85 /* get extra bits to add to distance base */
86 e &= 15;
87 GRABBITS(e) /* get extra bits (up to 13) */
88 d = t->base + ((uInt)b & zlib_inflate_mask[e]);
89 DUMPBITS(e)
90 61
91 /* do the copy */ 62 - The maximum bytes that a single length/distance pair can output is 258
92 m -= c; 63 bytes, which is the maximum length that can be coded. inflate_fast()
93 r = q - d; 64 requires strm->avail_out >= 258 for each loop to avoid checking for
94 if (r < s->window) /* wrap if needed */ 65 output space.
95 { 66 */
96 do { 67 void inflate_fast(strm, start)
97 r += s->end - s->window; /* force pointer in window */ 68 z_streamp strm;
98 } while (r < s->window); /* covers invalid distances */ 69 unsigned start; /* inflate()'s starting value for strm->avail_out */
99 e = s->end - r; 70 {
100 if (c > e) 71 struct inflate_state *state;
101 { 72 unsigned char *in; /* local strm->next_in */
102 c -= e; /* wrapped copy */ 73 unsigned char *last; /* while in < last, enough input available */
103 do { 74 unsigned char *out; /* local strm->next_out */
104 *q++ = *r++; 75 unsigned char *beg; /* inflate()'s initial strm->next_out */
105 } while (--e); 76 unsigned char *end; /* while out < end, enough space available */
106 r = s->window; 77 #ifdef INFLATE_STRICT
107 do { 78 unsigned dmax; /* maximum distance from zlib header */
108 *q++ = *r++; 79 #endif
109 } while (--c); 80 unsigned wsize; /* window size or zero if not using window */
110 } 81 unsigned whave; /* valid bytes in the window */
111 else /* normal copy */ 82 unsigned write; /* window write index */
112 { 83 unsigned char *window; /* allocated sliding window, if wsize != 0 */
113 *q++ = *r++; c--; 84 unsigned long hold; /* local strm->hold */
114 *q++ = *r++; c--; 85 unsigned bits; /* local strm->bits */
115 do { 86 code const *lcode; /* local strm->lencode */
116 *q++ = *r++; 87 code const *dcode; /* local strm->distcode */
117 } while (--c); 88 unsigned lmask; /* mask for first level of length codes */
118 } 89 unsigned dmask; /* mask for first level of distance codes */
90 code this; /* retrieved table entry */
91 unsigned op; /* code bits, operation, extra bits, or */
92 /* window position, window bytes to copy */
93 unsigned len; /* match length, unused bytes */
94 unsigned dist; /* match distance */
95 unsigned char *from; /* where to copy match from */
96
97 /* copy state to local variables */
98 state = (struct inflate_state *)strm->state;
99 in = strm->next_in - OFF;
100 last = in + (strm->avail_in - 5);
101 out = strm->next_out - OFF;
102 beg = out - (start - strm->avail_out);
103 end = out + (strm->avail_out - 257);
104 #ifdef INFLATE_STRICT
105 dmax = state->dmax;
106 #endif
107 wsize = state->wsize;
108 whave = state->whave;
109 write = state->write;
110 window = state->window;
111 hold = state->hold;
112 bits = state->bits;
113 lcode = state->lencode;
114 dcode = state->distcode;
115 lmask = (1U << state->lenbits) - 1;
116 dmask = (1U << state->distbits) - 1;
117
118 /* decode literals and length/distances until end-of-block or not enough
119 input data or output space */
120 do {
121 if (bits < 15) {
122 hold += (unsigned long)(PUP(in)) << bits;
123 bits += 8;
124 hold += (unsigned long)(PUP(in)) << bits;
125 bits += 8;
126 }
127 this = lcode[hold & lmask];
128 dolen:
129 op = (unsigned)(this.bits);
130 hold >>= op;
131 bits -= op;
132 op = (unsigned)(this.op);
133 if (op == 0) { /* literal */
134 PUP(out) = (unsigned char)(this.val);
135 }
136 else if (op & 16) { /* length base */
137 len = (unsigned)(this.val);
138 op &= 15; /* number of extra bits */
139 if (op) {
140 if (bits < op) {
141 hold += (unsigned long)(PUP(in)) << bits;
142 bits += 8;
143 }
144 len += (unsigned)hold & ((1U << op) - 1);
145 hold >>= op;
146 bits -= op;
119 } 147 }
120 else /* normal copy */ 148 if (bits < 15) {
121 { 149 hold += (unsigned long)(PUP(in)) << bits;
122 *q++ = *r++; c--; 150 bits += 8;
123 *q++ = *r++; c--; 151 hold += (unsigned long)(PUP(in)) << bits;
124 do { 152 bits += 8;
125 *q++ = *r++;
126 } while (--c);
127 } 153 }
154 this = dcode[hold & dmask];
155 dodist:
156 op = (unsigned)(this.bits);
157 hold >>= op;
158 bits -= op;
159 op = (unsigned)(this.op);
160 if (op & 16) { /* distance base */
161 dist = (unsigned)(this.val);
162 op &= 15; /* number of extra bits */
163 if (bits < op) {
164 hold += (unsigned long)(PUP(in)) << bits;
165 bits += 8;
166 if (bits < op) {
167 hold += (unsigned long)(PUP(in)) << bits;
168 bits += 8;
169 }
170 }
171 dist += (unsigned)hold & ((1U << op) - 1);
172 #ifdef INFLATE_STRICT
173 if (dist > dmax) {
174 strm->msg = (char *)"invalid distance too far back";
175 state->mode = BAD;
176 break;
177 }
178 #endif
179 hold >>= op;
180 bits -= op;
181 op = (unsigned)(out - beg); /* max distance in output */
182 if (dist > op) { /* see if copy from window */
183 op = dist - op; /* distance back in window */
184 if (op > whave) {
185 strm->msg = (char *)"invalid distance too far back";
186 state->mode = BAD;
187 break;
188 }
189 from = window - OFF;
190 if (write == 0) { /* very common case */
191 from += wsize - op;
192 if (op < len) { /* some from window */
193 len -= op;
194 do {
195 PUP(out) = PUP(from);
196 } while (--op);
197 from = out - dist; /* rest from output */
198 }
199 }
200 else if (write < op) { /* wrap around window */
201 from += wsize + write - op;
202 op -= write;
203 if (op < len) { /* some from end of window */
204 len -= op;
205 do {
206 PUP(out) = PUP(from);
207 } while (--op);
208 from = window - OFF;
209 if (write < len) { /* some from start of window */
210 op = write;
211 len -= op;
212 do {
213 PUP(out) = PUP(from);
214 } while (--op);
215 from = out - dist; /* rest from output */
216 }
217 }
218 }
219 else { /* contiguous in window */
220 from += write - op;
221 if (op < len) { /* some from window */
222 len -= op;
223 do {
224 PUP(out) = PUP(from);
225 } while (--op);
226 from = out - dist; /* rest from output */
227 }
228 }
229 while (len > 2) {
230 PUP(out) = PUP(from);
231 PUP(out) = PUP(from);
232 PUP(out) = PUP(from);
233 len -= 3;
234 }
235 if (len) {
236 PUP(out) = PUP(from);
237 if (len > 1)
238 PUP(out) = PUP(from);
239 }
240 }
241 else {
242 from = out - dist; /* copy direct from output */
243 do { /* minimum length is three */
244 PUP(out) = PUP(from);
245 PUP(out) = PUP(from);
246 PUP(out) = PUP(from);
247 len -= 3;
248 } while (len > 2);
249 if (len) {
250 PUP(out) = PUP(from);
251 if (len > 1)
252 PUP(out) = PUP(from);
253 }
254 }
255 }
256 else if ((op & 64) == 0) { /* 2nd level distance code */
257 this = dcode[this.val + (hold & ((1U << op) - 1))];
258 goto dodist;
259 }
260 else {
261 strm->msg = (char *)"invalid distance code";
262 state->mode = BAD;
263 break;
lib/zlib_inflate/inffast.h
1 /* inffast.h -- header to use inffast.c 1 /* inffast.h -- header to use inffast.c
2 * Copyright (C) 1995-1998 Mark Adler 2 * Copyright (C) 1995-2003 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6 /* WARNING: this file should *not* be used by applications. It is 6 /* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is 7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h. 8 subject to change. Applications should only use zlib.h.
9 */ 9 */
10 10
11 extern int zlib_inflate_fast ( 11 void inflate_fast (z_streamp strm, unsigned start);
12 uInt,
13 uInt,
14 inflate_huft *,
15 inflate_huft *,
16 inflate_blocks_statef *,
17 z_streamp );
18 12
lib/zlib_inflate/inffixed.h
File was created 1 /* inffixed.h -- table for decoding fixed codes
2 * Generated automatically by makefixed().
3 */
4
5 /* WARNING: this file should *not* be used by applications. It
6 is part of the implementation of the compression library and
7 is subject to change. Applications should only use zlib.h.
8 */
9
10 static const code lenfix[512] = {
11 {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
12 {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
13 {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
14 {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
15 {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
16 {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
17 {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
18 {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
19 {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
20 {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
21 {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
22 {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
23 {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
24 {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
25 {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
26 {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
27 {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
28 {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
29 {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
30 {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
31 {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
32 {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
33 {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
34 {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
35 {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
36 {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
37 {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
38 {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
39 {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
40 {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
41 {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
42 {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
43 {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
44 {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
45 {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
46 {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
47 {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
48 {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
49 {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
50 {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
51 {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
52 {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
53 {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
54 {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
55 {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
56 {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
57 {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
58 {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
59 {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
60 {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
61 {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
62 {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
63 {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
64 {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
65 {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
66 {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
67 {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
68 {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
69 {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
70 {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
71 {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
72 {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
73 {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
74 {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
75 {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
76 {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
77 {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
78 {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
79 {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
80 {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
81 {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
82 {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
83 {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
84 {0,9,255}
85 };
86
87 static const code distfix[32] = {
88 {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
89 {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
90 {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
91 {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
92 {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
93 {22,5,193},{64,5,0}
94 };
95
lib/zlib_inflate/inflate.c
1 /* inflate.c -- zlib interface to inflate modules 1 /* inflate.c -- zlib decompression
2 * Copyright (C) 1995-1998 Mark Adler 2 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 *
5 * Based on zlib 1.2.3 but modified for the Linux Kernel by
6 * Richard Purdie <richard@openedhand.com>
7 *
8 * Changes mainly for static instead of dynamic memory allocation
9 *
4 */ 10 */
5 11
6 #include <linux/zutil.h> 12 #include <linux/zutil.h>
7 #include "infblock.h" 13 #include "inftrees.h"
14 #include "inflate.h"
15 #include "inffast.h"
8 #include "infutil.h" 16 #include "infutil.h"
9 17
10 int zlib_inflate_workspacesize(void) 18 int zlib_inflate_workspacesize(void)
11 { 19 {
12 return sizeof(struct inflate_workspace); 20 return sizeof(struct inflate_workspace);
13 } 21 }
14 22
15 23 int zlib_inflateReset(z_streamp strm)
16 int zlib_inflateReset(
17 z_streamp z
18 )
19 { 24 {
20 if (z == NULL || z->state == NULL || z->workspace == NULL) 25 struct inflate_state *state;
21 return Z_STREAM_ERROR;
22 z->total_in = z->total_out = 0;
23 z->msg = NULL;
24 z->state->mode = z->state->nowrap ? BLOCKS : METHOD;
25 zlib_inflate_blocks_reset(z->state->blocks, z, NULL);
26 return Z_OK;
27 }
28 26
27 if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR;
28 state = (struct inflate_state *)strm->state;
29 strm->total_in = strm->total_out = state->total = 0;
30 strm->msg = NULL;
31 strm->adler = 1; /* to support ill-conceived Java test suite */
32 state->mode = HEAD;
33 state->last = 0;
34 state->havedict = 0;
35 state->dmax = 32768U;
36 state->hold = 0;
37 state->bits = 0;
38 state->lencode = state->distcode = state->next = state->codes;
29 39
30 int zlib_inflateEnd( 40 /* Initialise Window */
31 z_streamp z 41 state->wsize = 1U << state->wbits;
32 ) 42 state->write = 0;
43 state->whave = 0;
44
45 return Z_OK;
46 }
47
48 #if 0
49 int zlib_inflatePrime(z_streamp strm, int bits, int value)
33 { 50 {
34 if (z == NULL || z->state == NULL || z->workspace == NULL) 51 struct inflate_state *state;
35 return Z_STREAM_ERROR; 52
36 if (z->state->blocks != NULL) 53 if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR;
37 zlib_inflate_blocks_free(z->state->blocks, z); 54 state = (struct inflate_state *)strm->state;
38 z->state = NULL; 55 if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
39 return Z_OK; 56 value &= (1L << bits) - 1;
57 state->hold += value << state->bits;
58 state->bits += bits;
59 return Z_OK;
40 } 60 }
61 #endif
41 62
63 int zlib_inflateInit2(z_streamp strm, int windowBits)
64 {
65 struct inflate_state *state;
42 66
43 int zlib_inflateInit2_( 67 if (strm == NULL) return Z_STREAM_ERROR;
44 z_streamp z, 68 strm->msg = NULL; /* in case we return an error */
45 int w, 69
46 const char *version, 70 state = &WS(strm)->inflate_state;
47 int stream_size 71 strm->state = (struct internal_state *)state;
48 ) 72
73 if (windowBits < 0) {
74 state->wrap = 0;
75 windowBits = -windowBits;
76 }
77 else {
78 state->wrap = (windowBits >> 4) + 1;
79 }
80 if (windowBits < 8 || windowBits > 15) {
81 return Z_STREAM_ERROR;
82 }
83 state->wbits = (unsigned)windowBits;
84 state->window = &WS(strm)->working_window[0];
85
86 return zlib_inflateReset(strm);
87 }
88
89 /*
90 Return state with length and distance decoding tables and index sizes set to
91 fixed code decoding. This returns fixed tables from inffixed.h.
92 */
93 static void zlib_fixedtables(struct inflate_state *state)
49 { 94 {
50 if (version == NULL || version[0] != ZLIB_VERSION[0] || 95 # include "inffixed.h"
51 stream_size != sizeof(z_stream) || z->workspace == NULL) 96 state->lencode = lenfix;
52 return Z_VERSION_ERROR; 97 state->lenbits = 9;
98 state->distcode = distfix;
99 state->distbits = 5;
100 }
53 101
54 /* initialize state */
55 z->msg = NULL;
56 z->state = &WS(z)->internal_state;
57 z->state->blocks = NULL;
58 102
59 /* handle undocumented nowrap option (no zlib header or check) */ 103 /*
60 z->state->nowrap = 0; 104 Update the window with the last wsize (normally 32K) bytes written before
61 if (w < 0) 105 returning. This is only called when a window is already in use, or when
62 { 106 output has been written during this inflate call, but the end of the deflate
63 w = - w; 107 stream has not been reached yet. It is also called to window dictionary data
64 z->state->nowrap = 1; 108 when a dictionary is loaded.
65 }
66 109
67 /* set window size */ 110 Providing output buffers larger than 32K to inflate() should provide a speed
68 if (w < 8 || w > 15) 111 advantage, since only the last 32K of output is copied to the sliding window
69 { 112 upon return from inflate(), and since all distances after the first 32K of
70 zlib_inflateEnd(z); 113 output will fall in the output data, making match copies simpler and faster.
71 return Z_STREAM_ERROR; 114 The advantage may be dependent on the size of the processor's data caches.
72 } 115 */
73 z->state->wbits = (uInt)w; 116 static void zlib_updatewindow(z_streamp strm, unsigned out)
117 {
118 struct inflate_state *state;
119 unsigned copy, dist;
74 120
75 /* create inflate_blocks state */ 121 state = (struct inflate_state *)strm->state;
76 if ((z->state->blocks =
77 zlib_inflate_blocks_new(z, z->state->nowrap ? NULL : zlib_adler32, (uInt)1 << w))
78 == NULL)
79 {
80 zlib_inflateEnd(z);
81 return Z_MEM_ERROR;
82 }
83 122
84 /* reset state */ 123 /* copy state->wsize or less output bytes into the circular window */
85 zlib_inflateReset(z); 124 copy = out - strm->avail_out;
86 return Z_OK; 125 if (copy >= state->wsize) {
126 memcpy(state->window, strm->next_out - state->wsize, state->wsize);
127 state->write = 0;
128 state->whave = state->wsize;
129 }
130 else {
131 dist = state->wsize - state->write;
132 if (dist > copy) dist = copy;
133 memcpy(state->window + state->write, strm->next_out - copy, dist);
134 copy -= dist;
135 if (copy) {
136 memcpy(state->window, strm->next_out - copy, copy);
137 state->write = copy;
138 state->whave = state->wsize;
139 }
140 else {
141 state->write += dist;
142 if (state->write == state->wsize) state->write = 0;
143 if (state->whave < state->wsize) state->whave += dist;
144 }
145 }
87 } 146 }
88 147
89 148
90 /* 149 /*
91 * At the end of a Deflate-compressed PPP packet, we expect to have seen 150 * At the end of a Deflate-compressed PPP packet, we expect to have seen
92 * a `stored' block type value but not the (zero) length bytes. 151 * a `stored' block type value but not the (zero) length bytes.
93 */ 152 */
94 static int zlib_inflate_packet_flush(inflate_blocks_statef *s) 153 /*
154 Returns true if inflate is currently at the end of a block generated by
155 Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
156 implementation to provide an additional safety check. PPP uses
157 Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
158 block. When decompressing, PPP checks that at the end of input packet,
159 inflate is waiting for these length bytes.
160 */
161 static int zlib_inflateSyncPacket(z_streamp strm)
95 { 162 {
96 if (s->mode != LENS) 163 struct inflate_state *state;
97 return Z_DATA_ERROR; 164
98 s->mode = TYPE; 165 if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR;
166 state = (struct inflate_state *)strm->state;
167
168 if (state->mode == STORED && state->bits == 0) {
169 state->mode = TYPE;
170 return Z_OK;
171 }
172 return Z_DATA_ERROR;
173 }
174
175 /* Macros for inflate(): */
176
177 /* check function to use adler32() for zlib or crc32() for gzip */
178 #define UPDATE(check, buf, len) zlib_adler32(check, buf, len)
179
180 /* Load registers with state in inflate() for speed */
181 #define LOAD() \
182 do { \
183 put = strm->next_out; \
184 left = strm->avail_out; \
185 next = strm->next_in; \
186 have = strm->avail_in; \
187 hold = state->hold; \
188 bits = state->bits; \
189 } while (0)
190
191 /* Restore state from registers in inflate() */
192 #define RESTORE() \
193 do { \
194 strm->next_out = put; \
195 strm->avail_out = left; \
196 strm->next_in = next; \
197 strm->avail_in = have; \
198 state->hold = hold; \
199 state->bits = bits; \
200 } while (0)
201
202 /* Clear the input bit accumulator */
203 #define INITBITS() \
204 do { \
205 hold = 0; \
206 bits = 0; \
207 } while (0)
208
209 /* Get a byte of input into the bit accumulator, or return from inflate()
210 if there is no input available. */
211 #define PULLBYTE() \
212 do { \
213 if (have == 0) goto inf_leave; \
214 have--; \
215 hold += (unsigned long)(*next++) << bits; \
216 bits += 8; \
217 } while (0)
218
219 /* Assure that there are at least n bits in the bit accumulator. If there is
220 not enough available input to do that, then return from inflate(). */
221 #define NEEDBITS(n) \
222 do { \
223 while (bits < (unsigned)(n)) \
224 PULLBYTE(); \
225 } while (0)
226
227 /* Return the low n bits of the bit accumulator (n < 16) */
228 #define BITS(n) \
229 ((unsigned)hold & ((1U << (n)) - 1))
230
231 /* Remove n bits from the bit accumulator */
232 #define DROPBITS(n) \
233 do { \
234 hold >>= (n); \
235 bits -= (unsigned)(n); \
236 } while (0)
237
238 /* Remove zero to seven bits as needed to go to a byte boundary */
239 #define BYTEBITS() \
240 do { \
241 hold >>= bits & 7; \
242 bits -= bits & 7; \
243 } while (0)
244
245 /* Reverse the bytes in a 32-bit value */
246 #define REVERSE(q) \
247 ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
248 (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
249
250 /*
251 inflate() uses a state machine to process as much input data and generate as
252 much output data as possible before returning. The state machine is
253 structured roughly as follows:
254
255 for (;;) switch (state) {
256 ...
257 case STATEn:
258 if (not enough input data or output space to make progress)
259 return;
260 ... make progress ...
261 state = STATEm;
262 break;
263 ...
264 }
265
266 so when inflate() is called again, the same case is attempted again, and
267 if the appropriate resources are provided, the machine proceeds to the
268 next state. The NEEDBITS() macro is usually the way the state evaluates
269 whether it can proceed or should return. NEEDBITS() does the return if
270 the requested bits are not available. The typical use of the BITS macros
271 is:
272
273 NEEDBITS(n);
274 ... do something with BITS(n) ...
275 DROPBITS(n);
276
277 where NEEDBITS(n) either returns from inflate() if there isn't enough
278 input left to load n bits into the accumulator, or it continues. BITS(n)
279 gives the low n bits in the accumulator. When done, DROPBITS(n) drops
280 the low n bits off the accumulator. INITBITS() clears the accumulator
281 and sets the number of available bits to zero. BYTEBITS() discards just
282 enough bits to put the accumulator on a byte boundary. After BYTEBITS()
283 and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
284
285 NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
286 if there is no input available. The decoding of variable length codes uses
287 PULLBYTE() directly in order to pull just enough bytes to decode the next
288 code, and no more.
289
290 Some states loop until they get enough input, making sure that enough
291 state information is maintained to continue the loop where it left off
292 if NEEDBITS() returns in the loop. For example, want, need, and keep
293 would all have to actually be part of the saved state in case NEEDBITS()
294 returns:
295
296 case STATEw:
297 while (want < need) {
298 NEEDBITS(n);
299 keep[want++] = BITS(n);
300 DROPBITS(n);
301 }
302 state = STATEx;
303 case STATEx:
304
305 As shown above, if the next state is also the next case, then the break
306 is omitted.
307
308 A state may also return if there is not enough output space available to
309 complete that state. Those states are copying stored data, writing a
310 literal byte, and copying a matching string.
311
312 When returning, a "goto inf_leave" is used to update the total counters,
313 update the check value, and determine whether any progress has been made
314 during that inflate() call in order to return the proper return code.
315 Progress is defined as a change in either strm->avail_in or strm->avail_out.
316 When there is a window, goto inf_leave will update the window with the last
317 output written. If a goto inf_leave occurs in the middle of decompression
318 and there is no window currently, goto inf_leave will create one and copy
319 output to the window for the next call of inflate().
320
321 In this implementation, the flush parameter of inflate() only affects the
322 return code (per zlib.h). inflate() always writes as much as possible to
323 strm->next_out, given the space available and the provided input--the effect
324 documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
325 the allocation of and copying into a sliding window until necessary, which
326 provides the effect documented in zlib.h for Z_FINISH when the entire input
327 stream available. So the only thing the flush parameter actually does is:
328 when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
329 will return Z_BUF_ERROR if it has not reached the end of the stream.
330 */
331
332 int zlib_inflate(z_streamp strm, int flush)
333 {
334 struct inflate_state *state;
335 unsigned char *next; /* next input */
336 unsigned char *put; /* next output */
337 unsigned have, left; /* available input and output */
338 unsigned long hold; /* bit buffer */
339 unsigned bits; /* bits in bit buffer */
340 unsigned in, out; /* save starting available input and output */
341 unsigned copy; /* number of stored or match bytes to copy */
342 unsigned char *from; /* where to copy match bytes from */
343 code this; /* current decoding table entry */
344 code last; /* parent table entry */
345 unsigned len; /* length to copy for repeats, bits to drop */
346 int ret; /* return code */
347 static const unsigned short order[19] = /* permutation of code lengths */
348 {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
349
350 if (strm == NULL || strm->state == NULL || strm->next_out == NULL ||
351 (strm->next_in == NULL && strm->avail_in != 0))
352 return Z_STREAM_ERROR;
353
354 state = (struct inflate_state *)strm->state;
355
356 if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
357 LOAD();
358 in = have;
359 out = left;
360 ret = Z_OK;
361 for (;;)
362 switch (state->mode) {
363 case HEAD:
364 if (state->wrap == 0) {
365 state->mode = TYPEDO;
366 break;
367 }
368 NEEDBITS(16);
369 if (
370 ((BITS(8) << 8) + (hold >> 8)) % 31) {
371 strm->msg = (char *)"incorrect header check";
372 state->mode = BAD;
373 break;
374 }
375 if (BITS(4) != Z_DEFLATED) {
376 strm->msg = (char *)"unknown compression method";
377 state->mode = BAD;
378 break;
379 }
380 DROPBITS(4);
381 len = BITS(4) + 8;
382 if (len > state->wbits) {
383 strm->msg = (char *)"invalid window size";
384 state->mode = BAD;
385 break;
386 }
387 state->dmax = 1U << len;
388 strm->adler = state->check = zlib_adler32(0L, NULL, 0);
389 state->mode = hold & 0x200 ? DICTID : TYPE;
390 INITBITS();
391 break;
392 case DICTID:
393 NEEDBITS(32);
394 strm->adler = state->check = REVERSE(hold);
395 INITBITS();
396 state->mode = DICT;
397 case DICT:
398 if (state->havedict == 0) {
399 RESTORE();
400 return Z_NEED_DICT;
401 }
402 strm->adler = state->check = zlib_adler32(0L, NULL, 0);
403 state->mode = TYPE;
404 case TYPE:
405 if (flush == Z_BLOCK) goto inf_leave;
406 case TYPEDO:
407 if (state->last) {
408 BYTEBITS();
409 state->mode = CHECK;
410 break;
411 }
412 NEEDBITS(3);
413 state->last = BITS(1);
414 DROPBITS(1);
415 switch (BITS(2)) {
416 case 0: /* stored block */
417 state->mode = STORED;
418 break;
419 case 1: /* fixed block */
420 zlib_fixedtables(state);
421 state->mode = LEN; /* decode codes */
422 break;
423 case 2: /* dynamic block */
424 state->mode = TABLE;
425 break;
426 case 3:
427 strm->msg = (char *)"invalid block type";
428 state->mode = BAD;
429 }
430 DROPBITS(2);
431 break;
432 case STORED:
433 BYTEBITS(); /* go to byte boundary */
434 NEEDBITS(32);
435 if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
436 strm->msg = (char *)"invalid stored block lengths";
437 state->mode = BAD;
438 break;
439 }
440 state->length = (unsigned)hold & 0xffff;
441 INITBITS();
442 state->mode = COPY;
443 case COPY:
444 copy = state->length;
445 if (copy) {
446 if (copy > have) copy = have;
447 if (copy > left) copy = left;
448 if (copy == 0) goto inf_leave;
449 memcpy(put, next, copy);
450 have -= copy;
451 next += copy;
452 left -= copy;
453 put += copy;
454 state->length -= copy;
455 break;
456 }
457 state->mode = TYPE;
458 break;
459 case TABLE:
460 NEEDBITS(14);
461 state->nlen = BITS(5) + 257;
462 DROPBITS(5);
463 state->ndist = BITS(5) + 1;
464 DROPBITS(5);
465 state->ncode = BITS(4) + 4;
466 DROPBITS(4);
467 #ifndef PKZIP_BUG_WORKAROUND
468 if (state->nlen > 286 || state->ndist > 30) {
469 strm->msg = (char *)"too many length or distance symbols";
470 state->mode = BAD;
471 break;
472 }
473 #endif
474 state->have = 0;
475 state->mode = LENLENS;
476 case LENLENS:
477 while (state->have < state->ncode) {
478 NEEDBITS(3);
479 state->lens[order[state->have++]] = (unsigned short)BITS(3);
480 DROPBITS(3);
481 }
482 while (state->have < 19)
483 state->lens[order[state->have++]] = 0;
484 state->next = state->codes;
485 state->lencode = (code const *)(state->next);
486 state->lenbits = 7;
487 ret = zlib_inflate_table(CODES, state->lens, 19, &(state->next),
488 &(state->lenbits), state->work);
489 if (ret) {
490 strm->msg = (char *)"invalid code lengths set";
491 state->mode = BAD;
492 break;
493 }
494 state->have = 0;
495 state->mode = CODELENS;
496 case CODELENS:
497 while (state->have < state->nlen + state->ndist) {
498 for (;;) {
499 this = state->lencode[BITS(state->lenbits)];
500 if ((unsigned)(this.bits) <= bits) break;
501 PULLBYTE();
502 }
503 if (this.val < 16) {
504 NEEDBITS(this.bits);
505 DROPBITS(this.bits);
506 state->lens[state->have++] = this.val;
507 }
508 else {
509 if (this.val == 16) {
510 NEEDBITS(this.bits + 2);
511 DROPBITS(this.bits);
512 if (state->have == 0) {
513 strm->msg = (char *)"invalid bit length repeat";
514 state->mode = BAD;
515 break;
516 }
517 len = state->lens[state->have - 1];
518 copy = 3 + BITS(2);
519 DROPBITS(2);
520 }
521 else if (this.val == 17) {
522 NEEDBITS(this.bits + 3);
523 DROPBITS(this.bits);
524 len = 0;
525 copy = 3 + BITS(3);
526 DROPBITS(3);
527 }
528 else {
529 NEEDBITS(this.bits + 7);
530 DROPBITS(this.bits);
531 len = 0;
532 copy = 11 + BITS(7);
533 DROPBITS(7);
534 }
535 if (state->have + copy > state->nlen + state->ndist) {
536 strm->msg = (char *)"invalid bit length repeat";
537 state->mode = BAD;
538 break;
539 }
540 while (copy--)
541 state->lens[state->have++] = (unsigned short)len;
542 }
543 }
544
545 /* handle error breaks in while */
546 if (state->mode == BAD) break;
547
548 /* build code tables */
549 state->next = state->codes;
550 state->lencode = (code const *)(state->next);
551 state->lenbits = 9;
552 ret = zlib_inflate_table(LENS, state->lens, state->nlen, &(state->next),
553 &(state->lenbits), state->work);
554 if (ret) {
555 strm->msg = (char *)"invalid literal/lengths set";
556 state->mode = BAD;
557 break;
558 }
559 state->distcode = (code const *)(state->next);
560 state->distbits = 6;
561 ret = zlib_inflate_table(DISTS, state->lens + state->nlen, state->ndist,
562 &(state->next), &(state->distbits), state->work);
563 if (ret) {
564 strm->msg = (char *)"invalid distances set";
565 state->mode = BAD;
566 break;
567 }
568 state->mode = LEN;
569 case LEN:
570 if (have >= 6 && left >= 258) {
571 RESTORE();
572 inflate_fast(strm, out);
573 LOAD();
574 break;
575 }
576 for (;;) {
577 this = state->lencode[BITS(state->lenbits)];
578 if ((unsigned)(this.bits) <= bits) break;
579 PULLBYTE();
580 }
581 if (this.op && (this.op & 0xf0) == 0) {
582 last = this;
583 for (;;) {
584 this = state->lencode[last.val +
585 (BITS(last.bits + last.op) >> last.bits)];
586 if ((unsigned)(last.bits + this.bits) <= bits) break;
587 PULLBYTE();
588 }
589 DROPBITS(last.bits);
590 }
591 DROPBITS(this.bits);
592 state->length = (unsigned)this.val;
593 if ((int)(this.op) == 0) {
594 state->mode = LIT;
595 break;
596 }
597 if (this.op & 32) {
598 state->mode = TYPE;
599 break;
600 }
601 if (this.op & 64) {
602 strm->msg = (char *)"invalid literal/length code";
603 state->mode = BAD;
604 break;
605 }
606 state->extra = (unsigned)(this.op) & 15;
607 state->mode = LENEXT;
608 case LENEXT:
609 if (state->extra) {
610 NEEDBITS(state->extra);
611 state->length += BITS(state->extra);
612 DROPBITS(state->extra);
613 }
614 state->mode = DIST;
615 case DIST:
616 for (;;) {
617 this = state->distcode[BITS(state->distbits)];
618 if ((unsigned)(this.bits) <= bits) break;
619 PULLBYTE();
620 }
621 if ((this.op & 0xf0) == 0) {
622 last = this;
623 for (;;) {
624 this = state->distcode[last.val +
625 (BITS(last.bits + last.op) >> last.bits)];
626 if ((unsigned)(last.bits + this.bits) <= bits) break;
627 PULLBYTE();
628 }
629 DROPBITS(last.bits);
630 }
631 DROPBITS(this.bits);
632 if (this.op & 64) {
633 strm->msg = (char *)"invalid distance code";
634 state->mode = BAD;
635 break;
636 }
637 state->offset = (unsigned)this.val;
638 state->extra = (unsigned)(this.op) & 15;
639 state->mode = DISTEXT;
640 case DISTEXT:
641 if (state->extra) {
642 NEEDBITS(state->extra);
643 state->offset += BITS(state->extra);
644 DROPBITS(state->extra);
645 }
646 #ifdef INFLATE_STRICT
647 if (state->offset > state->dmax) {
648 strm->msg = (char *)"invalid distance too far back";
649 state->mode = BAD;
650 break;
651 }
652 #endif
653 if (state->offset > state->whave + out - left) {
654 strm->msg = (char *)"invalid distance too far back";
655 state->mode = BAD;
656 break;
657 }
658 state->mode = MATCH;
659 case MATCH:
660 if (left == 0) goto inf_leave;
661 copy = out - left;
662 if (state->offset > copy) { /* copy from window */
663 copy = state->offset - copy;
664 if (copy > state->write) {
665 copy -= state->write;
666 from = state->window + (state->wsize - copy);
667 }
668 else
669 from = state->window + (state->write - copy);
670 if (copy > state->length) copy = state->length;
671 }
672 else { /* copy from output */
673 from = put - state->offset;
674 copy = state->length;
675 }
676 if (copy > left) copy = left;
677 left -= copy;
678 state->length -= copy;
679 do {
680 *put++ = *from++;
681 } while (--copy);
682 if (state->length == 0) state->mode = LEN;
683 break;
684 case LIT:
685 if (left == 0) goto inf_leave;
686 *put++ = (unsigned char)(state->length);
687 left--;
688 state->mode = LEN;
689 break;
690 case CHECK:
691 if (state->wrap) {
692 NEEDBITS(32);
693 out -= left;
694 strm->total_out += out;
695 state->total += out;
696 if (out)
697 strm->adler = state->check =
698 UPDATE(state->check, put - out, out);
699 out = left;
700 if ((
701 REVERSE(hold)) != state->check) {
702 strm->msg = (char *)"incorrect data check";
703 state->mode = BAD;
704 break;
705 }
706 INITBITS();
707 }
708 state->mode = DONE;
709 case DONE:
710 ret = Z_STREAM_END;
711 goto inf_leave;
712 case BAD:
713 ret = Z_DATA_ERROR;
714 goto inf_leave;
715 case MEM:
716 return Z_MEM_ERROR;
717 case SYNC:
718 default:
719 return Z_STREAM_ERROR;
720 }
721
722 /*
723 Return from inflate(), updating the total counts and the check value.
724 If there was no progress during the inflate() call, return a buffer
725 error. Call zlib_updatewindow() to create and/or update the window state.
726 */
727 inf_leave:
728 RESTORE();
729 if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
730 zlib_updatewindow(strm, out);
731
732 in -= strm->avail_in;
733 out -= strm->avail_out;
734 strm->total_in += in;
735 strm->total_out += out;
736 state->total += out;
737 if (state->wrap && out)
738 strm->adler = state->check =
739 UPDATE(state->check, strm->next_out - out, out);
740
741 strm->data_type = state->bits + (state->last ? 64 : 0) +
742 (state->mode == TYPE ? 128 : 0);
743 if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
744 ret = Z_BUF_ERROR;
745
746 if (flush == Z_PACKET_FLUSH && ret == Z_OK &&
747 (strm->avail_out != 0 || strm->avail_in == 0))
748 return zlib_inflateSyncPacket(strm);
749 return ret;
750 }
751
752 int zlib_inflateEnd(z_streamp strm)
753 {
754 if (strm == NULL || strm->state == NULL)
755 return Z_STREAM_ERROR;
99 return Z_OK; 756 return Z_OK;
100 } 757 }
101 758
759 #if 0
760 int zlib_inflateSetDictionary(z_streamp strm, const Byte *dictionary,
761 uInt dictLength)
762 {
763 struct inflate_state *state;
764 unsigned long id;
102 765
103 int zlib_inflateInit_( 766 /* check state */
104 z_streamp z, 767 if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR;
105 const char *version, 768 state = (struct inflate_state *)strm->state;
106 int stream_size 769 if (state->wrap != 0 && state->mode != DICT)
107 ) 770 return Z_STREAM_ERROR;
771
772 /* check for correct dictionary id */
773 if (state->mode == DICT) {
774 id = zlib_adler32(0L, NULL, 0);
775 id = zlib_adler32(id, dictionary, dictLength);
776 if (id != state->check)
777 return Z_DATA_ERROR;
778 }
779
780 /* copy dictionary to window */
781 zlib_updatewindow(strm, strm->avail_out);
782
783 if (dictLength > state->wsize) {
784 memcpy(state->window, dictionary + dictLength - state->wsize,
785 state->wsize);
786 state->whave = state->wsize;
787 }
788 else {
789 memcpy(state->window + state->wsize - dictLength, dictionary,
790 dictLength);
791 state->whave = dictLength;
792 }
793 state->havedict = 1;
794 return Z_OK;
795 }
796 #endif
797
798 #if 0
799 /*
800 Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
801 or when out of input. When called, *have is the number of pattern bytes
802 found in order so far, in 0..3. On return *have is updated to the new
803 state. If on return *have equals four, then the pattern was found and the
804 return value is how many bytes were read including the last byte of the
805 pattern. If *have is less than four, then the pattern has not been found
806 yet and the return value is len. In the latter case, zlib_syncsearch() can be
807 called again with more data and the *have state. *have is initialized to
808 zero for the first call.
809 */
810 static unsigned zlib_syncsearch(unsigned *have, unsigned char *buf,
811 unsigned len)
108 { 812 {
109 return zlib_inflateInit2_(z, DEF_WBITS, version, stream_size); 813 unsigned got;
814 unsigned next;
815
816 got = *have;
817 next = 0;
818 while (next < len && got < 4) {
819 if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
820 got++;
821 else if (buf[next])
822 got = 0;
823 else
824 got = 4 - got;
825 next++;
826 }
827 *have = got;
828 return next;
110 } 829 }
830 #endif
111 831
112 #undef NEEDBYTE 832 #if 0
113 #undef NEXTBYTE 833 int zlib_inflateSync(z_streamp strm)
114 #define NEEDBYTE {if(z->avail_in==0)goto empty;r=trv;} 834 {
115 #define NEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++) 835 unsigned len; /* number of bytes to look at or looked at */
836 unsigned long in, out; /* temporary to save total_in and total_out */
837 unsigned char buf[4]; /* to restore bit buffer to byte string */
838 struct inflate_state *state;
116 839
117 int zlib_inflate( 840 /* check parameters */
118 z_streamp z, 841 if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR;
119 int f 842 state = (struct inflate_state *)strm->state;
120 ) 843 if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
844
845 /* if first time, start search in bit buffer */
846 if (state->mode != SYNC) {
847 state->mode = SYNC;
848 state->hold <<= state->bits & 7;
849 state->bits -= state->bits & 7;
850 len = 0;
851 while (state->bits >= 8) {
852 buf[len++] = (unsigned char)(state->hold);
853 state->hold >>= 8;
854 state->bits -= 8;
855 }
856 state->have = 0;
857 zlib_syncsearch(&(state->have), buf, len);
858 }
859
860 /* search available input */
861 len = zlib_syncsearch(&(state->have), strm->next_in, strm->avail_in);
862 strm->avail_in -= len;
863 strm->next_in += len;
864 strm->total_in += len;
865
866 /* return no joy or set up to restart inflate() on a new block */
867 if (state->have != 4) return Z_DATA_ERROR;
868 in = strm->total_in; out = strm->total_out;
869 zlib_inflateReset(strm);
870 strm->total_in = in; strm->total_out = out;
871 state->mode = TYPE;
872 return Z_OK;
873 }
874 #endif
875
876 /*
877 * This subroutine adds the data at next_in/avail_in to the output history
878 * without performing any output. The output buffer must be "caught up";
879 * i.e. no pending output but this should always be the case. The state must
880 * be waiting on the start of a block (i.e. mode == TYPE or HEAD). On exit,
881 * the output will also be caught up, and the checksum will have been updated
882 * if need be.
883 */
884 int zlib_inflateIncomp(z_stream *z)
121 { 885 {
122 int r, trv; 886 struct inflate_state *state = (struct inflate_state *)z->state;
123 uInt b; 887 Byte *saved_no = z->next_out;
888 uInt saved_ao = z->avail_out;
124 889
125 if (z == NULL || z->state == NULL || z->next_in == NULL) 890 if (state->mode != TYPE && state->mode != HEAD)
126 return Z_STREAM_ERROR; 891 return Z_DATA_ERROR;
127 trv = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
lib/zlib_inflate/inflate.h
File was created 1 /* inflate.h -- internal inflate state definition
2 * Copyright (C) 1995-2004 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6 /* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h.
9 */
10
11 /* Possible inflate modes between inflate() calls */
12 typedef enum {
13 HEAD, /* i: waiting for magic header */
14 FLAGS, /* i: waiting for method and flags (gzip) */
15 TIME, /* i: waiting for modification time (gzip) */
16 OS, /* i: waiting for extra flags and operating system (gzip) */
17 EXLEN, /* i: waiting for extra length (gzip) */
18 EXTRA, /* i: waiting for extra bytes (gzip) */
19 NAME, /* i: waiting for end of file name (gzip) */
20 COMMENT, /* i: waiting for end of comment (gzip) */
21 HCRC, /* i: waiting for header crc (gzip) */
22 DICTID, /* i: waiting for dictionary check value */
23 DICT, /* waiting for inflateSetDictionary() call */
24 TYPE, /* i: waiting for type bits, including last-flag bit */
25 TYPEDO, /* i: same, but skip check to exit inflate on new block */
26 STORED, /* i: waiting for stored size (length and complement) */
27 COPY, /* i/o: waiting for input or output to copy stored block */
28 TABLE, /* i: waiting for dynamic block table lengths */
29 LENLENS, /* i: waiting for code length code lengths */
30 CODELENS, /* i: waiting for length/lit and distance code lengths */
31 LEN, /* i: waiting for length/lit code */
32 LENEXT, /* i: waiting for length extra bits */
33 DIST, /* i: waiting for distance code */
34 DISTEXT, /* i: waiting for distance extra bits */
35 MATCH, /* o: waiting for output space to copy string */
36 LIT, /* o: waiting for output space to write literal */
37 CHECK, /* i: waiting for 32-bit check value */
38 LENGTH, /* i: waiting for 32-bit length (gzip) */
39 DONE, /* finished check, done -- remain here until reset */
40 BAD, /* got a data error -- remain here until reset */
41 MEM, /* got an inflate() memory error -- remain here until reset */
42 SYNC /* looking for synchronization bytes to restart inflate() */
43 } inflate_mode;
44
45 /*
46 State transitions between above modes -
47
48 (most modes can go to the BAD or MEM mode -- not shown for clarity)
49
50 Process header:
51 HEAD -> (gzip) or (zlib)
52 (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
53 NAME -> COMMENT -> HCRC -> TYPE
54 (zlib) -> DICTID or TYPE
55 DICTID -> DICT -> TYPE
56 Read deflate blocks:
57 TYPE -> STORED or TABLE or LEN or CHECK
58 STORED -> COPY -> TYPE
59 TABLE -> LENLENS -> CODELENS -> LEN
60 Read deflate codes:
61 LEN -> LENEXT or LIT or TYPE
62 LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
63 LIT -> LEN
64 Process trailer:
65 CHECK -> LENGTH -> DONE
66 */
67
68 /* state maintained between inflate() calls. Approximately 7K bytes. */
69 struct inflate_state {
70 inflate_mode mode; /* current inflate mode */
71 int last; /* true if processing last block */
72 int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
73 int havedict; /* true if dictionary provided */
74 int flags; /* gzip header method and flags (0 if zlib) */
75 unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
76 unsigned long check; /* protected copy of check value */
77 unsigned long total; /* protected copy of output count */
78 /* gz_headerp head; */ /* where to save gzip header information */
79 /* sliding window */
80 unsigned wbits; /* log base 2 of requested window size */
81 unsigned wsize; /* window size or zero if not using window */
82 unsigned whave; /* valid bytes in the window */
83 unsigned write; /* window write index */
84 unsigned char *window; /* allocated sliding window, if needed */
85 /* bit accumulator */
86 unsigned long hold; /* input bit accumulator */
87 unsigned bits; /* number of bits in "in" */
88 /* for string and stored block copying */
89 unsigned length; /* literal or length of data to copy */
90 unsigned offset; /* distance back to copy string from */
91 /* for table and code decoding */
92 unsigned extra; /* extra bits needed */
93 /* fixed and dynamic code tables */
94 code const *lencode; /* starting table for length/literal codes */
95 code const *distcode; /* starting table for distance codes */
96 unsigned lenbits; /* index bits for lencode */
97 unsigned distbits; /* index bits for distcode */
98 /* dynamic table building */
99 unsigned ncode; /* number of code length code lengths */
100 unsigned nlen; /* number of length code lengths */
101 unsigned ndist; /* number of distance code lengths */
102 unsigned have; /* number of code lengths in lens[] */
103 code *next; /* next available space in codes[] */
104 unsigned short lens[320]; /* temporary storage for code lengths */
105 unsigned short work[288]; /* work area for code table building */
106 code codes[ENOUGH]; /* space for code tables */
107 };
108
lib/zlib_inflate/inflate_syms.c
1 /* 1 /*
2 * linux/lib/zlib_inflate/inflate_syms.c 2 * linux/lib/zlib_inflate/inflate_syms.c
3 * 3 *
4 * Exported symbols for the inflate functionality. 4 * Exported symbols for the inflate functionality.
5 * 5 *
6 */ 6 */
7 7
8 #include <linux/module.h> 8 #include <linux/module.h>
9 #include <linux/init.h> 9 #include <linux/init.h>
10 10
11 #include <linux/zlib.h> 11 #include <linux/zlib.h>
12 12
13 EXPORT_SYMBOL(zlib_inflate_workspacesize); 13 EXPORT_SYMBOL(zlib_inflate_workspacesize);
14 EXPORT_SYMBOL(zlib_inflate); 14 EXPORT_SYMBOL(zlib_inflate);
15 EXPORT_SYMBOL(zlib_inflateInit_); 15 EXPORT_SYMBOL(zlib_inflateInit2);
16 EXPORT_SYMBOL(zlib_inflateInit2_);
17 EXPORT_SYMBOL(zlib_inflateEnd); 16 EXPORT_SYMBOL(zlib_inflateEnd);
18 EXPORT_SYMBOL(zlib_inflateReset); 17 EXPORT_SYMBOL(zlib_inflateReset);
19 EXPORT_SYMBOL(zlib_inflateIncomp); 18 EXPORT_SYMBOL(zlib_inflateIncomp);
20 MODULE_LICENSE("GPL"); 19 MODULE_LICENSE("GPL");
21 20
lib/zlib_inflate/inflate_sync.c
1 /* inflate.c -- zlib interface to inflate modules File was deleted
2 * Copyright (C) 1995-1998 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6 #include <linux/zutil.h>
7 #include "infblock.h"
8 #include "infutil.h"
9
10 #if 0
11 int zlib_inflateSync(
12 z_streamp z
13 )
14 {
15 uInt n; /* number of bytes to look at */
16 Byte *p; /* pointer to bytes */
17 uInt m; /* number of marker bytes found in a row */
18 uLong r, w; /* temporaries to save total_in and total_out */
19
20 /* set up */
21 if (z == NULL || z->state == NULL)
22 return Z_STREAM_ERROR;
23 if (z->state->mode != I_BAD)
24 {
25 z->state->mode = I_BAD;
26 z->state->sub.marker = 0;
27 }
28 if ((n = z->avail_in) == 0)
29 return Z_BUF_ERROR;
30 p = z->next_in;
31 m = z->state->sub.marker;
32
33 /* search */
34 while (n && m < 4)
35 {
36 static const Byte mark[4] = {0, 0, 0xff, 0xff};
37 if (*p == mark[m])
38 m++;
39 else if (*p)
40 m = 0;
41 else
42 m = 4 - m;
43 p++, n--;
44 }
45
46 /* restore */
47 z->total_in += p - z->next_in;
48 z->next_in = p;
49 z->avail_in = n;
50 z->state->sub.marker = m;
51
52 /* return no joy or set up to restart on a new block */
53 if (m != 4)
54 return Z_DATA_ERROR;
55 r = z->total_in; w = z->total_out;
56 zlib_inflateReset(z);
57 z->total_in = r; z->total_out = w;
58 z->state->mode = BLOCKS;
59 return Z_OK;
60 }
61 #endif /* 0 */
62
63
64 /* Returns true if inflate is currently at the end of a block generated
65 * by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
66 * implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH
67 * but removes the length bytes of the resulting empty stored block. When
68 * decompressing, PPP checks that at the end of input packet, inflate is
69 * waiting for these length bytes.
70 */
71 #if 0
72 int zlib_inflateSyncPoint(
73 z_streamp z
74 )
75 {
76 if (z == NULL || z->state == NULL || z->state->blocks == NULL)
77 return Z_STREAM_ERROR;
78 return zlib_inflate_blocks_sync_point(z->state->blocks);
79 }
80 #endif /* 0 */
81
82 /*
83 * This subroutine adds the data at next_in/avail_in to the output history
84 * without performing any output. The output buffer must be "caught up";
85 * i.e. no pending output (hence s->read equals s->write), and the state must
86 * be BLOCKS (i.e. we should be willing to see the start of a series of
87 * BLOCKS). On exit, the output will also be caught up, and the checksum
88 * will have been updated if need be.
89 */
90 static int zlib_inflate_addhistory(inflate_blocks_statef *s,
91 z_stream *z)
92 {
93 uLong b; /* bit buffer */ /* NOT USED HERE */
94 uInt k; /* bits in bit buffer */ /* NOT USED HERE */
95 uInt t; /* temporary storage */
96 Byte *p; /* input data pointer */
97 uInt n; /* bytes available there */
98 Byte *q; /* output window write pointer */
99 uInt m; /* bytes to end of window or read pointer */
100
101 if (s->read != s->write)
102 return Z_STREAM_ERROR;
103 if (s->mode != TYPE)
104 return Z_DATA_ERROR;
105
106 /* we're ready to rock */
107 LOAD
108 /* while there is input ready, copy to output buffer, moving
109 * pointers as needed.
110 */
111 while (n) {
112 t = n; /* how many to do */
113 /* is there room until end of buffer? */
114 if (t > m) t = m;
115 /* update check information */
116 if (s->checkfn != NULL)
117 s->check = (*s->checkfn)(s->check, q, t);
118 memcpy(q, p, t);
119 q += t;
120 p += t;
121 n -= t;
122 z->total_out += t;
123 s->read = q; /* drag read pointer forward */
124 /* WWRAP */ /* expand WWRAP macro by hand to handle s->read */
125 if (q == s->end) {
126 s->read = q = s->window;
127 m = WAVAIL;
128 }
129 }
130 UPDATE
131 return Z_OK;
132 }
133
134
135 /*
136 * This subroutine adds the data at next_in/avail_in to the output history
137 * without performing any output. The output buffer must be "caught up";
138 * i.e. no pending output (hence s->read equals s->write), and the state must
139 * be BLOCKS (i.e. we should be willing to see the start of a series of
140 * BLOCKS). On exit, the output will also be caught up, and the checksum
141 * will have been updated if need be.
142 */
143
144 int zlib_inflateIncomp(
145 z_stream *z
146
147 )
148 {
149 if (z->state->mode != BLOCKS)
150 return Z_DATA_ERROR;
151 return zlib_inflate_addhistory(z->state->blocks, z);
152 }
153 1 /* inflate.c -- zlib interface to inflate modules
lib/zlib_inflate/inftrees.c
1 /* inftrees.c -- generate Huffman trees for efficient decoding 1 /* inftrees.c -- generate Huffman trees for efficient decoding
2 * Copyright (C) 1995-1998 Mark Adler 2 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6 #include <linux/zutil.h> 6 #include <linux/zutil.h>
7 #include "inftrees.h" 7 #include "inftrees.h"
8 #include "infutil.h"
9 8
10 static const char inflate_copyright[] __attribute_used__ = 9 #define MAXBITS 15
11 " inflate 1.1.3 Copyright 1995-1998 Mark Adler "; 10
11 const char inflate_copyright[] =
12 " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
12 /* 13 /*
13 If you use the zlib library in a product, an acknowledgment is welcome 14 If you use the zlib library in a product, an acknowledgment is welcome
14 in the documentation of your product. If for some reason you cannot 15 in the documentation of your product. If for some reason you cannot
15 include such an acknowledgment, I would appreciate that you keep this 16 include such an acknowledgment, I would appreciate that you keep this
16 copyright string in the executable of your product. 17 copyright string in the executable of your product.
17 */ 18 */
18 struct internal_state;
19 19
20 /* simplify the use of the inflate_huft type with some defines */ 20 /*
21 #define exop word.what.Exop 21 Build a set of tables to decode the provided canonical Huffman code.
22 #define bits word.what.Bits 22 The code lengths are lens[0..codes-1]. The result starts at *table,
23 23 whose indices are 0..2^bits-1. work is a writable array of at least
24 24 lens shorts, which is used as a work area. type is the type of code
25 static int huft_build ( 25 to be generated, CODES, LENS, or DISTS. On return, zero is success,
26 uInt *, /* code lengths in bits */ 26 -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
27 uInt, /* number of codes */ 27 on return points to the next available entry's address. bits is the
28 uInt, /* number of "simple" codes */ 28 requested root table index bits, and on return it is the actual root
29 const uInt *, /* list of base values for non-simple codes */ 29 table index bits. It will differ if the request is greater than the
30 const uInt *, /* list of extra bits for non-simple codes */ 30 longest code or if it is less than the shortest code.
31 inflate_huft **, /* result: starting table */ 31 */
32 uInt *, /* maximum lookup bits (returns actual) */ 32 int zlib_inflate_table(type, lens, codes, table, bits, work)
33 inflate_huft *, /* space for trees */ 33 codetype type;
34 uInt *, /* hufts used in space */ 34 unsigned short *lens;
35 uInt * ); /* space for values */ 35 unsigned codes;
36 36 code **table;
37 /* Tables for deflate from PKZIP's appnote.txt. */ 37 unsigned *bits;
38 static const uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */ 38 unsigned short *work;
39 {
40 unsigned len; /* a code's length in bits */
41 unsigned sym; /* index of code symbols */
42 unsigned min, max; /* minimum and maximum code lengths */
43 unsigned root; /* number of index bits for root table */
44 unsigned curr; /* number of index bits for current table */
45 unsigned drop; /* code bits to drop for sub-table */
46 int left; /* number of prefix codes available */
47 unsigned used; /* code entries in table used */
48 unsigned huff; /* Huffman code */
49 unsigned incr; /* for incrementing code, index */
50 unsigned fill; /* index for replicating entries */
51 unsigned low; /* low bits for current root entry */
52 unsigned mask; /* mask for low root bits */
53 code this; /* table entry for duplication */
54 code *next; /* next available space in table */
55 const unsigned short *base; /* base value table to use */
56 const unsigned short *extra; /* extra bits table to use */
57 int end; /* use base and extra for symbol > end */
58 unsigned short count[MAXBITS+1]; /* number of codes of each length */
59 unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
60 static const unsigned short lbase[31] = { /* Length codes 257..285 base */
39 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 61 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
40 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; 62 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
41 /* see note #13 above about 258 */ 63 static const unsigned short lext[31] = { /* Length codes 257..285 extra */
42 static const uInt cplext[31] = { /* Extra bits for literal codes 257..285 */ 64 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
43 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 65 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
44 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; /* 112==invalid */ 66 static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
45 static const uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */
46 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 67 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
47 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 68 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
48 8193, 12289, 16385, 24577}; 69 8193, 12289, 16385, 24577, 0, 0};
49 static const uInt cpdext[30] = { /* Extra bits for distance codes */ 70 static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
50 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 71 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
51 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 72 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
52 12, 12, 13, 13}; 73 28, 28, 29, 29, 64, 64};
53 74
54 /* 75 /*
55 Huffman code decoding is performed using a multi-level table lookup. 76 Process a set of code lengths to create a canonical Huffman code. The
56 The fastest way to decode is to simply build a lookup table whose 77 code lengths are lens[0..codes-1]. Each length corresponds to the
57 size is determined by the longest code. However, the time it takes 78 symbols 0..codes-1. The Huffman code is generated by first sorting the
58 to build this table can also be a factor if the data being decoded 79 symbols by length from short to long, and retaining the symbol order
59 is not very long. The most common codes are necessarily the 80 for codes with equal lengths. Then the code starts with all zero bits
60 shortest codes, so those codes dominate the decoding time, and hence 81 for the first code of the shortest length, and the codes are integer
61 the speed. The idea is you can have a shorter table that decodes the 82 increments for the same length, and zeros are appended as the length
62 shorter, more probable codes, and then point to subsidiary tables for 83 increases. For the deflate format, these bits are stored backwards
63 the longer codes. The time it costs to decode the longer codes is 84 from their more natural integer increment ordering, and so when the
64 then traded against the time it takes to make longer tables. 85 decoding tables are built in the large loop below, the integer codes
86 are incremented backwards.
65 87
66 This results of this trade are in the variables lbits and dbits 88 This routine assumes, but does not check, that all of the entries in
67 below. lbits is the number of bits the first level table for literal/ 89 lens[] are in the range 0..MAXBITS. The caller must assure this.
68 length codes can decode in one step, and dbits is the same thing for 90 1..MAXBITS is interpreted as that code length. zero means that that
69 the distance codes. Subsequent tables are also less than or equal to 91 symbol does not occur in this code.
70 those sizes. These values may be adjusted either when all of the
71 codes are shorter than that, in which case the longest code length in
72 bits is used, or when the shortest code is *longer* than the requested
73 table size, in which case the length of the shortest code in bits is
74 used.
75 92
76 There are two different values for the two tables, since they code a 93 The codes are sorted by computing a count of codes for each length,
77 different number of possibilities each. The literal/length table 94 creating from that a table of starting indices for each length in the
78 codes 286 possible values, or in a flat code, a little over eight 95 sorted table, and then entering the symbols in order in the sorted
79 bits. The distance table codes 30 possible values, or a little less 96 table. The sorted table is work[], with that space being provided by
80 than five bits, flat. The optimum values for speed end up being 97 the caller.
81 about one bit more than those, so lbits is 8+1 and dbits is 5+1.
82 The optimum values may differ though from machine to machine, and
83 possibly even between compilers. Your mileage may vary.
84 */
85 98
99 The length counts are used for other purposes as well, i.e. finding
100 the minimum and maximum length codes, determining if there are any
101 codes at all, checking for a valid set of lengths, and looking ahead
102 at length counts to determine sub-table sizes when building the
103 decoding tables.
104 */
86 105
87 /* If BMAX needs to be larger than 16, then h and x[] should be uLong. */ 106 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
88 #define BMAX 15 /* maximum bit length of any code */ 107 for (len = 0; len <= MAXBITS; len++)
108 count[len] = 0;
109 for (sym = 0; sym < codes; sym++)
110 count[lens[sym]]++;
89 111
90 static int huft_build( 112 /* bound code lengths, force root to be within code lengths */
91 uInt *b, /* code lengths in bits (all assumed <= BMAX) */ 113 root = *bits;
92 uInt n, /* number of codes (assumed <= 288) */ 114 for (max = MAXBITS; max >= 1; max--)
93 uInt s, /* number of simple-valued codes (0..s-1) */ 115 if (count[max] != 0) break;
94 const uInt *d, /* list of base values for non-simple codes */ 116 if (root > max) root = max;
95 const uInt *e, /* list of extra bits for non-simple codes */ 117 if (max == 0) { /* no symbols to code at all */
96 inflate_huft **t, /* result: starting table */ 118 this.op = (unsigned char)64; /* invalid code marker */
97 uInt *m, /* maximum lookup bits, returns actual */ 119 this.bits = (unsigned char)1;
98 inflate_huft *hp, /* space for trees */ 120 this.val = (unsigned short)0;
99 uInt *hn, /* hufts used in space */ 121 *(*table)++ = this; /* make a table to force an error */
100 uInt *v /* working area: values in order of bit length */ 122 *(*table)++ = this;
101 ) 123 *bits = 1;
102 /* Given a list of code lengths and a maximum table size, make a set of 124 return 0; /* no symbols, but wait for decoding to report error */
103 tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR 125 }
104 if the given code set is incomplete (the tables are still built in this 126 for (min = 1; min <= MAXBITS; min++)
105 case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of 127 if (count[min] != 0) break;
106 lengths), or Z_MEM_ERROR if not enough memory. */ 128 if (root < min) root = min;
107 {
108 129
109 uInt a; /* counter for codes of length k */ 130 /* check for an over-subscribed or incomplete set of lengths */
110 uInt c[BMAX+1]; /* bit length count table */ 131 left = 1;
111 uInt f; /* i repeats in table every f entries */ 132 for (len = 1; len <= MAXBITS; len++) {
112 int g; /* maximum code length */ 133 left <<= 1;
113 int h; /* table level */ 134 left -= count[len];
114 register uInt i; /* counter, current code */ 135 if (left < 0) return -1; /* over-subscribed */
115 register uInt j; /* counter */ 136 }
116 register int k; /* number of bits in current code */ 137 if (left > 0 && (type == CODES || max != 1))
117 int l; /* bits per table (returned in m) */ 138 return -1; /* incomplete set */
118 uInt mask; /* (1 << w) - 1, to avoid cc -O bug on HP */
119 register uInt *p; /* pointer into c[], b[], or v[] */
120 inflate_huft *q; /* points to current table */
121 struct inflate_huft_s r; /* table entry for structure assignment */
122 inflate_huft *u[BMAX]; /* table stack */
123 register int w; /* bits before this table == (l * h) */
124 uInt x[BMAX+1]; /* bit offsets, then code stack */
125 uInt *xp; /* pointer into x */
126 int y; /* number of dummy codes added */
127 uInt z; /* number of entries in current table */
128 139
140 /* generate offsets into symbol table for each length for sorting */
141 offs[1] = 0;
142 for (len = 1; len < MAXBITS; len++)
143 offs[len + 1] = offs[len] + count[len];
129 144
130 /* Generate counts for each bit length */ 145 /* sort symbols by length, by symbol order within each length */
131 p = c; 146 for (sym = 0; sym < codes; sym++)
132 #define C0 *p++ = 0; 147 if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
133 #define C2 C0 C0 C0 C0
134 #define C4 C2 C2 C2 C2
135 C4 /* clear c[]--assume BMAX+1 is 16 */
136 p = b; i = n;
137 do {
138 c[*p++]++; /* assume all entries <= BMAX */
139 } while (--i);
140 if (c[0] == n) /* null input--all zero length codes */
141 {
142 *t = NULL;
143 *m = 0;
144 return Z_OK;
145 }
146 148
149 /*
150 Create and fill in decoding tables. In this loop, the table being
151 filled is at next and has curr index bits. The code being used is huff
152 with length len. That code is converted to an index by dropping drop
153 bits off of the bottom. For codes where len is less than drop + curr,
154 those top drop + curr - len bits are incremented through all values to
155 fill the table with replicated entries.
147 156
148 /* Find minimum and maximum length, bound *m by those */ 157 root is the number of index bits for the root table. When len exceeds
149 l = *m; 158 root, sub-tables are created pointed to by the root entry with an index
150 for (j = 1; j <= BMAX; j++) 159 of the low root bits of huff. This is saved in low to check for when a
151 if (c[j]) 160 new sub-table should be started. drop is zero when the root table is
152 break; 161 being filled, and drop is root when sub-tables are being filled.
153 k = j; /* minimum code length */
154 if ((uInt)l < j)
155 l = j;
156 for (i = BMAX; i; i--)
157 if (c[i])
158 break;
159 g = i; /* maximum code length */
160 if ((uInt)l > i)
161 l = i;
162 *m = l;
163 162
163 When a new sub-table is needed, it is necessary to look ahead in the
164 code lengths to determine what size sub-table is needed. The length
165 counts are used for this, and so count[] is decremented as codes are
166 entered in the tables.
164 167
165 /* Adjust last length count to fill out codes, if needed */ 168 used keeps track of how many table entries have been allocated from the
166 for (y = 1 << j; j < i; j++, y <<= 1) 169 provided *table space. It is checked when a LENS table is being made
167 if ((y -= c[j]) < 0) 170 against the space in *table, ENOUGH, minus the maximum space needed by
168 return Z_DATA_ERROR; 171 the worst case distance code, MAXD. This should never happen, but the
169 if ((y -= c[i]) < 0) 172 sufficiency of ENOUGH has not been proven exhaustively, hence the check.
170 return Z_DATA_ERROR; 173 This assumes that when type == LENS, bits == 9.
171 c[i] += y;
172 174
175 sym increments through all symbols, and the loop terminates when
176 all codes of length max, i.e. all codes, have been processed. This
177 routine permits incomplete codes, so another loop after this one fills
178 in the rest of the decoding tables with invalid code markers.
179 */
173 180
174 /* Generate starting offsets into the value table for each length */ 181 /* set up for code type */
175 x[1] = j = 0; 182 switch (type) {
176 p = c + 1; xp = x + 2; 183 case CODES:
177 while (--i) { /* note that i == g from above */ 184 base = extra = work; /* dummy value--not used */
178 *xp++ = (j += *p++); 185 end = 19;
179 } 186 break;
187 case LENS:
188 base = lbase;
189 base -= 257;
190 extra = lext;
191 extra -= 257;
192 end = 256;
193 break;
194 default: /* DISTS */
195 base = dbase;
196 extra = dext;
197 end = -1;
198 }
180 199
200 /* initialize state for loop */
201 huff = 0; /* starting code */
202 sym = 0; /* starting code symbol */
203 len = min; /* starting code length */
204 next = *table; /* current table to fill in */
205 curr = root; /* current table index bits */
206 drop = 0; /* current bits to drop from code for index */
207 low = (unsigned)(-1); /* trigger new sub-table when len > root */
208 used = 1U << root; /* use root table entries */
209 mask = used - 1; /* mask for comparing low */
181 210
182 /* Make a table of values in order of bit lengths */ 211 /* check available table space */
183 p = b; i = 0; 212 if (type == LENS && used >= ENOUGH - MAXD)
184 do { 213 return 1;
185 if ((j = *p++) != 0)
186 v[x[j]++] = i;
187 } while (++i < n);
188 n = x[g]; /* set n to length of v */
189 214
190 215 /* process all codes and make table entries */
191 /* Generate the Huffman codes and for each, make the table entries */ 216 for (;;) {
192 x[0] = i = 0; /* first Huffman code is zero */ 217 /* create table entry */
193 p = v; /* grab values in bit order */ 218 this.bits = (unsigned char)(len - drop);
194 h = -1; /* no tables yet--level -1 */ 219 if ((int)(work[sym]) < end) {
195 w = -l; /* bits decoded == (l * h) */ 220 this.op = (unsigned char)0;
196 u[0] = NULL; /* just to keep compilers happy */ 221 this.val = work[sym];
197 q = NULL; /* ditto */
198 z = 0; /* ditto */
199
200 /* go through the bit lengths (k already is bits in shortest code) */
201 for (; k <= g; k++)
202 {
203 a = c[k];
204 while (a--)
205 {
206 /* here i is the Huffman code of length k bits for value *p */
207 /* make tables up to required level */
208 while (k > w + l)
209 {
210 h++;
211 w += l; /* previous table always l bits */
212
213 /* compute minimum size table less than or equal to l bits */
214 z = g - w;
215 z = z > (uInt)l ? l : z; /* table size upper limit */
216 if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */
217 { /* too few codes for k-w bit table */
218 f -= a + 1; /* deduct codes from patterns left */
219 xp = c + k;
220 if (j < z)
221 while (++j < z) /* try smaller tables up to z bits */
222 {
223 if ((f <<= 1) <= *++xp)
224 break; /* enough codes to use up j bits */
225 f -= *xp; /* else deduct codes from patterns */
226 }
227 } 222 }
228 z = 1 << j; /* table entries for j-bit table */ 223 else if ((int)(work[sym]) > end) {
224 this.op = (unsigned char)(extra[work[sym]]);
225 this.val = base[work[sym]];
226 }
227 else {
228 this.op = (unsigned char)(32 + 64); /* end of block */
229 this.val = 0;
230 }
229 231
230 /* allocate new table */ 232 /* replicate for those indices with low len bits equal to huff */
231 if (*hn + z > MANY) /* (note: doesn't matter for fixed) */ 233 incr = 1U << (len - drop);
232 return Z_DATA_ERROR; /* overflow of MANY */ 234 fill = 1U << curr;
233 u[h] = q = hp + *hn; 235 min = fill; /* save offset to next table */
234 *hn += z; 236 do {
237 fill -= incr;
238 next[(huff >> drop) + fill] = this;
239 } while (fill != 0);
235 240
236 /* connect to last table, if there is one */ 241 /* backwards increment the len-bit code huff */
237 if (h) 242 incr = 1U << (len - 1);
238 { 243 while (huff & incr)
239 x[h] = i; /* save pattern for backing up */ 244 incr >>= 1;
240 r.bits = (Byte)l; /* bits to dump before this table */ 245 if (incr != 0) {
241 r.exop = (Byte)j; /* bits in this table */ 246 huff &= incr - 1;
242 j = i >> (w - l); 247 huff += incr;
243 r.base = (uInt)(q - u[h-1] - j); /* offset to this table */
244 u[h-1][j] = r; /* connect to last table */
245 } 248 }
246 else 249 else
247 *t = q; /* first table is returned result */ 250 huff = 0;
248 }
249 251
250 /* set up table entry in r */ 252 /* go to next symbol, update count, len */
251 r.bits = (Byte)(k - w); 253 sym++;
252 if (p >= v + n) 254 if (--(count[len]) == 0) {
253 r.exop = 128 + 64; /* out of values--invalid code */ 255 if (len == max) break;
254 else if (*p < s) 256 len = lens[work[sym]];
255 { 257 }
256 r.exop = (Byte)(*p < 256 ? 0 : 32 + 64); /* 256 is end-of-block */
257 r.base = *p++; /* simple code is just the value */
258 }
259 else
260 {
261 r.exop = (Byte)(e[*p - s] + 16 + 64);/* non-simple--look up in lists */
262 r.base = d[*p++ - s];
263 }
264 258
265 /* fill code-like entries with r */ 259 /* create new sub-table if needed */
266 f = 1 << (k - w); 260 if (len > root && (huff & mask) != low) {
267 for (j = i >> w; j < z; j += f) 261 /* if first time, transition to sub-tables */
268 q[j] = r; 262 if (drop == 0)
263 drop = root;
269 264
270 /* backwards increment the k-bit code i */ 265 /* increment past last table */
271 for (j = 1 << (k - 1); i & j; j >>= 1) 266 next += min; /* here min is 1 << curr */
272 i ^= j;
273 i ^= j;
274 267
275 /* backup over finished tables */ 268 /* determine length of next table */
276 mask = (1 << w) - 1; /* needed on HP, cc -O bug */ 269 curr = len - drop;
277 while ((i & mask) != x[h]) 270 left = (int)(1 << curr);
278 { 271 while (curr + drop < max) {
279 h--; /* don't need to update q */ 272 left -= count[curr + drop];
280 w -= l; 273 if (left <= 0) break;
281 mask = (1 << w) - 1; 274 curr++;
282 } 275 left <<= 1;
283 } 276 }
284 }
285 277
278 /* check for enough space */
279 used += 1U << curr;
280 if (type == LENS && used >= ENOUGH - MAXD)
281 return 1;
286 282
287 /* Return Z_BUF_ERROR if we were given an incomplete table */ 283 /* point entry in root table to sub-table */
288 return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK; 284 low = huff & mask;
289 } 285 (*table)[low].op = (unsigned char)curr;
286 (*table)[low].bits = (unsigned char)root;
287 (*table)[low].val = (unsigned short)(next - *table);
288 }
289 }
290 290
291 /*
292 Fill in rest of table for incomplete codes. This loop is similar to the
293 loop above in incrementing huff for table indices. It is assumed that
294 len is equal to curr + drop, so there is no loop needed to increment
295 through high index bits. When the current sub-table is filled, the loop
296 drops back to the root table to fill in any remaining entries there.
297 */
298 this.op = (unsigned char)64; /* invalid code marker */
299 this.bits = (unsigned char)(len - drop);
300 this.val = (unsigned short)0;
301 while (huff != 0) {
302 /* when done with sub-table, drop back to root table */
303 if (drop != 0 && (huff & mask) != low) {
304 drop = 0;
305 len = root;
306 next = *table;
307 this.bits = (unsigned char)len;
308 }
291 309
292 int zlib_inflate_trees_bits( 310 /* put invalid code marker in table */
293 uInt *c, /* 19 code lengths */ 311 next[huff >> drop] = this;
294 uInt *bb, /* bits tree desired/actual depth */
295 inflate_huft **tb, /* bits tree result */
296 inflate_huft *hp, /* space for trees */
297 z_streamp z /* for messages */
298 )
299 {
300 int r;
lib/zlib_inflate/inftrees.h
1 /* inftrees.h -- header to use inftrees.c 1 /* inftrees.h -- header to use inftrees.c
2 * Copyright (C) 1995-1998 Mark Adler 2 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6 /* WARNING: this file should *not* be used by applications. It is 6 /* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is 7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h. 8 subject to change. Applications should only use zlib.h.
9 */ 9 */
10 10
11 /* Huffman code lookup table entry--this entry is four bytes for machines 11 /* Structure for decoding tables. Each entry provides either the
12 that have 16-bit pointers (e.g. PC's in the small or medium model). */ 12 information needed to do the operation requested by the code that
13 indexed that table entry, or it provides a pointer to another
14 table that indexes more bits of the code. op indicates whether
15 the entry is a pointer to another table, a literal, a length or
16 distance, an end-of-block, or an invalid code. For a table
17 pointer, the low four bits of op is the number of index bits of
18 that table. For a length or distance, the low four bits of op
19 is the number of extra bits to get after the code. bits is
20 the number of bits in this code or part of the code to drop off
21 of the bit buffer. val is the actual byte to output in the case
22 of a literal, the base length or distance, or the offset from
23 the current table to the next table. Each entry is four bytes. */
24 typedef struct {
25 unsigned char op; /* operation, extra bits, table bits */
26 unsigned char bits; /* bits in this part of the code */
27 unsigned short val; /* offset in table or code value */
28 } code;
13 29
14 #ifndef _INFTREES_H 30 /* op values as set by inflate_table():
15 #define _INFTREES_H 31 00000000 - literal
32 0000tttt - table link, tttt != 0 is the number of table index bits
33 0001eeee - length or distance, eeee is the number of extra bits
34 01100000 - end of block
35 01000000 - invalid code
36 */
16 37
17 typedef struct inflate_huft_s inflate_huft;
18
19 struct inflate_huft_s {
20 union {
21 struct {
22 Byte Exop; /* number of extra bits or operation */
23 Byte Bits; /* number of bits in this code or subcode */
24 } what;
25 uInt pad; /* pad structure to a power of 2 (4 bytes for */
26 } word; /* 16-bit, 8 bytes for 32-bit int's) */
27 uInt base; /* literal, length base, distance base,
28 or table offset */
29 };
30
31 /* Maximum size of dynamic tree. The maximum found in a long but non- 38 /* Maximum size of dynamic tree. The maximum found in a long but non-
32 exhaustive search was 1004 huft structures (850 for length/literals 39 exhaustive search was 1444 code structures (852 for length/literals
33 and 154 for distances, the latter actually the result of an 40 and 592 for distances, the latter actually the result of an
34 exhaustive search). The actual maximum is not known, but the 41 exhaustive search). The true maximum is not known, but the value
35 value below is more than safe. */ 42 below is more than safe. */
36 #define MANY 1440 43 #define ENOUGH 2048
44 #define MAXD 592
37 45
38 extern int zlib_inflate_trees_bits ( 46 /* Type of code to build for inftable() */
39 uInt *, /* 19 code lengths */ 47 typedef enum {
40 uInt *, /* bits tree desired/actual depth */ 48 CODES,
41 inflate_huft **, /* bits tree result */ 49 LENS,
42 inflate_huft *, /* space for trees */ 50 DISTS
43 z_streamp); /* for messages */ 51 } codetype;
lib/zlib_inflate/infutil.c
1 /* inflate_util.c -- data and routines common to blocks and codes File was deleted
2 * Copyright (C) 1995-1998 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6 #include <linux/zutil.h>
7 #include "infblock.h"
8 #include "inftrees.h"
9 #include "infcodes.h"
10 #include "infutil.h"
11
12 struct inflate_codes_state;
13
14 /* And'ing with mask[n] masks the lower n bits */
15 uInt zlib_inflate_mask[17] = {
16 0x0000,
17 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
18 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
19 };
20
21
22 /* copy as much as possible from the sliding window to the output area */
23 int zlib_inflate_flush(
24 inflate_blocks_statef *s,
25 z_streamp z,
26 int r
27 )
28 {
29 uInt n;
30 Byte *p;
31 Byte *q;
32
33 /* local copies of source and destination pointers */
34 p = z->next_out;
35 q = s->read;
36
37 /* compute number of bytes to copy as far as end of window */
38 n = (uInt)((q <= s->write ? s->write : s->end) - q);
39 if (n > z->avail_out) n = z->avail_out;
40 if (n && r == Z_BUF_ERROR) r = Z_OK;
41
42 /* update counters */
43 z->avail_out -= n;
44 z->total_out += n;
45
46 /* update check information */
47 if (s->checkfn != NULL)
48 z->adler = s->check = (*s->checkfn)(s->check, q, n);
49
50 /* copy as far as end of window */
51 memcpy(p, q, n);
52 p += n;
53 q += n;
54
55 /* see if more to copy at beginning of window */
56 if (q == s->end)
57 {
58 /* wrap pointers */
59 q = s->window;
60 if (s->write == s->end)
61 s->write = s->window;
62
63 /* compute bytes to copy */
64 n = (uInt)(s->write - q);
65 if (n > z->avail_out) n = z->avail_out;
66 if (n && r == Z_BUF_ERROR) r = Z_OK;
67
68 /* update counters */
69 z->avail_out -= n;
70 z->total_out += n;
71
72 /* update check information */
73 if (s->checkfn != NULL)
74 z->adler = s->check = (*s->checkfn)(s->check, q, n);
75
76 /* copy */
77 memcpy(p, q, n);
78 p += n;
79 q += n;
80 }
81
82 /* update pointers */
83 z->next_out = p;
84 s->read = q;
85
86 /* done */
87 return r;
88 }
89 1 /* inflate_util.c -- data and routines common to blocks and codes
lib/zlib_inflate/infutil.h
1 /* infutil.h -- types and macros common to blocks and codes 1 /* infutil.h -- types and macros common to blocks and codes
2 * Copyright (C) 1995-1998 Mark Adler 2 * Copyright (C) 1995-1998 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6 /* WARNING: this file should *not* be used by applications. It is 6 /* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is 7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h. 8 subject to change. Applications should only use zlib.h.
9 */ 9 */
10 10
11 #ifndef _INFUTIL_H 11 #ifndef _INFUTIL_H
12 #define _INFUTIL_H 12 #define _INFUTIL_H
13 13
14 #include <linux/zconf.h> 14 #include <linux/zlib.h>
15 #include "inftrees.h"
16 #include "infcodes.h"
17 15
18 typedef enum {
19 TYPE, /* get type bits (3, including end bit) */
20 LENS, /* get lengths for stored */
21 STORED, /* processing stored block */
22 TABLE, /* get table lengths */
23 BTREE, /* get bit lengths tree for a dynamic block */
24 DTREE, /* get length, distance trees for a dynamic block */
25 CODES, /* processing fixed or dynamic block */
26 DRY, /* output remaining window bytes */
27 B_DONE, /* finished last block, done */
28 B_BAD} /* got a data error--stuck here */
29 inflate_block_mode;
30
31 /* inflate blocks semi-private state */
32 struct inflate_blocks_state {
33
34 /* mode */
35 inflate_block_mode mode; /* current inflate_block mode */
36
37 /* mode dependent information */
38 union {
39 uInt left; /* if STORED, bytes left to copy */
40 struct {
41 uInt table; /* table lengths (14 bits) */
42 uInt index; /* index into blens (or border) */
43 uInt *blens; /* bit lengths of codes */
44 uInt bb; /* bit length tree depth */
45 inflate_huft *tb; /* bit length decoding tree */
46 } trees; /* if DTREE, decoding info for trees */
47 struct {
48 inflate_codes_statef
49 *codes;
50 } decode; /* if CODES, current state */
51 } sub; /* submode */
52 uInt last; /* true if this block is the last block */
53
54 /* mode independent information */
55 uInt bitk; /* bits in bit buffer */
56 uLong bitb; /* bit buffer */
57 inflate_huft *hufts; /* single malloc for tree space */
58 Byte *window; /* sliding window */
59 Byte *end; /* one byte after sliding window */
60 Byte *read; /* window read pointer */
61 Byte *write; /* window write pointer */
62 check_func checkfn; /* check function */
63 uLong check; /* check on output */
64
65 };
66
67
68 /* defines for inflate input/output */
69 /* update pointers and return */
70 #define UPDBITS {s->bitb=b;s->bitk=k;}
71 #define UPDIN {z->avail_in=n;z->total_in+=p-z->next_in;z->next_in=p;}
72 #define UPDOUT {s->write=q;}
73 #define UPDATE {UPDBITS UPDIN UPDOUT}
74 #define LEAVE {UPDATE return zlib_inflate_flush(s,z,r);}
75 /* get bytes and bits */
76 #define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;}
77 #define NEEDBYTE {if(n)r=Z_OK;else LEAVE}
78 #define NEXTBYTE (n--,*p++)
79 #define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<<k;k+=8;}}
80 #define DUMPBITS(j) {b>>=(j);k-=(j);}
81 /* output bytes */
82 #define WAVAIL (uInt)(q<s->read?s->read-q-1:s->end-q)
83 #define LOADOUT {q=s->write;m=(uInt)WAVAIL;}
84 #define WRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}}
85 #define FLUSH {UPDOUT r=zlib_inflate_flush(s,z,r); LOADOUT}
86 #define NEEDOUT {if(m==0){WRAP if(m==0){FLUSH WRAP if(m==0) LEAVE}}r=Z_OK;}
87 #define OUTBYTE(a) {*q++=(Byte)(a);m--;}
88 /* load local pointers */
89 #define LOAD {LOADIN LOADOUT}
90
91 /* masks for lower bits (size given to avoid silly warnings with Visual C++) */
92 extern uInt zlib_inflate_mask[17];
93
94 /* copy as much as possible from the sliding window to the output area */
95 extern int zlib_inflate_flush (
96 inflate_blocks_statef *,
97 z_streamp ,
98 int);
99
100 /* inflate private state */
101 typedef enum {
102 METHOD, /* waiting for method byte */
103 FLAG, /* waiting for flag byte */
104 DICT4, /* four dictionary check bytes to go */
105 DICT3, /* three dictionary check bytes to go */
106 DICT2, /* two dictionary check bytes to go */
107 DICT1, /* one dictionary check byte to go */
108 DICT0, /* waiting for inflateSetDictionary */
109 BLOCKS, /* decompressing blocks */
110 CHECK4, /* four check bytes to go */
111 CHECK3, /* three check bytes to go */
112 CHECK2, /* two check bytes to go */
113 CHECK1, /* one check byte to go */
114 I_DONE, /* finished check, done */
115 I_BAD} /* got an error--stay here */
116 inflate_mode;
117
118 struct internal_state {
119
120 /* mode */
121 inflate_mode mode; /* current inflate mode */
122
123 /* mode dependent information */
124 union {
125 uInt method; /* if FLAGS, method byte */
126 struct {
127 uLong was; /* computed check value */
128 uLong need; /* stream check value */
129 } check; /* if CHECK, check values to compare */
130 uInt marker; /* if BAD, inflateSync's marker bytes count */
131 } sub; /* submode */
132
133 /* mode independent information */
134 int nowrap; /* flag for no wrapper */
135 uInt wbits; /* log2(window size) (8..15, defaults to 15) */
136 inflate_blocks_statef
137 *blocks; /* current inflate_blocks state */
138
139 };
140
141 /* inflate codes private state */
142 typedef enum { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
143 START, /* x: set up for LEN */
144 LEN, /* i: get length/literal/eob next */
145 LENEXT, /* i: getting length extra (have base) */
146 DIST, /* i: get distance next */
147 DISTEXT, /* i: getting distance extra */
148 COPY, /* o: copying bytes in window, waiting for space */
149 LIT, /* o: got literal, waiting for output space */
150 WASH, /* o: got eob, possibly still output waiting */
151 END, /* x: got eob and all data flushed */
152 BADCODE} /* x: got error */
153 inflate_codes_mode;
154
155 struct inflate_codes_state {
156
157 /* mode */
158 inflate_codes_mode mode; /* current inflate_codes mode */
159
160 /* mode dependent information */
161 uInt len;
162 union {
163 struct {
164 inflate_huft *tree; /* pointer into tree */
165 uInt need; /* bits needed */
166 } code; /* if LEN or DIST, where in tree */
167 uInt lit; /* if LIT, literal */
168 struct {
169 uInt get; /* bits to get for extra */
170 uInt dist; /* distance back to copy from */
171 } copy; /* if EXT or COPY, where and how much */
172 } sub; /* submode */
173
174 /* mode independent information */
175 Byte lbits; /* ltree bits decoded per branch */
176 Byte dbits; /* dtree bits decoder per branch */
177 inflate_huft *ltree; /* literal/length/eob tree */
178 inflate_huft *dtree; /* distance tree */
179
180 };
181
182 /* memory allocation for inflation */ 16 /* memory allocation for inflation */
183 17
184 struct inflate_workspace { 18 struct inflate_workspace {
185 inflate_codes_statef working_state; 19 struct inflate_state inflate_state;
186 struct inflate_blocks_state working_blocks_state;
187 struct internal_state internal_state;
188 unsigned int tree_work_area_1[19];
189 unsigned int tree_work_area_2[288];
190 unsigned working_blens[258 + 0x1f + 0x1f];
191 inflate_huft working_hufts[MANY];
192 unsigned char working_window[1 << MAX_WBITS]; 20 unsigned char working_window[1 << MAX_WBITS];
193 }; 21 };
194 22
195 #define WS(z) ((struct inflate_workspace *)(z->workspace)) 23 #define WS(z) ((struct inflate_workspace *)(z->workspace))
196 24
197 #endif 25 #endif
198 26