Previous 15994 Revisions Next

r14440 Monday 13th February, 2012 at 08:12:01 UTC by Miodrag Milanović
Sync with MAME r15371 (no whatsnew)
[ROOT]makefile
[src/emu]fileio.c fileio.h
[src/lib]lib.mak
[src/lib/lib7z]7z.h* 7zBuf.c* 7zBuf.h* 7zBuf2.c* 7zCrc.c* 7zCrc.h* 7zCrcOpt.c* 7zDec.c* 7zIn.c* 7zStream.c* 7zVersion.h* 7zVersion.rc* Aes.c* Aes.h* AesOpt.c* Alloc.c* Alloc.h* Bcj2.c* Bcj2.h* Bra.c* Bra.h* Bra86.c* BraIA64.c* BwtSort.c* BwtSort.h* CpuArch.c* CpuArch.h* Delta.c* Delta.h* HuffEnc.c* HuffEnc.h* LzFind.c* LzFind.h* LzFindMt.c* LzFindMt.h* LzHash.h* Lzma2Dec.c* Lzma2Dec.h* Lzma2Enc.c* Lzma2Enc.h* Lzma86.h* Lzma86Dec.c* Lzma86Enc.c* LzmaDec.c* LzmaDec.h* LzmaEnc.c* LzmaEnc.h* LzmaLib.c* LzmaLib.h* MtCoder.c* MtCoder.h* Ppmd.h* Ppmd7.c* Ppmd7.h* Ppmd7Dec.c* Ppmd7Enc.c* Ppmd8.c* Ppmd8.h* Ppmd8Dec.c* Ppmd8Enc.c* RotateDefs.h* Sha256.c* Sha256.h* Sort.c* Sort.h* Threads.c* Threads.h* Types.h* Xz.c* Xz.h* XzCrc64.c* XzCrc64.h* XzDec.c* XzEnc.c* XzEnc.h* XzIn.c* x7zAlloc.c* x7zAlloc.h* x7zFile.c* x7zFile.h*
[src/lib/util]un7z.c* un7z.h*
[src/mame]mame.lst
[src/mame/drivers]30test.c pacman.c
[src/mame/layout]30test.lay avalnche.lay circus.lay invad2ct.lay kungfur.lay videopin.lay
[src/osd/sdl]README_SDL20.txt* debugwin.c draw13.c drawogl.c drawsdl.c gl_shader_mgr.c input.c osd_opengl.h osdsdl.h sdl.mak sdlinc.h* sdlmain.c sdlmisc_macosx.c sdlmisc_os2.c sdlmisc_win32.c sdlos_macosx.c sdlos_os2.c sdlos_unix.c sdlos_win32.c sdlsync_ntc.c sdlsync_os2.c sdlsync_sdl.c sdlsync_tc.c sound.c testkeys.c video.c window.c window.h

src/mame/mame.lst
r14439r14440
7979ctrpllrp      // hack
8080eyes         // (c) 1982 Digitrex Techstar + "Rockola presents"
8181eyes2         // (c) 1982 Techstar + "Rockola presents"
82eyesb         // bootleg
8283eyeszac         // (c) 1982 Techstar / Zaccaria
8384eyeszacb      // bootleg
8485birdiy         // (c) 1983 Mama Top
src/mame/layout/avalnche.lay
r14439r14440
1010         <color red="0.125" green="0.125" blue="1" />
1111      </rect>
1212      <rect>
13         <bounds left="0" top="20" right="256" bottom="29" />
13         <bounds left="0" top="20" right="256" bottom="28.5" />
1414         <color red="1" green="1" blue="0.125" />
1515      </rect>
1616      <rect>
17         <bounds left="0" top="29" right="256" bottom="40" />
17         <bounds left="0" top="28.5" right="256" bottom="40.5" />
1818         <color red="1" green="0.5" blue="0.0627" />
1919      </rect>
2020      <rect>
21         <bounds left="0" top="40" right="256" bottom="240" />
21         <bounds left="0" top="40.5" right="256" bottom="240" />
2222         <color red="0.5" green="1" blue="1" />
2323      </rect>
2424   </element>
src/mame/layout/circus.lay
r14439r14440
1010         <color red="0.125" green="0.125" blue="1" />
1111      </rect>
1212      <rect>
13         <bounds left="0" top="36" right="248" bottom="48" />
13         <bounds left="0" top="36" right="248" bottom="48.5" />
1414         <color red="0.125" green="1" blue="0.125" />
1515      </rect>
1616      <rect>
17         <bounds left="0" top="48" right="248" bottom="64" />
17         <bounds left="0" top="48.5" right="248" bottom="64.5" />
1818         <color red="1" green="1" blue="0.125" />
1919      </rect>
2020      <rect>
21         <bounds left="0" top="64" right="248" bottom="256" />
21         <bounds left="0" top="64.5" right="248" bottom="256" />
2222         <color red="1" green="1" blue="1" />
2323      </rect>
2424   </element>
src/mame/layout/invad2ct.lay
r14439r14440
22<mamelayout version="2">
33   <element name="overlay">
44      <rect>
5         <bounds left="0" top="0" right="224" bottom="29" />
5         <bounds left="0" top="0" right="224" bottom="27.5" />
66         <color red="1" green="1" blue="0.125" />
77      </rect>
88      <rect>
9         <bounds left="0" top="29" right="224" bottom="52" />
9         <bounds left="0" top="27.5" right="224" bottom="52" />
1010         <color red="0.5" green="1" blue="0" />
1111      </rect>
1212      <rect>
src/mame/layout/30test.lay
r14439r14440
11<?xml version="1.0"?>
22<mamelayout version="2">
3   <element name="digit" defstate="10">
3
4<!-- define elements -->
5
6   <element name="digit" defstate="0">
47      <led7seg>
5         <color red="1.0" green="0.0" blue="0.0" />
8         <color red="1.0" green="0.1" blue="0.1" />
69      </led7seg>
710   </element>
811
9   <element name="rank">
10      <rect state="1">
11         <color red="1.0" green="0.0" blue="0.0" />
12   <element name="disk_lamp">
13      <disk state="1">
14         <color red="1.0" green="0.1" blue="0.1" />
15      </disk>
16      <disk state="0">
17         <color red="0.1" green="0.0" blue="0.0" />
18      </disk>
19   </element>
20
21   <element name="disk_blue">
22      <disk>
23         <color red="0.1" green="0.35" blue="0.8" />
24      </disk>
25   </element>
26   <element name="disk_red">
27      <disk>
28         <color red="0.8" green="0.1" blue="0.0" />
29      </disk>
30   </element>
31
32   <element name="static_black">
33      <rect>
34         <color red="0.0" green="0.0" blue="0.0" />
1235      </rect>
36   </element>
37   <element name="static_blue">
38      <rect>
39         <color red="0.1" green="0.35" blue="0.8" />
40      </rect>
41   </element>
42   <element name="static_yellow">
43      <rect>
44         <color red="0.95" green="0.8" blue="0.1" />
45      </rect>
46   </element>
47   <element name="static_red">
48      <rect>
49         <color red="0.8" green="0.1" blue="0.0" />
50      </rect>
51   </element>
52
53   <!-- note: cab has a white button underneath, -->
54   <!-- make the border white-ish instead (normally red), -->
55   <!-- implying that it should be clickable -->
56   <element name="led_box" defstate="0">
1357      <rect state="0">
14         <color red="0.1" green="0.0" blue="0.0" />
58         <color red="0.7" green="0.7" blue="0.8" />
59         <bounds x="0" y="0" width="30" height="25" />
1560      </rect>
61      <rect state="0">
62         <color red="0.0" green="0.0" blue="0.0" />
63         <bounds x="2" y="2" width="26" height="21" />
64      </rect>
65      <rect state="0">
66         <color red="0.0" green="0.0" blue="0.0" />
67         <bounds x="2" y="2" width="26" height="21" />
68      </rect>
69      <rect state="1">
70         <color red="1.0" green="0.7" blue="0.8" />
71         <bounds x="1" y="1" width="28" height="23" />
72      </rect>
73      <rect state="1">
74         <color red="0.0" green="0.0" blue="0.0" />
75         <bounds x="3" y="3" width="24" height="19" />
76      </rect>
1677   </element>
1778
18   <view name="Simple LEDs">
19      <bounds left="0" top="0" right="3.4" bottom="4.3" />
2079
80<!-- define text -->
2181
22<!-- the grid -->
82   <element name="text_score">
83      <text string="SCORE">
84         <color red="0.1" green="0.35" blue="0.8" />
85      </text>
86   </element>
87   <element name="text_time">
88      <text string="TIME">
89         <color red="0.1" green="0.35" blue="0.8" />
90      </text>
91   </element>
92   <element name="text_best">
93      <text string="BEST">
94         <color red="0.1" green="0.35" blue="0.8" />
95      </text>
96   </element>
2397
24      <bezel name="digit0" element="digit">
25         <bounds x="0.0" y="1.3" width="0.2" height="0.3" />
26      </bezel>
98   <element name="text_1">
99      <text string="1." align="2">
100         <color red="0.1" green="0.35" blue="0.8" />
101      </text>
102   </element>
103   <element name="text_2">
104      <text string="2." align="2">
105         <color red="0.1" green="0.35" blue="0.8" />
106      </text>
107   </element>
108   <element name="text_3">
109      <text string="3." align="2">
110         <color red="0.1" green="0.35" blue="0.8" />
111      </text>
112   </element>
27113
28      <bezel name="digit1" element="digit">
29         <bounds x="0.2" y="1.3" width="0.2" height="0.3" />
30      </bezel>
114   <element name="text_rank1">
115      <text string="great!!" align="1">
116         <color red="0.1" green="0.35" blue="0.8" />
117      </text>
118   </element>
119   <element name="text_rank2">
120      <text string="pretty good" align="1">
121         <color red="0.1" green="0.35" blue="0.8" />
122      </text>
123   </element>
124   <element name="text_rank3">
125      <text string="not bad" align="1">
126         <color red="0.1" green="0.35" blue="0.8" />
127      </text>
128   </element>
129   <element name="text_rank4">
130      <text string="mediocre" align="1">
131         <color red="0.1" green="0.35" blue="0.8" />
132      </text>
133   </element>
134   <element name="text_rank5">
135      <text string="pretty bad" align="1">
136         <color red="0.1" green="0.35" blue="0.8" />
137      </text>
138   </element>
139   <element name="text_rank6">
140      <text string="awful" align="1">
141         <color red="0.1" green="0.35" blue="0.8" />
142      </text>
143   </element>
31144
145   <element name="text_gameover">
146      <text string="game over" align="1">
147         <color red="0.1" green="0.35" blue="0.8" />
148      </text>
149   </element>
32150
33      <bezel name="digit2" element="digit">
34         <bounds x="0.6" y="1.3" width="0.2" height="0.3" />
35      </bezel>
36151
37      <bezel name="digit3" element="digit">
38         <bounds x="0.8" y="1.3" width="0.2" height="0.3" />
39      </bezel>
40152
41153
42      <bezel name="digit4" element="digit">
43         <bounds x="1.2" y="1.3" width="0.2" height="0.3" />
44      </bezel>
45154
46      <bezel name="digit5" element="digit">
47         <bounds x="1.4" y="1.3" width="0.2" height="0.3" />
155   <view name="Internal Layout">
156      <bounds left="0" top="0" right="246" bottom="246" />
157      <bezel element="static_blue">
158         <bounds left="0" right="246" top="0" bottom="246" />
48159      </bezel>
49160
50161
51      <bezel name="digit6" element="digit">
52         <bounds x="1.8" y="1.3" width="0.2" height="0.3" />
162<!-- info box -->
163
164      <bezel element="static_red">
165         <bounds x="18" y="5" width="210" height="69" />
53166      </bezel>
54167
55      <bezel name="digit7" element="digit">
56         <bounds x="2.0" y="1.3" width="0.2" height="0.3" />
168      <bezel element="static_blue">
169         <bounds x="18" y="5" width="4" height="4" />
57170      </bezel>
171      <bezel element="disk_red">
172         <bounds x="18" y="5" width="8" height="8" />
173      </bezel>
58174
59
60      <bezel name="digit8" element="digit">
61         <bounds x="2.4" y="1.3" width="0.2" height="0.3" />
175      <bezel element="static_blue">
176         <bounds x="18" y="70" width="4" height="4" />
62177      </bezel>
178      <bezel element="disk_red">
179         <bounds x="18" y="66" width="8" height="8" />
180      </bezel>
63181
64      <bezel name="digit9" element="digit">
65         <bounds x="2.6" y="1.3" width="0.2" height="0.3" />
182      <bezel element="static_blue">
183         <bounds x="224" y="5" width="4" height="4" />
66184      </bezel>
185      <bezel element="disk_red">
186         <bounds x="220" y="5" width="8" height="8" />
187      </bezel>
67188
68
69      <bezel name="digit10" element="digit">
70         <bounds x="3.0" y="1.3" width="0.2" height="0.3" />
189      <bezel element="static_blue">
190         <bounds x="224" y="70" width="4" height="4" />
71191      </bezel>
192      <bezel element="disk_red">
193         <bounds x="220" y="66" width="8" height="8" />
194      </bezel>
72195
73      <bezel name="digit11" element="digit">
74         <bounds x="3.2" y="1.3" width="0.2" height="0.3" />
196      <bezel element="static_yellow">
197         <bounds x="20" y="7" width="206" height="65" />
75198      </bezel>
76199
77200
201<!-- score -->
78202
79
80      <bezel name="digit12" element="digit">
81         <bounds x="0.0" y="1.9" width="0.2" height="0.3" />
203      <bezel element="text_score">
204         <bounds x="25" y="7" width="37.4" height="7" />
82205      </bezel>
83206
84      <bezel name="digit13" element="digit">
85         <bounds x="0.2" y="1.9" width="0.2" height="0.3" />
207      <bezel element="static_blue">
208         <bounds x="25" y="14.3" width="37.4" height="28.9" />
86209      </bezel>
87
88
89      <bezel name="digit14" element="digit">
90         <bounds x="0.6" y="1.9" width="0.2" height="0.3" />
210      <bezel element="static_black">
211         <bounds x="25.7" y="15" width="36" height="27.5" />
91212      </bezel>
92213
93      <bezel name="digit15" element="digit">
94         <bounds x="0.8" y="1.9" width="0.2" height="0.3" />
214      <bezel name="digit70" element="digit">
215         <bounds x="26.7" y="16" width="17" height="25.5" />
95216      </bezel>
96
97
98      <bezel name="digit16" element="digit">
99         <bounds x="1.2" y="1.9" width="0.2" height="0.3" />
217      <bezel name="digit71" element="digit">
218         <bounds x="43.7" y="16" width="17" height="25.5" />
100219      </bezel>
101220
102      <bezel name="digit17" element="digit">
103         <bounds x="1.4" y="1.9" width="0.2" height="0.3" />
104      </bezel>
105221
222<!-- time -->
106223
107      <bezel name="digit18" element="digit">
108         <bounds x="1.8" y="1.9" width="0.2" height="0.3" />
224      <bezel element="text_time">
225         <bounds x="22.3" y="43" width="43.4" height="7" />
109226      </bezel>
110227
111      <bezel name="digit19" element="digit">
112         <bounds x="2.0" y="1.9" width="0.2" height="0.3" />
228      <bezel element="static_blue">
229         <bounds x="22.3" y="50.3" width="43.4" height="18.4" />
113230      </bezel>
231      <bezel element="static_black">
232         <bounds x="23" y="51" width="42" height="17" />
233      </bezel>
114234
115
116      <bezel name="digit20" element="digit">
117         <bounds x="2.4" y="1.9" width="0.2" height="0.3" />
235      <bezel name="digit60" element="digit">
236         <bounds x="24" y="52" width="10" height="15" />
118237      </bezel>
119238
120      <bezel name="digit21" element="digit">
121         <bounds x="2.6" y="1.9" width="0.2" height="0.3" />
239      <bezel name="digit61" element="digit">
240         <bounds x="34" y="52" width="10" height="15" />
122241      </bezel>
123242
124
125      <bezel name="digit22" element="digit">
126         <bounds x="3.0" y="1.9" width="0.2" height="0.3" />
243      <bezel name="digit62" element="digit">
244         <bounds x="44" y="52" width="10" height="15" />
127245      </bezel>
128246
129      <bezel name="digit23" element="digit">
130         <bounds x="3.2" y="1.9" width="0.2" height="0.3" />
247      <bezel name="digit63" element="digit">
248         <bounds x="54" y="52" width="10" height="15" />
131249      </bezel>
132250
133251
252<!-- today's highscores -->
134253
135
136      <bezel name="digit24" element="digit">
137         <bounds x="0.0" y="2.5" width="0.2" height="0.3" />
254      <bezel element="text_best">
255         <bounds x="73.3" y="7" width="23.4" height="7" />
138256      </bezel>
139257
140      <bezel name="digit25" element="digit">
141         <bounds x="0.2" y="2.5" width="0.2" height="0.3" />
258      <bezel element="text_1">
259         <bounds x="63" y="25.5" width="10" height="7" />
142260      </bezel>
143
144
145      <bezel name="digit26" element="digit">
146         <bounds x="0.6" y="2.5" width="0.2" height="0.3" />
261      <bezel element="text_2">
262         <bounds x="63" y="43.5" width="10" height="7" />
147263      </bezel>
148
149      <bezel name="digit27" element="digit">
150         <bounds x="0.8" y="2.5" width="0.2" height="0.3" />
264      <bezel element="text_3">
265         <bounds x="63" y="61.5" width="10" height="7" />
151266      </bezel>
152267
153
154      <bezel name="digit28" element="digit">
155         <bounds x="1.2" y="2.5" width="0.2" height="0.3" />
268      <bezel element="static_blue">
269         <bounds x="73.3" y="14.3" width="23.4" height="54.4" />
156270      </bezel>
157271
158      <bezel name="digit29" element="digit">
159         <bounds x="1.4" y="2.5" width="0.2" height="0.3" />
272      <bezel element="static_black">
273         <bounds x="74" y="15" width="22" height="17" />
160274      </bezel>
161
162
163      <bezel name="digit30" element="digit">
164         <bounds x="1.8" y="2.5" width="0.2" height="0.3" />
275      <bezel element="static_black">
276         <bounds x="74" y="33" width="22" height="17" />
165277      </bezel>
166
167      <bezel name="digit31" element="digit">
168         <bounds x="2.0" y="2.5" width="0.2" height="0.3" />
278      <bezel element="static_black">
279         <bounds x="74" y="51" width="22" height="17" />
169280      </bezel>
170281
171
172      <bezel name="digit32" element="digit">
173         <bounds x="2.4" y="2.5" width="0.2" height="0.3" />
282      <bezel name="digit64" element="digit">
283         <bounds x="75" y="16" width="10" height="15" />
174284      </bezel>
175
176      <bezel name="digit33" element="digit">
177         <bounds x="2.6" y="2.5" width="0.2" height="0.3" />
285      <bezel name="digit65" element="digit">
286         <bounds x="85" y="16" width="10" height="15" />
178287      </bezel>
179288
180
181      <bezel name="digit34" element="digit">
182         <bounds x="3.0" y="2.5" width="0.2" height="0.3" />
289      <bezel name="digit66" element="digit">
290         <bounds x="75" y="34" width="10" height="15" />
183291      </bezel>
292      <bezel name="digit67" element="digit">
293         <bounds x="85" y="34" width="10" height="15" />
294      </bezel>
184295
185      <bezel name="digit35" element="digit">
186         <bounds x="3.2" y="2.5" width="0.2" height="0.3" />
296      <bezel name="digit68" element="digit">
297         <bounds x="75" y="52" width="10" height="15" />
187298      </bezel>
299      <bezel name="digit69" element="digit">
300         <bounds x="85" y="52" width="10" height="15" />
301      </bezel>
188302
189303
304<!-- ranking -->
190305
191
192      <bezel name="digit36" element="digit">
193         <bounds x="0.0" y="3.1" width="0.2" height="0.3" />
306      <bezel element="disk_blue">
307         <bounds x="102.75" y="15.75" width="6.25" height="6.25" />
194308      </bezel>
195
196      <bezel name="digit37" element="digit">
197         <bounds x="0.2" y="3.1" width="0.2" height="0.3" />
309      <bezel name="lamp0" element="disk_lamp">
310         <bounds x="103" y="16" width="5.75" height="5.75" />
198311      </bezel>
199312
200
201      <bezel name="digit38" element="digit">
202         <bounds x="0.6" y="3.1" width="0.2" height="0.3" />
313      <bezel element="disk_blue">
314         <bounds x="102.75" y="22.25" width="6.25" height="6.25" />
203315      </bezel>
204
205      <bezel name="digit39" element="digit">
206         <bounds x="0.8" y="3.1" width="0.2" height="0.3" />
316      <bezel name="lamp1" element="disk_lamp">
317         <bounds x="103" y="22.5" width="5.75" height="5.75" />
207318      </bezel>
208319
209
210      <bezel name="digit40" element="digit">
211         <bounds x="1.2" y="3.1" width="0.2" height="0.3" />
320      <bezel element="disk_blue">
321         <bounds x="102.75" y="28.75" width="6.25" height="6.25" />
212322      </bezel>
213
214      <bezel name="digit41" element="digit">
215         <bounds x="1.4" y="3.1" width="0.2" height="0.3" />
323      <bezel name="lamp2" element="disk_lamp">
324         <bounds x="103" y="29" width="5.75" height="5.75" />
216325      </bezel>
217326
218
219      <bezel name="digit42" element="digit">
220         <bounds x="1.8" y="3.1" width="0.2" height="0.3" />
327      <bezel element="disk_blue">
328         <bounds x="102.75" y="35.25" width="6.25" height="6.25" />
221329      </bezel>
330      <bezel name="lamp3" element="disk_lamp">
331         <bounds x="103" y="35.5" width="5.75" height="5.75" />
332      </bezel>
222333
223      <bezel name="digit43" element="digit">
224         <bounds x="2.0" y="3.1" width="0.2" height="0.3" />
334      <bezel element="disk_blue">
335         <bounds x="102.75" y="41.75" width="6.25" height="6.25" />
225336      </bezel>
337      <bezel name="lamp4" element="disk_lamp">
338         <bounds x="103" y="42" width="5.75" height="5.75" />
339      </bezel>
226340
227
228      <bezel name="digit44" element="digit">
229         <bounds x="2.4" y="3.1" width="0.2" height="0.3" />
341      <bezel element="disk_blue">
342         <bounds x="102.75" y="48.25" width="6.25" height="6.25" />
230343      </bezel>
344      <bezel name="lamp5" element="disk_lamp">
345         <bounds x="103" y="48.5" width="5.75" height="5.75" />
346      </bezel>
231347
232      <bezel name="digit45" element="digit">
233         <bounds x="2.6" y="3.1" width="0.2" height="0.3" />
348      <bezel element="disk_blue">
349         <bounds x="102.75" y="54.75" width="6.25" height="6.25" />
234350      </bezel>
351      <bezel name="lamp6" element="disk_lamp">
352         <bounds x="103" y="55" width="5.75" height="5.75" />
353      </bezel>
235354
236
237      <bezel name="digit46" element="digit">
238         <bounds x="3.0" y="3.1" width="0.2" height="0.3" />
355      <bezel element="text_rank1">
356         <bounds x="111" y="15.25" width="40" height="6.5" />
239357      </bezel>
358      <bezel element="text_rank2">
359         <bounds x="111" y="21.75" width="40" height="6.5" />
360      </bezel>
361      <bezel element="text_rank3">
362         <bounds x="111" y="28.25" width="40" height="6.5" />
363      </bezel>
364      <bezel element="text_rank4">
365         <bounds x="111" y="34.75" width="40" height="6.5" />
366      </bezel>
367      <bezel element="text_rank5">
368         <bounds x="111" y="41.25" width="40" height="6.5" />
369      </bezel>
370      <bezel element="text_rank6">
371         <bounds x="111" y="47.75" width="40" height="6.5" />
372      </bezel>
240373
241      <bezel name="digit47" element="digit">
242         <bounds x="3.2" y="3.1" width="0.2" height="0.3" />
374      <bezel element="text_gameover">
375         <bounds x="111" y="54.25" width="40" height="6.5" />
243376      </bezel>
244377
245378
379<!-- the grid -->
380<!-- row 1 -->
246381
247
248      <bezel name="digit48" element="digit">
249         <bounds x="0.0" y="3.7" width="0.2" height="0.3" />
382      <bezel element="led_box" inputtag="IN0" inputmask="0x01">
383         <bounds x="18" y="80" width="30" height="25" />
250384      </bezel>
385      <bezel name="digit0" element="digit">
386         <bounds x="23" y="85" width="10" height="15" />
387      </bezel>
388      <bezel name="digit1" element="digit">
389         <bounds x="33" y="85" width="10" height="15" />
390      </bezel>
251391
252      <bezel name="digit49" element="digit">
253         <bounds x="0.2" y="3.7" width="0.2" height="0.3" />
392      <bezel element="led_box" inputtag="IN0" inputmask="0x02">
393         <bounds x="54" y="80" width="30" height="25" />
254394      </bezel>
395      <bezel name="digit2" element="digit">
396         <bounds x="59" y="85" width="10" height="15" />
397      </bezel>
398      <bezel name="digit3" element="digit">
399         <bounds x="69" y="85" width="10" height="15" />
400      </bezel>
255401
256
257      <bezel name="digit50" element="digit">
258         <bounds x="0.6" y="3.7" width="0.2" height="0.3" />
402      <bezel element="led_box" inputtag="IN0" inputmask="0x04">
403         <bounds x="90" y="80" width="30" height="25" />
259404      </bezel>
405      <bezel name="digit4" element="digit">
406         <bounds x="95" y="85" width="10" height="15" />
407      </bezel>
408      <bezel name="digit5" element="digit">
409         <bounds x="105" y="85" width="10" height="15" />
410      </bezel>
260411
261      <bezel name="digit51" element="digit">
262         <bounds x="0.8" y="3.7" width="0.2" height="0.3" />
412      <bezel element="led_box" inputtag="IN0" inputmask="0x08">
413         <bounds x="126" y="80" width="30" height="25" />
263414      </bezel>
415      <bezel name="digit6" element="digit">
416         <bounds x="131" y="85" width="10" height="15" />
417      </bezel>
418      <bezel name="digit7" element="digit">
419         <bounds x="141" y="85" width="10" height="15" />
420      </bezel>
264421
265
266      <bezel name="digit52" element="digit">
267         <bounds x="1.2" y="3.7" width="0.2" height="0.3" />
422      <bezel element="led_box" inputtag="IN0" inputmask="0x10">
423         <bounds x="162" y="80" width="30" height="25" />
268424      </bezel>
425      <bezel name="digit8" element="digit">
426         <bounds x="167" y="85" width="10" height="15" />
427      </bezel>
428      <bezel name="digit9" element="digit">
429         <bounds x="177" y="85" width="10" height="15" />
430      </bezel>
269431
270      <bezel name="digit53" element="digit">
271         <bounds x="1.4" y="3.7" width="0.2" height="0.3" />
432      <bezel element="led_box" inputtag="IN0" inputmask="0x20">
433         <bounds x="198" y="80" width="30" height="25" />
272434      </bezel>
435      <bezel name="digit10" element="digit">
436         <bounds x="203" y="85" width="10" height="15" />
437      </bezel>
438      <bezel name="digit11" element="digit">
439         <bounds x="213" y="85" width="10" height="15" />
440      </bezel>
273441
442<!-- row 2 -->
274443
275      <bezel name="digit54" element="digit">
276         <bounds x="1.8" y="3.7" width="0.2" height="0.3" />
444      <bezel element="led_box" inputtag="IN0" inputmask="0x40">
445         <bounds x="18" y="114" width="30" height="25" />
277446      </bezel>
447      <bezel name="digit12" element="digit">
448         <bounds x="23" y="119" width="10" height="15" />
449      </bezel>
450      <bezel name="digit13" element="digit">
451         <bounds x="33" y="119" width="10" height="15" />
452      </bezel>
278453
279      <bezel name="digit55" element="digit">
280         <bounds x="2.0" y="3.7" width="0.2" height="0.3" />
454      <bezel element="led_box" inputtag="IN0" inputmask="0x80">
455         <bounds x="54" y="114" width="30" height="25" />
281456      </bezel>
457      <bezel name="digit14" element="digit">
458         <bounds x="59" y="119" width="10" height="15" />
459      </bezel>
460      <bezel name="digit15" element="digit">
461         <bounds x="69" y="119" width="10" height="15" />
462      </bezel>
282463
283
284      <bezel name="digit56" element="digit">
285         <bounds x="2.4" y="3.7" width="0.2" height="0.3" />
464      <bezel element="led_box" inputtag="IN1" inputmask="0x01">
465         <bounds x="90" y="114" width="30" height="25" />
286466      </bezel>
467      <bezel name="digit16" element="digit">
468         <bounds x="95" y="119" width="10" height="15" />
469      </bezel>
470      <bezel name="digit17" element="digit">
471         <bounds x="105" y="119" width="10" height="15" />
472      </bezel>
287473
288      <bezel name="digit57" element="digit">
289         <bounds x="2.6" y="3.7" width="0.2" height="0.3" />
474      <bezel element="led_box" inputtag="IN1" inputmask="0x02">
475         <bounds x="126" y="114" width="30" height="25" />
290476      </bezel>
477      <bezel name="digit18" element="digit">
478         <bounds x="131" y="119" width="10" height="15" />
479      </bezel>
480      <bezel name="digit19" element="digit">
481         <bounds x="141" y="119" width="10" height="15" />
482      </bezel>
291483
292
293      <bezel name="digit58" element="digit">
294         <bounds x="3.0" y="3.7" width="0.2" height="0.3" />
484      <bezel element="led_box" inputtag="IN1" inputmask="0x04">
485         <bounds x="162" y="114" width="30" height="25" />
295486      </bezel>
487      <bezel name="digit20" element="digit">
488         <bounds x="167" y="119" width="10" height="15" />
489      </bezel>
490      <bezel name="digit21" element="digit">
491         <bounds x="177" y="119" width="10" height="15" />
492      </bezel>
296493
297      <bezel name="digit59" element="digit">
298         <bounds x="3.2" y="3.7" width="0.2" height="0.3" />
494      <bezel element="led_box" inputtag="IN1" inputmask="0x08">
495         <bounds x="198" y="114" width="30" height="25" />
299496      </bezel>
497      <bezel name="digit22" element="digit">
498         <bounds x="203" y="119" width="10" height="15" />
499      </bezel>
500      <bezel name="digit23" element="digit">
501         <bounds x="213" y="119" width="10" height="15" />
502      </bezel>
300503
504<!-- row 3 -->
301505
302<!-- time -->
303
304      <bezel name="digit60" element="digit">
305         <bounds x="0.0" y="0.9" width="0.2" height="0.2" />
506      <bezel element="led_box" inputtag="IN1" inputmask="0x10">
507         <bounds x="18" y="148" width="30" height="25" />
306508      </bezel>
509      <bezel name="digit24" element="digit">
510         <bounds x="23" y="153" width="10" height="15" />
511      </bezel>
512      <bezel name="digit25" element="digit">
513         <bounds x="33" y="153" width="10" height="15" />
514      </bezel>
307515
308      <bezel name="digit61" element="digit">
309         <bounds x="0.2" y="0.9" width="0.2" height="0.2" />
516      <bezel element="led_box" inputtag="IN1" inputmask="0x20">
517         <bounds x="54" y="148" width="30" height="25" />
310518      </bezel>
519      <bezel name="digit26" element="digit">
520         <bounds x="59" y="153" width="10" height="15" />
521      </bezel>
522      <bezel name="digit27" element="digit">
523         <bounds x="69" y="153" width="10" height="15" />
524      </bezel>
311525
312      <bezel name="digit62" element="digit">
313         <bounds x="0.4" y="0.9" width="0.2" height="0.2" />
526      <bezel element="led_box" inputtag="IN1" inputmask="0x40">
527         <bounds x="90" y="148" width="30" height="25" />
314528      </bezel>
529      <bezel name="digit28" element="digit">
530         <bounds x="95" y="153" width="10" height="15" />
531      </bezel>
532      <bezel name="digit29" element="digit">
533         <bounds x="105" y="153" width="10" height="15" />
534      </bezel>
315535
316      <bezel name="digit63" element="digit">
317         <bounds x="0.6" y="0.9" width="0.2" height="0.2" />
536      <bezel element="led_box" inputtag="IN1" inputmask="0x80">
537         <bounds x="126" y="148" width="30" height="25" />
318538      </bezel>
539      <bezel name="digit30" element="digit">
540         <bounds x="131" y="153" width="10" height="15" />
541      </bezel>
542      <bezel name="digit31" element="digit">
543         <bounds x="141" y="153" width="10" height="15" />
544      </bezel>
319545
320
321<!-- today's highscores -->
322
323      <bezel name="digit64" element="digit">
324         <bounds x="0.9" y="0.3" width="0.2" height="0.2" />
546      <bezel element="led_box" inputtag="IN2" inputmask="0x01">
547         <bounds x="162" y="148" width="30" height="25" />
325548      </bezel>
549      <bezel name="digit32" element="digit">
550         <bounds x="167" y="153" width="10" height="15" />
551      </bezel>
552      <bezel name="digit33" element="digit">
553         <bounds x="177" y="153" width="10" height="15" />
554      </bezel>
326555
327      <bezel name="digit65" element="digit">
328         <bounds x="1.1" y="0.3" width="0.2" height="0.2" />
556      <bezel element="led_box" inputtag="IN2" inputmask="0x02">
557         <bounds x="198" y="148" width="30" height="25" />
329558      </bezel>
559      <bezel name="digit34" element="digit">
560         <bounds x="203" y="153" width="10" height="15" />
561      </bezel>
562      <bezel name="digit35" element="digit">
563         <bounds x="213" y="153" width="10" height="15" />
564      </bezel>
330565
566<!-- row 4 -->
331567
332      <bezel name="digit66" element="digit">
333         <bounds x="0.9" y="0.6" width="0.2" height="0.2" />
568      <bezel element="led_box" inputtag="IN2" inputmask="0x04">
569         <bounds x="18" y="182" width="30" height="25" />
334570      </bezel>
571      <bezel name="digit36" element="digit">
572         <bounds x="23" y="187" width="10" height="15" />
573      </bezel>
574      <bezel name="digit37" element="digit">
575         <bounds x="33" y="187" width="10" height="15" />
576      </bezel>
335577
336      <bezel name="digit67" element="digit">
337         <bounds x="1.1" y="0.6" width="0.2" height="0.2" />
578      <bezel element="led_box" inputtag="IN2" inputmask="0x08">
579         <bounds x="54" y="182" width="30" height="25" />
338580      </bezel>
581      <bezel name="digit38" element="digit">
582         <bounds x="59" y="187" width="10" height="15" />
583      </bezel>
584      <bezel name="digit39" element="digit">
585         <bounds x="69" y="187" width="10" height="15" />
586      </bezel>
339587
340
341      <bezel name="digit68" element="digit">
342         <bounds x="0.9" y="0.9" width="0.2" height="0.2" />
588      <bezel element="led_box" inputtag="IN2" inputmask="0x10">
589         <bounds x="90" y="182" width="30" height="25" />
343590      </bezel>
591      <bezel name="digit40" element="digit">
592         <bounds x="95" y="187" width="10" height="15" />
593      </bezel>
594      <bezel name="digit41" element="digit">
595         <bounds x="105" y="187" width="10" height="15" />
596      </bezel>
344597
345      <bezel name="digit69" element="digit">
346         <bounds x="1.1" y="0.9" width="0.2" height="0.2" />
598      <bezel element="led_box" inputtag="IN2" inputmask="0x20">
599         <bounds x="126" y="182" width="30" height="25" />
347600      </bezel>
601      <bezel name="digit42" element="digit">
602         <bounds x="131" y="187" width="10" height="15" />
603      </bezel>
604      <bezel name="digit43" element="digit">
605         <bounds x="141" y="187" width="10" height="15" />
606      </bezel>
348607
349
350<!-- score -->
351
352      <bezel name="digit70" element="digit">
353         <bounds x="0.0" y="0.3" width="0.4" height="0.4" />
608      <bezel element="led_box" inputtag="IN2" inputmask="0x40">
609         <bounds x="162" y="182" width="30" height="25" />
354610      </bezel>
611      <bezel name="digit44" element="digit">
612         <bounds x="167" y="187" width="10" height="15" />
613      </bezel>
614      <bezel name="digit45" element="digit">
615         <bounds x="177" y="187" width="10" height="15" />
616      </bezel>
355617
356      <bezel name="digit71" element="digit">
357         <bounds x="0.4" y="0.3" width="0.4" height="0.4" />
618      <bezel element="led_box" inputtag="IN2" inputmask="0x80">
619         <bounds x="198" y="182" width="30" height="25" />
358620      </bezel>
621      <bezel name="digit46" element="digit">
622         <bounds x="203" y="187" width="10" height="15" />
623      </bezel>
624      <bezel name="digit47" element="digit">
625         <bounds x="213" y="187" width="10" height="15" />
626      </bezel>
359627
628<!-- row 5 -->
360629
361<!-- ranking -->
362
363      <bezel name="lamp0" element="rank">
364         <bounds x="1.5" y="0.3" width="0.1" height="0.1" />
630      <bezel element="led_box" inputtag="IN3" inputmask="0x01">
631         <bounds x="18" y="214" width="30" height="25" />
365632      </bezel>
366
367      <bezel name="lamp1" element="rank">
368         <bounds x="1.5" y="0.4" width="0.1" height="0.1" />
633      <bezel name="digit48" element="digit">
634         <bounds x="23" y="219" width="10" height="15" />
369635      </bezel>
636      <bezel name="digit49" element="digit">
637         <bounds x="33" y="219" width="10" height="15" />
638      </bezel>
370639
371      <bezel name="lamp2" element="rank">
372         <bounds x="1.5" y="0.5" width="0.1" height="0.1" />
640      <bezel element="led_box" inputtag="IN3" inputmask="0x02">
641         <bounds x="54" y="214" width="30" height="25" />
373642      </bezel>
643      <bezel name="digit50" element="digit">
644         <bounds x="59" y="219" width="10" height="15" />
645      </bezel>
646      <bezel name="digit51" element="digit">
647         <bounds x="69" y="219" width="10" height="15" />
648      </bezel>
374649
375      <bezel name="lamp3" element="rank">
376         <bounds x="1.5" y="0.6" width="0.1" height="0.1" />
650      <bezel element="led_box" inputtag="IN3" inputmask="0x04">
651         <bounds x="90" y="214" width="30" height="25" />
377652      </bezel>
653      <bezel name="digit52" element="digit">
654         <bounds x="95" y="219" width="10" height="15" />
655      </bezel>
656      <bezel name="digit53" element="digit">
657         <bounds x="105" y="219" width="10" height="15" />
658      </bezel>
378659
379      <bezel name="lamp4" element="rank">
380         <bounds x="1.5" y="0.7" width="0.1" height="0.1" />
660      <bezel element="led_box" inputtag="IN3" inputmask="0x08">
661         <bounds x="126" y="214" width="30" height="25" />
381662      </bezel>
663      <bezel name="digit54" element="digit">
664         <bounds x="131" y="219" width="10" height="15" />
665      </bezel>
666      <bezel name="digit55" element="digit">
667         <bounds x="141" y="219" width="10" height="15" />
668      </bezel>
382669
383      <bezel name="lamp5" element="rank">
384         <bounds x="1.5" y="0.8" width="0.1" height="0.1" />
670      <bezel element="led_box" inputtag="IN3" inputmask="0x10">
671         <bounds x="162" y="214" width="30" height="25" />
385672      </bezel>
673      <bezel name="digit56" element="digit">
674         <bounds x="167" y="219" width="10" height="15" />
675      </bezel>
676      <bezel name="digit57" element="digit">
677         <bounds x="177" y="219" width="10" height="15" />
678      </bezel>
386679
387      <bezel name="lamp6" element="rank">
388         <bounds x="1.5" y="0.9" width="0.1" height="0.1" />
680      <bezel element="led_box" inputtag="IN3" inputmask="0x20">
681         <bounds x="198" y="214" width="30" height="25" />
389682      </bezel>
683      <bezel name="digit58" element="digit">
684         <bounds x="203" y="219" width="10" height="15" />
685      </bezel>
686      <bezel name="digit59" element="digit">
687         <bounds x="213" y="219" width="10" height="15" />
688      </bezel>
390689
391690
392691   </view>
src/mame/layout/videopin.lay
r14439r14440
44         <color red="1.0" green="0.125" blue="0.125" />
55      </disk>
66   </element>
7   <view name="LEDs">
7   <view name="Simple LEDs">
88      <screen index="0">
99         <bounds x="0" y="0" width="300" height="400" />
1010      </screen>
src/mame/layout/kungfur.lay
r14439r14440
141141   </element>
142142
143143   <element name="text_1">
144      <text string="1ST">
144      <text string="1ST" align="2">
145145         <color red="1.0" green="1.0" blue="1.0" />
146146      </text>
147147   </element>
148148   <element name="text_2">
149      <text string="2ND">
149      <text string="2ND" align="2">
150150         <color red="1.0" green="1.0" blue="1.0" />
151151      </text>
152152   </element>
153153   <element name="text_3">
154      <text string="3RD">
154      <text string="3RD" align="2">
155155         <color red="1.0" green="1.0" blue="1.0" />
156156      </text>
157157   </element>
r14439r14440
169169
170170
171171
172   <view name="Simple LEDs">
172   <view name="Internal Layout">
173173      <bounds left="0" right="147" top="0" bottom="100" />
174174      <bezel element="static_green">
175175         <bounds left="0" right="147" top="0" bottom="100" />
r14439r14440
190190      </bezel>
191191
192192      <bezel element="text_1">
193         <bounds x="98.8" y="21" width="10" height="5" />
193         <bounds x="97.5" y="21" width="10" height="5" />
194194      </bezel>
195195      <bezel element="static_black">
196196         <bounds x="109" y="9" width="22" height="17" />
r14439r14440
204204      </bezel>
205205
206206      <bezel element="text_2">
207         <bounds x="99" y="46" width="10" height="5" />
207         <bounds x="97.5" y="46" width="10" height="5" />
208208      </bezel>
209209      <bezel element="static_black">
210210         <bounds x="109" y="34" width="22" height="17" />
r14439r14440
218218      </bezel>
219219
220220      <bezel element="text_3">
221         <bounds x="99" y="71" width="10" height="5" />
221         <bounds x="97.5" y="71" width="10" height="5" />
222222      </bezel>
223223      <bezel element="static_black">
224224         <bounds x="109" y="59" width="22" height="17" />
src/mame/drivers/30test.c
r14439r14440
55    driver by Angelo Salese
66
77    TODO:
8    - clickable artwork;
98    - portd meaning is a mystery
109    - inputs are annoying to map;
1110    - EEPROM
r14439r14440
6059};
6160
6261
63static READ8_HANDLER(hc11_mux_r)
64{
65   namco_30test_state *state = space->machine().driver_data<namco_30test_state>();
62static const UINT8 led_map[16] =
63   { 0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7c,0x07,0x7f,0x67,0x77,0x7c,0x39,0x5e,0x79,0x00 };
6664
67   return state->m_mux_data;
65static WRITE8_HANDLER( namco_30test_led_w )
66{
67   output_set_digit_value(0 + offset * 2, led_map[(data & 0xf0) >> 4]);
68   output_set_digit_value(1 + offset * 2, led_map[(data & 0x0f) >> 0]);
6869}
6970
70static WRITE8_HANDLER(hc11_mux_w)
71static WRITE8_HANDLER( namco_30test_led_rank_w )
7172{
72   namco_30test_state *state = space->machine().driver_data<namco_30test_state>();
73   output_set_digit_value(64 + offset * 2, led_map[(data & 0xf0) >> 4]);
74   output_set_digit_value(65 + offset * 2, led_map[(data & 0x0f) >> 0]);
75}
7376
74   state->m_mux_data = data;
77static WRITE8_HANDLER( namco_30test_lamps_w )
78{
79   // d0-d5: ranking, d6: game over, d7: assume marquee lamp
80   for (int i = 0; i < 8; i++)
81      output_set_lamp_value(i, data >> i & 1);
7582}
7683
7784static READ8_HANDLER(namco_30test_mux_r)
r14439r14440
9097   return res;
9198}
9299
93static const UINT8 led_map[16] =
94   { 0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7c,0x07,0x7f,0x67,0x77,0x7c,0x39,0x5e,0x79,0x00 };
95
96static WRITE8_HANDLER( namco_30test_led_w )
100static READ8_HANDLER(hc11_mux_r)
97101{
98   output_set_digit_value(0 + offset * 2, led_map[(data & 0xf0) >> 4]);
99   output_set_digit_value(1 + offset * 2, led_map[(data & 0x0f) >> 0]);
102   namco_30test_state *state = space->machine().driver_data<namco_30test_state>();
103   return state->m_mux_data;
100104}
101105
102static WRITE8_HANDLER( namco_30test_led_rank_w )
106static WRITE8_HANDLER(hc11_mux_w)
103107{
104   output_set_digit_value(64 + offset * 2, led_map[(data & 0xf0) >> 4]);
105   output_set_digit_value(65 + offset * 2, led_map[(data & 0x0f) >> 0]);
108   namco_30test_state *state = space->machine().driver_data<namco_30test_state>();
109   state->m_mux_data = data;
106110}
107111
108static WRITE8_HANDLER( namco_30test_lamps_w )
109{
110   if(!(data & 0x80)) // guess: lamps mask
111      data = 0;
112
113   output_set_lamp_value(0, (data & 0x01) >> 0); // really OK! lamp
114   output_set_lamp_value(1, (data & 0x02) >> 1); // pretty good lamp
115   output_set_lamp_value(2, (data & 0x04) >> 2); // not bad lamp
116   output_set_lamp_value(3, (data & 0x08) >> 3); // normal lamp
117   output_set_lamp_value(4, (data & 0x10) >> 4); // pretty bad lamp
118   output_set_lamp_value(5, (data & 0x20) >> 5); // worst lamp
119   output_set_lamp_value(6, (data & 0x40) >> 6); // game over lamp
120}
121
122112static READ8_DEVICE_HANDLER( hc11_okibank_r )
123113{
124114   namco_30test_state *state = device->machine().driver_data<namco_30test_state>();
r14439r14440
163153
164154
165155static INPUT_PORTS_START( 30test )
166   /* we use num pad to map system inputs */
167156   PORT_START("IN0")
168   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("1-1") PORT_CODE(KEYCODE_1)
169   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("2-1") PORT_CODE(KEYCODE_2)
170   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("3-1") PORT_CODE(KEYCODE_3)
171   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("4-1") PORT_CODE(KEYCODE_4)
172   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("5-1") PORT_CODE(KEYCODE_5)
173   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("6-1") PORT_CODE(KEYCODE_6)
174   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("1-2") PORT_CODE(KEYCODE_Q)
175   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("2-2") PORT_CODE(KEYCODE_W)
157   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 1-1") PORT_CODE(KEYCODE_1)
158   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 1-2") PORT_CODE(KEYCODE_2)
159   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 1-3") PORT_CODE(KEYCODE_3)
160   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 1-4") PORT_CODE(KEYCODE_4)
161   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 1-5") PORT_CODE(KEYCODE_5)
162   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 1-6") PORT_CODE(KEYCODE_6)
163   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 2-1") PORT_CODE(KEYCODE_Q)
164   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 2-2") PORT_CODE(KEYCODE_W)
176165
177166   PORT_START("IN1")
178   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("3-2") PORT_CODE(KEYCODE_E)
179   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("4-2") PORT_CODE(KEYCODE_R)
180   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("5-2") PORT_CODE(KEYCODE_T)
181   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("6-2") PORT_CODE(KEYCODE_Y)
182   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("1-3") PORT_CODE(KEYCODE_A)
183   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("2-3") PORT_CODE(KEYCODE_S)
184   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("3-3") PORT_CODE(KEYCODE_D)
185   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("4-3") PORT_CODE(KEYCODE_F)
167   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 2-3") PORT_CODE(KEYCODE_E)
168   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 2-4") PORT_CODE(KEYCODE_R)
169   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 2-5") PORT_CODE(KEYCODE_T)
170   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 2-6") PORT_CODE(KEYCODE_Y)
171   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 3-1") PORT_CODE(KEYCODE_A)
172   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 3-2") PORT_CODE(KEYCODE_S)
173   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 3-3") PORT_CODE(KEYCODE_D)
174   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 3-4") PORT_CODE(KEYCODE_F)
186175
187176   PORT_START("IN2")
188   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("5-3") PORT_CODE(KEYCODE_G)
189   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("6-3") PORT_CODE(KEYCODE_H)
190   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("1-4") PORT_CODE(KEYCODE_Z)
191   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("2-4") PORT_CODE(KEYCODE_X)
192   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("3-4") PORT_CODE(KEYCODE_C)
193   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("4-4") PORT_CODE(KEYCODE_V)
194   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("5-4") PORT_CODE(KEYCODE_B)
195   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("6-4") PORT_CODE(KEYCODE_N)
177   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 3-5") PORT_CODE(KEYCODE_G)
178   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 3-6") PORT_CODE(KEYCODE_H)
179   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 4-1") PORT_CODE(KEYCODE_Z)
180   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 4-2") PORT_CODE(KEYCODE_X)
181   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 4-3") PORT_CODE(KEYCODE_C)
182   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 4-4") PORT_CODE(KEYCODE_V)
183   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 4-5") PORT_CODE(KEYCODE_B)
184   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 4-6") PORT_CODE(KEYCODE_N)
196185
197186   PORT_START("IN3")
198   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("1-5") PORT_CODE(KEYCODE_LSHIFT)
199   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("2-5") PORT_CODE(KEYCODE_LCONTROL)
200   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("3-5") PORT_CODE(KEYCODE_LALT)
201   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("4-5") PORT_CODE(KEYCODE_SPACE)
202   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("5-5") PORT_CODE(KEYCODE_RALT)
203   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("6-5") PORT_CODE(KEYCODE_RCONTROL)
204   PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) )
205   PORT_DIPSETTING(    0x40, DEF_STR( Off ) )
206   PORT_DIPSETTING(    0x00, DEF_STR( On ) )
207   PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) )
208   PORT_DIPSETTING(    0x80, DEF_STR( Off ) )
209   PORT_DIPSETTING(    0x00, DEF_STR( On ) )
187   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 5-1") PORT_CODE(KEYCODE_LSHIFT)
188   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 5-2") PORT_CODE(KEYCODE_LCONTROL)
189   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 5-3") PORT_CODE(KEYCODE_LALT)
190   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 5-4") PORT_CODE(KEYCODE_SPACE)
191   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 5-5") PORT_CODE(KEYCODE_RALT)
192   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_OTHER ) PORT_NAME("Button 5-6") PORT_CODE(KEYCODE_RCONTROL)
193   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
194   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
210195
211196   PORT_START("SYSTEM")
212   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_SERVICE )
213   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_CODE(KEYCODE_5_PAD)
214   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_CODE(KEYCODE_6_PAD)
215   PORT_DIPNAME( 0x08, 0x08, "SYSTEM" )
197   PORT_SERVICE( 0x01, IP_ACTIVE_LOW )
198   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_CODE(KEYCODE_7)
199   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_CODE(KEYCODE_8)
200   PORT_DIPNAME( 0x08, 0x08, "UNK3" )
216201   PORT_DIPSETTING(    0x08, DEF_STR( Off ) )
217202   PORT_DIPSETTING(    0x00, DEF_STR( On ) )
218   PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) )
203   PORT_DIPNAME( 0x10, 0x10, "UNK4" )
219204   PORT_DIPSETTING(    0x10, DEF_STR( Off ) )
220205   PORT_DIPSETTING(    0x00, DEF_STR( On ) )
221   PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) )
206   PORT_DIPNAME( 0x20, 0x20, "UNK5" )
222207   PORT_DIPSETTING(    0x20, DEF_STR( Off ) )
223208   PORT_DIPSETTING(    0x00, DEF_STR( On ) )
224   PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) )
209   PORT_DIPNAME( 0x40, 0x40, "UNK6" )
225210   PORT_DIPSETTING(    0x40, DEF_STR( Off ) )
226211   PORT_DIPSETTING(    0x00, DEF_STR( On ) )
227   PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) )
212   PORT_DIPNAME( 0x80, 0x80, "UNK7" )
228213   PORT_DIPSETTING(    0x80, DEF_STR( Off ) )
229214   PORT_DIPSETTING(    0x00, DEF_STR( On ) )
230215INPUT_PORTS_END
r14439r14440
267252   /* sound hardware */
268253   MCFG_SPEAKER_STANDARD_MONO("mono")
269254
270   MCFG_OKIM6295_ADD("oki", 1056000, OKIM6295_PIN7_HIGH) // pin 7 not verified
255   MCFG_OKIM6295_ADD("oki", 1056000, OKIM6295_PIN7_HIGH)
271256   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0)
272257MACHINE_CONFIG_END
273258
src/mame/drivers/pacman.c
r14439r14440
45474547ROM_END
45484548
45494549
4550ROM_START( eyesb )
4551   ROM_REGION( 0x10000, "maincpu", 0 )
4552   ROM_LOAD( "1.bin",           0x0000, 0x0800, CRC(339d279a) SHA1(bc2a7801b9f94782f260346255f84a0e84729f01) )
4553   ROM_LOAD( "5.bin",           0x0800, 0x0800, CRC(1b68a61d) SHA1(348ef7b19934b000b03c74bec4796f1089dfc5eb) )
4554   ROM_LOAD( "2.bin",           0x1000, 0x0800, CRC(d4f9aaf8) SHA1(1e450a7ecf42f9bc2d58823907930dd7aa454215) )
4555   ROM_LOAD( "6.bin",           0x1800, 0x0800, CRC(6b41bb80) SHA1(aa3555833a2e8e596e126a749fe12853e4aa05b1) )
4556   ROM_LOAD( "3.bin",           0x2000, 0x0800, CRC(748e0e48) SHA1(857de6f7fe79a2613a93fb3efd981edb64c0190e) )
4557   ROM_LOAD( "7.bin",           0x2800, 0x0800, CRC(7b7f4a74) SHA1(373229de4ed25d577fe15deb3b6bc36786988284) )
4558   ROM_LOAD( "4.bin",           0x3000, 0x0800, CRC(367a3884) SHA1(d55d7eca56412661adac1849a398298670e86d15) )
4559   ROM_LOAD( "8.bin",           0x3800, 0x0800, CRC(2baaadae) SHA1(7b20ed5935e9a4f793f690bab2a6bc0db44d12af) )
4560
4561   ROM_REGION( 0x2000, "gfx1", 0 )
4562   ROM_LOAD( "9.bin",           0x0000, 0x0800, CRC(342c0653) SHA1(d07e3d4528b72e54a1b5dbed009cce765a5a086f) )
4563   ROM_LOAD( "11.bin",          0x0800, 0x0800, CRC(aaa7a537) SHA1(571d981ed2aad62d7c7f2798e9084228d45523d4) )
4564   ROM_LOAD( "10.bin",          0x1000, 0x0800, CRC(b247b82c) SHA1(8c10a8ef5e79b0b5fefad6eb77bfa68a0ca18035) )
4565   ROM_LOAD( "12.bin",          0x1800, 0x0800, CRC(99af4b30) SHA1(6a0939ff2fa7ae39a960dd4d9f9b7c01f57647c5) )
4566
4567   ROM_REGION( 0x0120, "proms", 0 )
4568   ROM_LOAD( "7051.bin",        0x0000, 0x0020, CRC(0dad2ccb) SHA1(f42c5ee7084e5702b5b0c8c1d86b0a41a6e1821d) )
4569   ROM_LOAD( "7051-3.bin",      0x0020, 0x0100, CRC(d8d78829) SHA1(19820d1651423210083a087fb70ebea73ad34951) )
4570
4571   ROM_REGION( 0x0200, "namco", 0 )   /* sound PROMs */
4572   ROM_LOAD( "82s126.1m",       0x0000, 0x0100, CRC(a9cc86bf) SHA1(bbcec0570aeceb582ff8238a4bc8546a23430081) )   // not dumped, taken from parent
4573   ROM_LOAD( "7051-2.bin",      0x0100, 0x0100, CRC(77245b66) SHA1(0c4d0bee858b97632411c440bea6948a74759746) )   // two of these?
4574ROM_END
4575
4576
45504577ROM_START( eyeszac )
45514578   ROM_REGION( 0x10000, "maincpu", 0 )
45524579   ROM_LOAD( "1.7d",         0x0000, 0x1000, BAD_DUMP CRC(568851aa) SHA1(a97963556a6d77400afaafd73bcc32cb7f3a54d2) ) // 2532 vs 2732 problem, (near)identical halves
r14439r14440
58985925GAME( 1982, ctrpllrp, puckman,  pacman,   pacman,   0,        ROT90,  "hack", "Caterpillar Pacman Hack", GAME_SUPPORTS_SAVE )
58995926GAME( 1982, eyes,     0,        pacman,   eyes,     eyes,     ROT90,  "Digitrex Techstar (Rock-Ola license)", "Eyes (US set 1)", GAME_SUPPORTS_SAVE )
59005927GAME( 1982, eyes2,    eyes,     pacman,   eyes,     eyes,     ROT90,  "Techstar (Rock-Ola license)", "Eyes (US set 2)", GAME_SUPPORTS_SAVE )
5928GAME( 1982, eyesb,    eyes,     pacman,   eyes,     eyes,     ROT90,  "bootleg", "Eyes (bootleg set 1)", GAME_SUPPORTS_SAVE )
59015929GAME( 1982, eyeszac,  eyes,     pacman,   eyes,     eyes,     ROT90,  "Techstar (Zaccaria license)", "Eyes (Italy)", GAME_SUPPORTS_SAVE | GAME_NOT_WORKING ) // bad dump
5902GAME( 1982, eyeszacb, eyes,     pacman,   eyes,     0,        ROT90,  "bootleg", "Eyes (bootleg)", GAME_SUPPORTS_SAVE ) // based on Zaccaria version
5930GAME( 1982, eyeszacb, eyes,     pacman,   eyes,     0,        ROT90,  "bootleg", "Eyes (bootleg set 2, decrypted)", GAME_SUPPORTS_SAVE ) // based on Zaccaria version
59035931GAME( 1983, birdiy,   0,        birdiy,   pacman,   0,        ROT270, "Mama Top", "Birdiy", GAME_SUPPORTS_SAVE )
59045932GAME( 1983, mrtnt,    0,        pacman,   mrtnt,    eyes,     ROT90,  "Techstar (Telko license)", "Mr. TNT", GAME_SUPPORTS_SAVE )
59055933GAME( 1983, gorkans,  mrtnt,    pacman,   mrtnt,    0,        ROT90,  "Techstar", "Gorkans", GAME_SUPPORTS_SAVE )
src/osd/sdl/README_SDL20.txt
r0r14440
1======================================================================================
2SDLMAME now supports SDL from version 2.0 on upwards.
3=======================================================================================
4 
5 
6Warning
7=======
8 
9- SDL2.0 still is still under development, the following may or may not
10  work.
11- if you are using wine on unix be sure to disable wintab32.dll
12 
13Known bugs:
14===========
15 
16* SDL1.3/X11: Some compound keys, e.g. "'" are not supported by SDL driver
17* SDL2.0: sdlvideofps does not take -numscreens>1 into account.
18* SDL1.3/WIN32: crashes with -rd d3d
19* SDL1.3/WIN32: resizing does not work
20       
21Build SDL 2.0 from HG
22======================
23 
24Pull 2.0 from hg. Than 
25 
26sh autogen.sh
27./configure --prefix=/usr/local/sdl13/ --disable-video-svga --enable-video-directfb --enable-fusionsound
28make 
29[sudo] make install
30 
31You may leave away the last two enables, if you do not want to play around with directfb - although it is lightning fast now :-)
32 
33To build the files in test, do
34 
35cd test
36./configure --prefix=/usr/local/sdl13/ --with-sdl-pfx=/usr/local/sdl13
37make
38 
39Replace /usr/local/sdl13 above with a safe location, this may as well be a directory in $HOME.
40 
41Edit sdl.mak to have
42 
43SDL_LIBVER = sdl2
44SDL_INSTALL_ROOT = /usr/local/sdl13
45 
46That's it.
47 
48make
49./mame -video sdl13 -rd opengl dkong
50 
51 
52All drivers
53===========
54 
55should support:
56 
57-waitvsync
58-prescale
59-resolution[X]
60-switchres
61-numscreens
62-screen[X]
63 
64The following modes are working:
65 
66SDL13
67=====
68 
69This is driver using SDL texture and line drawing support. It supports 
70-prescale, -filter and -waitvsync.  The driver determines which pixel 
71formats perform best and converts textures to these pixel formats and at 
72the same time performs any necessary rotation.   
73 
74Basic usage examples:
75 
76X11/opengl: ./mamed -video sdl13 -rd opengl mario 
77DFB/DFB:    ./mamed -video sdl13 -vd directfb -rd directfb mario 
78 
79The performance of the directfb driver depends on the combined
80support of the kernel framebuffer driver and the directfb driver.
81Having loaded radeonfb I get the same performance as with the open source
82radeon X11 driver.
83 
84Using the SDL software renderer (preferred is -video soft, thought)
85 
86X11,DFB,WIN32 ./mamed -video sdl13 -rd software
87 
88Soft:
89=====
90 
91./mamed -mt -video soft  -sm none -numscreens 2 mario
92 
93OpenGL:
94=======
95 
96Plain opengl does work. Anything more advanced like pbo, fbo or glsl will 
97most probably not work with more than one screen.
98 
99   ./mamed -mt -video opengl mario -nogl_pbo -nogl_vbo -nogl_glsl -numscreens 2
100 
101YUV - modes:
102============
103 
104   ./mamed -mt -video soft -sm yuy2 mario
105 
106Using DirectFB, the following should get you going
107 
108   ./mamed -mt -video soft -sm yuy2 -vd directfb -rd directfb mario
109   
110for accelerated blitting on the framebuffer - provided directfb supports it. 
111At least my Radeon R480 is supported.
112 
113-video soft and -scale_mode (-sm)
114=================================
115 
116sdlmame supports 7 scale modes using textures in -video soft:
117 
118none: All rendering/scaling in software.
119 
120hwblit: Rendering in software/scaling with hardware (if supported)
121 
122hwbest: Rendering in software/antialiased scaling with hardware (if supported)
123 
124yv12, yv12x2, yuy2, yuy2x2: 
125Rendering in software / scaling with hardware (if supported)
126 
127Whether these are actually hardware accelerated depends on the SDL driver
128and the hardware. The SDL directfb driver supports all above if the hardware 
129supports it. However, only one YUV-texture per display is supported. 
130The second window consequently will get "software" YUV blitting.
131 
132     
src/osd/sdl/sdlos_macosx.c
r14439r14440
1010//============================================================
1111
1212// standard sdl header
13#include <SDL/SDL.h>
13#include "sdlinc.h"
1414
1515#include <sys/stat.h>
1616#include <unistd.h>
src/osd/sdl/sdlos_win32.c
r14439r14440
1010//============================================================
1111
1212// standard sdl header
13#include <SDL/SDL.h>
13#include "sdlinc.h"
1414
1515
1616#define WIN32_LEAN_AND_MEAN
src/osd/sdl/sdlos_os2.c
r14439r14440
1010//============================================================
1111
1212// standard sdl header
13#include <SDL/SDL.h>
13#include "sdlinc.h"
1414#include <unistd.h>
1515#include <stdio.h>
1616#include <string.h>
src/osd/sdl/sdl.mak
r14439r14440
2121# for details
2222#-------------------------------------------------
2323
24
2524# uncomment and edit next line to specify a distribution
2625# supported debian-stable, ubuntu-intrepid
2726
r14439r14440
4847
4948USE_DISPATCH_GL = 1
5049
51# uncomment and change the next line to compile and link to specific
52# SDL library. This is currently supported for unix and win32.
50# The following settings are currently supported for unix only.
5351# There is no need to play with this option unless you are doing
5452# active development on sdlmame or SDL.
5553
56ifeq ($(TARGETOS),win32)
57#SDL_INSTALL_ROOT = /usr/local/sdl13w32
58else
59#SDL_INSTALL_ROOT = /usr/local/sdl13
60#SDL_INSTALL_ROOT = /usr/local/test
61endif
54# uncomment the next line to compile and link against SDL2.0
6255
56# SDL_LIBVER = sdl2
57
58# uncomment the next line to use couriersud's multi-keyboard patch for sdl2.0
59# SDL2_MULTIAPI = 1
60
61# uncomment the next line to specify where you have installed
62# SDL. Equivalent to the ./configure --prefix=<path>
63# SDL_INSTALL_ROOT = /usr/local/sdl13
64
6365# uncomment and change the next line to build the gtk debugger for win32
6466# Get what you need here: http://www.gtk.org/download-windows.html
6567# GTK_INSTALL_ROOT = y:/couriersud/win/gtk-32
r14439r14440
7072##################   END USER-CONFIGURABLE OPTIONS   ######################
7173###########################################################################
7274
75ifndef SDL_LIBVER
76SDL_LIBVER = sdl
77endif
78
79ifdef SDL_INSTALL_ROOT
80SDL_CONFIG = $(SDL_INSTALL_ROOT)/bin/$(SDL_LIBVER)-config
81else
82SDL_CONFIG = $(SDL_LIBVER)-config
83endif
84
85ifeq ($(SDL_LIBVER),sdl2)
86DEFS += -DSDLMAME_SDL2=1
87   ifeq ($(SDL2_MULTIAPI),1)
88   DEFS += -DSDL2_MULTIAPI
89   endif
90else
91DEFS += -DSDLMAME_SDL2=0
92endif
93
7394ifdef NOASM
7495DEFS += -DSDLMAME_NOASM
7596endif
r14439r14440
288309   $(SDLOBJ)/output.o \
289310   $(SDLOBJ)/watchdog.o
290311
291# Add SDL1.3 support
292ifdef SDL_INSTALL_ROOT
312# Add SDL2.0 support
313
314ifeq ($(SDL_LIBVER),sdl2)
293315OSDOBJS += $(SDLOBJ)/draw13.o
294316endif
295317
r14439r14440
350372endif
351373endif
352374
353ifndef SDL_INSTALL_ROOT
354INCPATH += `sdl-config --cflags  | sed -e 's:/SDL::' -e 's:\(-D[^ ]*\)::g'`
355CCOMFLAGS += `sdl-config --cflags  | sed -e 's:/SDL::' -e 's:\(-I[^ ]*\)::g'`
356LIBS += -lm `sdl-config --libs`
357375
358else
359# The commented out statements document what sdl-config returns when build from svn.
360# sdl-config --libs on ubuntu returns "-L/usr/lib -lSDL" which is not what we really
361# want in a multi-version SDL environment. Should the svn sdl-config at some point
362# return the same output, we need the commented out section again.
376INCPATH += `$(SDL_CONFIG) --cflags  | sed -e 's:/SDL[2]*::' -e 's:\(-D[^ ]*\)::g'`
377CCOMFLAGS += `$(SDL_CONFIG) --cflags  | sed -e 's:/SDL[2]*::' -e 's:\(-I[^ ]*\)::g'`
378LIBS += -lm `$(SDL_CONFIG) --libs`
363379
364#INCPATH += -I$(SDL_INSTALL_ROOT)/include
365#CCOMFLAGS += -D_GNU_SOURCE=1
366#LIBS += -lm -L$(SDL_INSTALL_ROOT)/lib -Wl,-rpath,$(SDL_INSTALL_ROOT)/lib -lSDL
367
368# FIXME: remove the directfb ref. later. This is just there for now to work around an issue with SDL1.3.
380ifeq ($(SDL_LIBVER),sdl2)
381ifdef SDL_INSTALL_ROOT
382# FIXME: remove the directfb ref. later. This is just there for now to work around an issue with SDL1.3 and SDL2.0
369383INCPATH += -I$(SDL_INSTALL_ROOT)/include/directfb
370INCPATH += `$(SDL_INSTALL_ROOT)/bin/sdl-config --cflags  | sed -e 's:/SDL::' -e 's:\(-D[^ ]*\)::g'`
371CCOMFLAGS += `$(SDL_INSTALL_ROOT)/bin/sdl-config --cflags  | sed -e 's:/SDL::' -e 's:\(-I[^ ]*\)::g'`
372LIBS += -lm `$(SDL_INSTALL_ROOT)/bin/sdl-config --libs`
373384endif
385endif
374386
375387INCPATH += `pkg-config --cflags fontconfig`
376388LIBS += `pkg-config --libs fontconfig`
389
390ifeq ($(SDL_LIBVER),sdl2)
391LIBS += -lSDL2_ttf -lutil
392else
377393LIBS += -lSDL_ttf -lutil
394endif
378395
396
379397endif # Unix
380398
381399#-------------------------------------------------
r14439r14440
591609#-------------------------------------------------
592610
593611testlib:
594   -echo LIBS: $(LIBS)
595   -echo DEFS: $(DEFS)
596   -echo CORE: $(OSDCOREOBJS)
612   @echo LIBS: $(LIBS)
613   @echo INCPATH: $(INCPATH)
614   @echo DEFS: $(DEFS)
615   @echo CORE: $(OSDCOREOBJS)
597616
598617ifneq ($(TARGETOS),win32)
599618BUILD_VERSION = $(shell grep 'build_version\[\] =' src/version.c | sed -e "s/.*= \"//g" -e "s/ .*//g")
src/osd/sdl/sdlos_unix.c
r14439r14440
1616#include <sys/time.h>
1717#include <sys/stat.h>
1818
19#include <SDL/SDL.h>
20#include <SDL/SDL_syswm.h>
19#include "sdlinc.h"
2120
2221// MAME headers
2322#include "osdcore.h"
r14439r14440
138137   return setenv(name, value, overwrite);
139138}
140139
141#if defined(SDL_VIDEO_DRIVER_X11) && defined(SDLMAME_X11)
140#if (SDLMAME_SDL2)
142141
143142//============================================================
144143//  osd_get_clipboard_text
r14439r14440
146145
147146char *osd_get_clipboard_text(void)
148147{
148   char *result = NULL;
149
150   if (SDL_HasClipboardText())
151   {
152      char *temp = SDL_GetClipboardText();
153      result = (char *) osd_malloc_array(strlen(temp) + 1);
154      strcpy(result, temp);
155      SDL_free(temp);
156   }
157   return result;
158}
159
160#elif defined(SDL_VIDEO_DRIVER_X11) && defined(SDLMAME_X11)
161
162//============================================================
163//  osd_get_clipboard_text
164//============================================================
165
166char *osd_get_clipboard_text(void)
167{
149168   SDL_SysWMinfo info;
150169   Display* display;
151170   Window our_win;
r14439r14440
167186      return NULL;
168187   if ( info.subsystem != SDL_SYSWM_X11 )
169188      return NULL;
170#if (SDL_VERSION_ATLEAST(1,3,0))
171189   if ( (display = info.info.x11.display) == NULL )
172190      return NULL;
173191   if ( (our_win = info.info.x11.window) == None )
174192      return NULL;
175#else
176   if ( (display = info.info.x11.display) == NULL )
177      return NULL;
178   if ( (our_win = info.info.x11.window) == None )
179      return NULL;
180#endif
193
181194   /* request data to owner */
182195   selection_win = XGetSelectionOwner( display, XA_PRIMARY );
183196   if ( selection_win == None )
src/osd/sdl/drawsdl.c
r14439r14440
1818#include "ui.h"
1919
2020// standard SDL headers
21#include <SDL/SDL.h>
21#include "sdlinc.h"
2222
2323// OSD headers
2424#include "osdsdl.h"
r14439r14440
3838
3939typedef struct _sdl_scale_mode sdl_scale_mode;
4040
41// FIXME: Only until there is a final decision from SAM on scalemodes
42#if (SDL_VERSION_ATLEAST(1,3,0))
43#define   SDL_SCALEMODE_NONE   (0)
44#define   SDL_SCALEMODE_FAST   (0)
45#define   SDL_SCALEMODE_BEST   (0)
41#if (SDLMAME_SDL2)
42#define   DRAW2_SCALEMODE_NEAREST   "0"
43#define   DRAW2_SCALEMODE_LINEAR   "1"
44#define   DRAW2_SCALEMODE_BEST   "2"
4645#endif
4746
4847/* sdl_info is the information about SDL for the current screen */
r14439r14440
5251   INT32            blittimer;
5352   UINT32            extra_flags;
5453
55#if (SDL_VERSION_ATLEAST(1,3,0))
54#if (SDLMAME_SDL2)
55   SDL_Renderer      *sdl_renderer;
5656   SDL_Texture         *texture_id;
5757#else
5858   // SDL surface
r14439r14440
7373   int               last_vofs;
7474   int               old_blitwidth;
7575   int               old_blitheight;
76
77   // shortcut to scale mode info
78
79   const sdl_scale_mode      *scale_mode;
8076};
8177
8278struct _sdl_scale_mode
r14439r14440
8682   int            is_yuv;            /* Yuv mode?             */
8783   int            mult_w;            /* Width multiplier      */
8884   int            mult_h;            /* Height multiplier     */
89#if (!SDL_VERSION_ATLEAST(1,3,0))
85#if (!SDLMAME_SDL2)
9086   int            extra_flags;      /* Texture/surface flags */
9187#else
92   //SDL_ScaleMode sdl_scale_mode;     /* sdl 1.3 scale mode    */
93   int            sdl_scale_mode;      /* got removed recently - trying to get it in again */
88   const char      *sdl_scale_mode;      /* what to use as a hint ? */
9489#endif
9590   int            pixel_format;      /* Pixel/Overlay format  */
9691   void          (*yuv_blit)(UINT16 *bitmap, sdl_info *sdl, UINT8 *ptr, int pitch);
r14439r14440
116111static void drawsdl_window_clear(sdl_window_info *window);
117112static int drawsdl_xy_to_render_target(sdl_window_info *window, int x, int y, int *xt, int *yt);
118113
119#if (SDL_VERSION_ATLEAST(1,3,0))
114#if (SDLMAME_SDL2)
120115static void setup_texture(sdl_window_info *window, int tempwidth, int tempheight);
121116#endif
122117
r14439r14440
137132
138133// Static declarations
139134
140#if (!SDL_VERSION_ATLEAST(1,3,0))
135#if (!SDLMAME_SDL2)
141136static int shown_video_info = 0;
142137
143138static const sdl_scale_mode scale_modes[] =
r14439r14440
153148#else
154149static const sdl_scale_mode scale_modes[] =
155150{
156      { "none",    0, 0, 0, 0, SDL_SCALEMODE_NONE, 0, 0 },
157      { "hwblit",  1, 0, 1, 1, SDL_SCALEMODE_FAST, 0, 0 },
158      { "hwbest",  1, 0, 1, 1, SDL_SCALEMODE_BEST, 0, 0 },
159      { "yv12",    1, 1, 1, 1, SDL_SCALEMODE_NONE, SDL_PIXELFORMAT_YV12, yuv_RGB_to_YV12 },
160      { "yv12x2",  1, 1, 2, 2, SDL_SCALEMODE_NONE, SDL_PIXELFORMAT_YV12, yuv_RGB_to_YV12X2 },
161      { "yuy2",    1, 1, 1, 1, SDL_SCALEMODE_NONE, SDL_PIXELFORMAT_YUY2, yuv_RGB_to_YUY2 },
162      { "yuy2x2",  1, 1, 2, 1, SDL_SCALEMODE_NONE, SDL_PIXELFORMAT_YUY2, yuv_RGB_to_YUY2X2 },
151      { "none",    0, 0, 0, 0, DRAW2_SCALEMODE_NEAREST, 0, 0 },
152      { "hwblit",  1, 0, 1, 1, DRAW2_SCALEMODE_LINEAR, 0, 0 },
153      { "hwbest",  1, 0, 1, 1, DRAW2_SCALEMODE_BEST, 0, 0 },
154      { "yv12",    1, 1, 1, 1, DRAW2_SCALEMODE_NEAREST, SDL_PIXELFORMAT_YV12, yuv_RGB_to_YV12 },
155      { "yv12x2",  1, 1, 2, 2, DRAW2_SCALEMODE_NEAREST, SDL_PIXELFORMAT_YV12, yuv_RGB_to_YV12X2 },
156      { "yuy2",    1, 1, 1, 1, DRAW2_SCALEMODE_NEAREST, SDL_PIXELFORMAT_YUY2, yuv_RGB_to_YUY2 },
157      { "yuy2x2",  1, 1, 2, 1, DRAW2_SCALEMODE_NEAREST, SDL_PIXELFORMAT_YUY2, yuv_RGB_to_YUY2X2 },
163158      { NULL }
164159};
165160#endif
r14439r14440
208203   callbacks->exit = drawsdl_exit;
209204   callbacks->attach = drawsdl_attach;
210205
211   if (SDL_VERSION_ATLEAST(1,3,0))
212      mame_printf_verbose("Using SDL multi-window soft driver (SDL 1.3+)\n");
206   if (SDLMAME_SDL2)
207      mame_printf_verbose("Using SDL multi-window soft driver (SDL 2.0+)\n");
213208   else
214209      mame_printf_verbose("Using SDL single-window soft driver (SDL 1.2)\n");
215210
r14439r14440
254249//  setup_texture for window
255250//============================================================
256251
257#if (SDL_VERSION_ATLEAST(1,3,0))
252#if (SDLMAME_SDL2)
258253static void setup_texture(sdl_window_info *window, int tempwidth, int tempheight)
259254{
260255   sdl_info *sdl = (sdl_info *) window->dxdata;
261   const sdl_scale_mode *sdl_sm = sdl->scale_mode;
256   const sdl_scale_mode *sdl_sm = &scale_modes[video_config.scale_mode];
262257   SDL_DisplayMode mode;
263258   UINT32 fmt;
264259
r14439r14440
278273      {
279274         sdl->hw_scale_width *= video_config.prescale;
280275         sdl->hw_scale_height *= video_config.prescale;
276
277         /* This must be a multiple of 2 */
278         sdl->hw_scale_width = (sdl->hw_scale_width + 1) & ~1;
281279      }
282280   }
283281
r14439r14440
291289      int w = sdl->hw_scale_width * sdl_sm->mult_w;
292290      int h = sdl->hw_scale_height * sdl_sm->mult_h;
293291
294      sdl->texture_id = SDL_CreateTexture(window->sdl_renderer, fmt, SDL_TEXTUREACCESS_STREAMING, w, h);
292      sdl->texture_id = SDL_CreateTexture(sdl->sdl_renderer, fmt, SDL_TEXTUREACCESS_STREAMING, w, h);
295293
296294   }
297295   else
298296   {
299      sdl->texture_id = SDL_CreateTexture(window->sdl_renderer,fmt, SDL_TEXTUREACCESS_STREAMING,
297      sdl->texture_id = SDL_CreateTexture(sdl->sdl_renderer,fmt, SDL_TEXTUREACCESS_STREAMING,
300298            tempwidth, tempheight);
301299   }
302
303   //SDL_SetTextureScaleMode(window->sdl_renderer,sdl->texture_id, sdl_sm->sdl_scale_mode);
304
305300}
306301#endif
307302
r14439r14440
309304//  yuv_overlay_init
310305//============================================================
311306
312#if (!SDL_VERSION_ATLEAST(1,3,0))
307#if (!SDLMAME_SDL2)
313308static void yuv_overlay_init(sdl_window_info *window)
314309{
315310   sdl_info *sdl = (sdl_info *) window->dxdata;
316   const sdl_scale_mode *sdl_sm = sdl->scale_mode;
311   const sdl_scale_mode *sdl_sm = &scale_modes[video_config.scale_mode];
317312   int minimum_width, minimum_height;
318313
319314   window->target->compute_minimum_size(minimum_width, minimum_height);
r14439r14440
364359//  drawsdl_show_info
365360//============================================================
366361
367#if (SDL_VERSION_ATLEAST(1,3,0))
362#if (SDLMAME_SDL2)
368363static void   drawsdl_show_info(sdl_window_info *window, struct SDL_RendererInfo *render_info)
369364{
370365#define RF_ENTRY(x) {x, #x }
r14439r14440
400395static int drawsdl_window_create(sdl_window_info *window, int width, int height)
401396{
402397   sdl_info *sdl;
398    const sdl_scale_mode *sm = &scale_modes[video_config.scale_mode];
403399
404400   // allocate memory for our structures
405401   sdl = (sdl_info *) osd_malloc(sizeof(sdl_info));
r14439r14440
407403
408404   window->dxdata = sdl;
409405
410   sdl->scale_mode = &scale_modes[window->scale_mode];
406#if (SDLMAME_SDL2)
411407
412#if (SDL_VERSION_ATLEAST(1,3,0))
408   /* set hints ... */
409
410   SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, sm->sdl_scale_mode);
411
413412   sdl->extra_flags = (window->fullscreen ?
414413         SDL_WINDOW_BORDERLESS | SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS
415414         | SDL_WINDOW_INPUT_GRABBED : SDL_WINDOW_RESIZABLE);
416415
416   window->sdl_window = SDL_CreateWindow(window->title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
417         width, height, sdl->extra_flags);
418
417419   if (window->fullscreen && video_config.switchres)
418420   {
419421      SDL_DisplayMode mode;
r14439r14440
427429   else
428430      SDL_SetWindowDisplayMode(window->sdl_window, NULL);   // Use desktop
429431
430   window->sdl_window = SDL_CreateWindow(window->title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
431         width, height, sdl->extra_flags);
432432   SDL_ShowWindow(window->sdl_window);
433433
434434   SDL_SetWindowFullscreen(window->sdl_window, (SDL_bool) window->fullscreen);
r14439r14440
442442   // create a texture
443443
444444   if (video_config.waitvsync)
445      window->sdl_renderer = SDL_CreateRenderer(window->sdl_window, -1, /*SDL_RENDERER_PRESENTFLIP2 | SDL_RENDERER_PRESENTDISCARD |*/ SDL_RENDERER_PRESENTVSYNC);
445      sdl->sdl_renderer = SDL_CreateRenderer(window->sdl_window, -1, /*SDL_RENDERER_PRESENTFLIP2 | SDL_RENDERER_PRESENTDISCARD |*/ SDL_RENDERER_PRESENTVSYNC);
446446   else
447      window->sdl_renderer = SDL_CreateRenderer(window->sdl_window, -1, /*SDL_RENDERER_PRESENTFLIP2 | SDL_RENDERER_PRESENTDISCARD*/ 0);
447      sdl->sdl_renderer = SDL_CreateRenderer(window->sdl_window, -1, /*SDL_RENDERER_PRESENTFLIP2 | SDL_RENDERER_PRESENTDISCARD*/ 0);
448448
449449    //SDL_SelectRenderer(window->sdl_window);
450450
451451    {
452452        struct SDL_RendererInfo render_info;
453       SDL_GetRendererInfo(window->sdl_renderer, &render_info);
454453
454        SDL_GetRendererInfo(sdl->sdl_renderer, &render_info);
455455       drawsdl_show_info(window, &render_info);
456456
457457       // Check scale mode
458458
459       if (sdl->scale_mode->pixel_format)
459       if (sm->pixel_format)
460460       {
461461          int i;
462462          int found = 0;
463463
464464          for (i=0; i < render_info.num_texture_formats; i++)
465             if (sdl->scale_mode->pixel_format == render_info.texture_formats[i])
465             if (sm->pixel_format == render_info.texture_formats[i])
466466                found = 1;
467467
468468          if (!found)
469469          {
470             mame_printf_verbose("window: Scale mode %s not supported! Using default.\n", sdl->scale_mode->name);
471             ui_popup_time(3, "Scale mode %s not supported! Using default.", sdl->scale_mode->name);
472             sdl->scale_mode = &scale_modes[0];
470             mame_printf_verbose("window: Scale mode %s not supported!\n", sm->name);
471             ui_popup_time(3, "Scale mode %s not supported!", sm->name);
473472          }
474473       }
475474    }
r14439r14440
478477#else
479478   sdl->extra_flags = (window->fullscreen ?  SDL_FULLSCREEN : SDL_RESIZABLE);
480479
481   sdl->extra_flags |= sdl->scale_mode->extra_flags;
480   sdl->extra_flags |= sm->extra_flags;
482481
483482   sdl->sdlsurf = SDL_SetVideoMode(width, height,
484483               0, SDL_SWSURFACE | SDL_ANYFORMAT | sdl->extra_flags);
r14439r14440
489488   window->width = sdl->sdlsurf->w;
490489   window->height = sdl->sdlsurf->h;
491490
492   if (sdl->scale_mode->is_yuv)
491   if (sm->is_yuv)
493492      yuv_overlay_init(window);
494493
495494   // set the window title
r14439r14440
508507
509508static void drawsdl_window_resize(sdl_window_info *window, int width, int height)
510509{
511
512#if (SDL_VERSION_ATLEAST(1,3,0))
510#if (!SDLMAME_SDL2)
511   const sdl_scale_mode *sdl_sm = &scale_modes[video_config.scale_mode];
512#endif
513#if (SDLMAME_SDL2)
513514   SDL_SetWindowSize(window->sdl_window, width, height);
514515   SDL_GetWindowSize(window->sdl_window, &window->width, &window->height);
515516
r14439r14440
529530   window->width = sdl->sdlsurf->w;
530531   window->height = sdl->sdlsurf->h;
531532
532   if (sdl->scale_mode->is_yuv)
533   if (sdl_sm->is_yuv)
533534   {
534535      yuv_overlay_init(window);
535536   }
r14439r14440
550551   if (sdl == NULL)
551552      return;
552553
553#if (SDL_VERSION_ATLEAST(1,3,0))
554#if (SDLMAME_SDL2)
554555   //SDL_SelectRenderer(window->sdl_window);
555556   SDL_DestroyTexture(sdl->texture_id);
556557   //SDL_DestroyRenderer(window->sdl_window);
r14439r14440
602603static int drawsdl_xy_to_render_target(sdl_window_info *window, int x, int y, int *xt, int *yt)
603604{
604605   sdl_info *sdl = (sdl_info *) window->dxdata;
606   const sdl_scale_mode *sm = &scale_modes[video_config.scale_mode];
605607
606608   *xt = x - sdl->last_hofs;
607609   *yt = y - sdl->last_vofs;
r14439r14440
609611      return 0;
610612   if (*yt<0 || *xt >= window->blitheight)
611613      return 0;
612   if (!sdl->scale_mode->is_scale)
614   if (!sm->is_scale)
613615   {
614616      return 1;
615617   }
r14439r14440
626628static render_primitive_list &drawsdl_window_get_primitives(sdl_window_info *window)
627629{
628630   sdl_info *sdl = (sdl_info *) window->dxdata;
631   const sdl_scale_mode *sm = &scale_modes[video_config.scale_mode];
629632
630633   if ((!window->fullscreen) || (video_config.switchres))
631634   {
r14439r14440
636639      sdlwindow_blit_surface_size(window, window->monitor->center_width, window->monitor->center_height);
637640   }
638641
639   if (!sdl->scale_mode->is_scale)
642   if (!sm->is_scale)
640643      window->target->set_bounds(window->blitwidth, window->blitheight, sdlvideo_monitor_get_aspect(window->monitor));
641644   else
642645      window->target->set_bounds(sdl->hw_scale_width, sdl->hw_scale_height);
r14439r14440
651654static int drawsdl_window_draw(sdl_window_info *window, UINT32 dc, int update)
652655{
653656   sdl_info *sdl = (sdl_info *) window->dxdata;
657   const sdl_scale_mode *sm = &scale_modes[video_config.scale_mode];
654658   UINT8 *surfptr;
655659   INT32 pitch;
656660   int bpp;
657661   Uint32 rmask, gmask, bmask;
658#if (SDL_VERSION_ATLEAST(1,3,0))
662#if (SDLMAME_SDL2)
659663   Uint32 amask;
660664#endif
661665   INT32 vofs, hofs, blitwidth, blitheight, ch, cw;
r14439r14440
670674      return 1;
671675
672676   // lock it if we need it
673#if (!SDL_VERSION_ATLEAST(1,3,0))
677#if (!SDLMAME_SDL2)
674678
675679   pitch = sdl->sdlsurf->pitch;
676680   bpp = sdl->sdlsurf->format->BytesPerPixel;
r14439r14440
681685
682686   if (window->blitwidth != sdl->old_blitwidth || window->blitheight != sdl->old_blitheight)
683687   {
684      if (sdl->scale_mode->is_yuv)
688      if (sm->is_yuv)
685689         yuv_overlay_init(window);
686690      sdl->old_blitwidth = window->blitwidth;
687691      sdl->old_blitheight = window->blitheight;
r14439r14440
698702   }
699703
700704
701   if (sdl->scale_mode->is_yuv)
705   if (sm->is_yuv)
702706   {
703707      SDL_LockYUVOverlay(sdl->yuvsurf);
704708      surfptr = sdl->yuvsurf->pixels[0]; // (UINT8 *) sdl->yuv_bitmap;
r14439r14440
711715
712716   if (window->blitwidth != sdl->old_blitwidth || window->blitheight != sdl->old_blitheight)
713717   {
718      SDL_RenderSetViewport(sdl->sdl_renderer, NULL);
719
714720      SDL_DestroyTexture(sdl->texture_id);
715721      setup_texture(window, window->blitwidth, window->blitheight);
716722      sdl->old_blitwidth = window->blitwidth;
r14439r14440
731737   if (sdl->blittimer > 0)
732738   {
733739      /* SDL Underlays need alpha = 0 ! */
734      SDL_SetRenderDrawColor(window->sdl_renderer,0,0,0,0);
735      SDL_RenderFillRect(window->sdl_renderer,NULL);
740      SDL_SetRenderDrawColor(sdl->sdl_renderer,0,0,0,0);
741      SDL_RenderFillRect(sdl->sdl_renderer,NULL);
736742      //SDL_RenderFill(0,0,0,0 /*255*/,NULL);
737743      sdl->blittimer--;
738744   }
r14439r14440
784790   window->primlist->acquire_lock();
785791
786792   // render to it
787   if (!sdl->scale_mode->is_yuv)
793   if (!sm->is_yuv)
788794   {
789795      int mamewidth, mameheight;
790796
791      if (!sdl->scale_mode->is_scale)
797      if (!sm->is_scale)
792798      {
793799         mamewidth = blitwidth;
794800         mameheight = blitheight;
795#if !SDL_VERSION_ATLEAST(1,3,0)
801#if !SDLMAME_SDL2
796802         surfptr += ((vofs * pitch) + (hofs * bpp));
797803#endif
798804      }
r14439r14440
833839      assert (sdl->yuv_bitmap != NULL);
834840      assert (surfptr != NULL);
835841      drawsdl_rgb555_draw_primitives(*window->primlist, sdl->yuv_bitmap, sdl->hw_scale_width, sdl->hw_scale_height, sdl->hw_scale_width);
836      sdl->scale_mode->yuv_blit((UINT16 *)sdl->yuv_bitmap, sdl, surfptr, pitch);
842      sm->yuv_blit((UINT16 *)sdl->yuv_bitmap, sdl, surfptr, pitch);
837843   }
838844
839845   window->primlist->release_lock();
840846
841847   // unlock and flip
842#if (!SDL_VERSION_ATLEAST(1,3,0))
848#if (!SDLMAME_SDL2)
843849   if (SDL_MUSTLOCK(sdl->sdlsurf)) SDL_UnlockSurface(sdl->sdlsurf);
844   if (!sdl->scale_mode->is_yuv)
850   if (!sm->is_yuv)
845851   {
846852      SDL_Flip(sdl->sdlsurf);
847853   }
r14439r14440
867873      r.h=blitheight;
868874      //printf("blitwidth %d %d - %d %d\n", blitwidth, blitheight, window->width, window->height);
869875      //SDL_UpdateTexture(sdl->sdltex, NULL, sdl->sdlsurf->pixels, pitch);
870      SDL_RenderCopy(window->sdl_renderer,sdl->texture_id, NULL, &r);
871      SDL_RenderPresent(window->sdl_renderer);
876      SDL_RenderCopy(sdl->sdl_renderer,sdl->texture_id, NULL, &r);
877      SDL_RenderPresent(sdl->sdl_renderer);
872878   }
873879#endif
874880   return 0;
src/osd/sdl/draw13.c
r14439r14440
1818#include "options.h"
1919
2020// standard SDL headers
21#include <SDL/SDL.h>
21#include "sdlinc.h"
2222
2323// OSD headers
2424#include "osdsdl.h"
r14439r14440
379379#if 0
380380      if ((PRIMFLAG_GET_SCREENTEX(prim->flags)) && video_config.filter)
381381      {
382         SDL_SetTextureScaleMode(texture->texture_id,  SDL_SCALEMODE_BEST);
382         SDL_SetTextureScaleMode(texture->texture_id,  DRAW2_SCALEMODE_BEST);
383383      }
384384      else
385385      {
386         SDL_SetTextureScaleMode(texture->texture_id,  SDL_SCALEMODE_NONE);
386         SDL_SetTextureScaleMode(texture->texture_id,  DRAW2_SCALEMODE_NEAREST);
387387      }
388388#endif
389389      SDL_SetTextureBlendMode(texture_id, texture->sdl_blendmode);
r14439r14440
497497   callbacks->exit = draw13_exit;
498498   callbacks->attach = draw13_attach;
499499
500   mame_printf_verbose("Using SDL native texturing driver (SDL 1.3+)\n");
500   mame_printf_verbose("Using SDL native texturing driver (SDL 2.0+)\n");
501501
502502   expand_copy_info(blit_info_default);
503503   //FIXME: -opengl16 should be -opengl -prefer16bpp
r14439r14440
577577         SDL_WINDOW_BORDERLESS | SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_FULLSCREEN : SDL_WINDOW_RESIZABLE);
578578
579579   // create the SDL window
580   window->sdl_window = SDL_CreateWindow(window->title, SDL_WINDOWPOS_UNDEFINED_DISPLAY(window->monitor->handle), SDL_WINDOWPOS_UNDEFINED,
581         width, height, sdl->extra_flags);
582
580583   if (window->fullscreen && video_config.switchres)
581584   {
582585      SDL_DisplayMode mode;
r14439r14440
610613   else
611614      SDL_SetWindowDisplayMode(window->sdl_window, NULL);   // Use desktop
612615
613   window->sdl_window = SDL_CreateWindow(window->title, SDL_WINDOWPOS_UNDEFINED_DISPLAY(window->monitor->handle), SDL_WINDOWPOS_UNDEFINED,
614         width, height, sdl->extra_flags);
615
616616   // create renderer
617617
618618   if (video_config.waitvsync)
619      sdl->sdl_renderer = SDL_CreateRenderer(window->sdl_window, -1, /*SDL_RENDERER_PRESENTFLIP2 | SDL_RENDERER_PRESENTDISCARD | */SDL_RENDERER_PRESENTVSYNC);
619      sdl->sdl_renderer = SDL_CreateRenderer(window->sdl_window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED);
620620   else
621      sdl->sdl_renderer = SDL_CreateRenderer(window->sdl_window, -1, /*SDL_RENDERER_PRESENTFLIP2 | SDL_RENDERER_PRESENTDISCARD*/ 0);
621      sdl->sdl_renderer = SDL_CreateRenderer(window->sdl_window, -1, SDL_RENDERER_ACCELERATED);
622622
623623   if (!sdl->sdl_renderer)
624624   {
r14439r14440
721721      SDL_SetWindowSize(window->sdl_window, sdl->resize_width, sdl->resize_height);
722722      SDL_GetWindowSize(window->sdl_window, &window->width, &window->height);
723723      sdl->resize_pending = 0;
724      SDL_RenderSetViewport(sdl->sdl_renderer, NULL);
724725   }
725726
726727    //SDL_SelectRenderer(window->sdl_window);
src/osd/sdl/sdlsync_os2.c
r14439r14440
1313#define _GNU_SOURCE    // for PTHREAD_MUTEX_RECURSIVE; needs to be here before other glibc headers are included
1414#endif
1515
16#include "SDL/SDL.h"
16#include "sdlinc.h"
1717
1818// standard C headers
1919#include <math.h>
src/osd/sdl/sdlsync_tc.c
r14439r14440
1313#define _GNU_SOURCE    // for PTHREAD_MUTEX_RECURSIVE; needs to be here before other glibc headers are included
1414#endif
1515
16#include "SDL/SDL.h"
16#include "sdlinc.h"
1717
1818#ifdef SDLMAME_MACOSX
1919#include <mach/mach.h>
src/osd/sdl/video.c
r14439r14440
99//
1010//============================================================
1111
12#include <SDL/SDL.h>
13// on win32 this includes windows.h by itself and breaks us!
14#ifndef SDLMAME_WIN32
15#include <SDL/SDL_syswm.h>
16#endif
12#include "sdlinc.h"
1713
1814#ifdef SDLMAME_X11
1915#include <X11/extensions/Xinerama.h>
r14439r14440
163159
164160void sdlvideo_monitor_refresh(sdl_monitor_info *monitor)
165161{
166   #if (SDL_VERSION_ATLEAST(1,3,0))
162   #if (SDLMAME_SDL2)
167163   SDL_DisplayMode dmode;
168164
169165   SDL_GetDesktopDisplayMode(monitor->handle, &dmode);
r14439r14440
283279         info_shown = 1;
284280      }
285281   }
286   #endif //  (SDL_VERSION_ATLEAST(1,3,0))
282   #endif //  (SDLMAME_SDL2)
287283}
288284
289285
r14439r14440
354350//  add_primary_monitor
355351//============================================================
356352
357#if !defined(SDLMAME_WIN32) && !(SDL_VERSION_ATLEAST(1,3,0))
353#if !defined(SDLMAME_WIN32) && !(SDLMAME_SDL2)
358354static void add_primary_monitor(void *data)
359355{
360356   sdl_monitor_info ***tailptr = (sdl_monitor_info ***)data;
r14439r14440
385381//  monitor_enum_callback
386382//============================================================
387383
388#if defined(SDLMAME_WIN32) && !(SDL_VERSION_ATLEAST(1,3,0))
384#if defined(SDLMAME_WIN32) && !(SDLMAME_SDL2)
389385static BOOL CALLBACK monitor_enum_callback(HMONITOR handle, HDC dc, LPRECT rect, LPARAM data)
390386{
391387   sdl_monitor_info ***tailptr = (sdl_monitor_info ***)data;
r14439r14440
446442   sdl_monitor_list = NULL;
447443   tailptr = &sdl_monitor_list;
448444
449   #if (SDL_VERSION_ATLEAST(1,3,0))
445   #if (SDLMAME_SDL2)
450446   {
451447      int i;
452448
r14439r14440
494490//  pick_monitor
495491//============================================================
496492
497#if (SDL_VERSION_ATLEAST(1,3,0)) || defined(SDLMAME_WIN32)
493#if (SDLMAME_SDL2) || defined(SDLMAME_WIN32)
498494static sdl_monitor_info *pick_monitor(sdl_options &options, int index)
499495{
500496   sdl_monitor_info *monitor;
r14439r14440
580576      ui_popup_time(1, "Keepaspect %s", video_config.keepaspect? "enabled":"disabled");
581577   }
582578
583   if (USE_OPENGL || SDL_VERSION_ATLEAST(1,3,0))
579   if (USE_OPENGL || SDLMAME_SDL2)
584580   {
585581      //FIXME: on a per window basis
586582      if (ui_input_pressed(machine, IPT_OSD_5))
r14439r14440
654650      video_config.mode = VIDEO_MODE_OPENGL;
655651      video_config.prefer16bpp_tex = 1;
656652   }
657   else if (SDL_VERSION_ATLEAST(1,3,0) && (strcmp(stemp, SDLOPTVAL_SDL13) == 0))
653   else if (SDLMAME_SDL2 && (strcmp(stemp, SDLOPTVAL_SDL13) == 0))
658654   {
659655      video_config.mode = VIDEO_MODE_SDL13;
660656      video_config.prefer16bpp_tex = 1;
r14439r14440
676672      video_config.syncrefresh = 0;
677673   }
678674
679   if (USE_OPENGL || SDL_VERSION_ATLEAST(1,3,0))
675   if (USE_OPENGL || SDLMAME_SDL2)
680676   {
681677      video_config.filter        = options.filter();
682678   }
r14439r14440
765761   // misc options: sanity check values
766762
767763   // global options: sanity check values
768#if (!SDL_VERSION_ATLEAST(1,3,0))
764#if (!SDLMAME_SDL2)
769765   if (video_config.numscreens < 1 || video_config.numscreens > 1) //MAX_VIDEO_WINDOWS)
770766   {
771767      mame_printf_warning("Invalid numscreens value %d; reverting to 1\n", video_config.numscreens);
src/osd/sdl/sdlmisc_win32.c
r14439r14440
1010//============================================================
1111
1212// standard sdl header
13#include <SDL/SDL.h>
13#include "sdlinc.h"
1414
1515
1616#define WIN32_LEAN_AND_MEAN
src/osd/sdl/sdlsync_sdl.c
r14439r14440
99//
1010//============================================================
1111
12#include "SDL/SDL.h"
12#include "sdlinc.h"
1313
1414// standard C headers
1515#include <unistd.h>
src/osd/sdl/sdlmisc_os2.c
r14439r14440
1010//============================================================
1111
1212// standard sdl header
13#include <SDL/SDL.h>
13#include "sdlinc.h"
1414#include <unistd.h>
1515#include <stdio.h>
1616#include <string.h>
src/osd/sdl/sdlmain.c
r14439r14440
1010//============================================================
1111
1212// standard sdl header
13#include <SDL/SDL.h>
14#include <SDL/SDL_version.h>
13#include "sdlinc.h"
1514
1615#ifdef SDLMAME_UNIX
1716#ifndef SDLMAME_MACOSX
17#if (SDLMAME_SDL2)
18#include <SDL2/SDL_ttf.h>
19#else
1820#include <SDL/SDL_ttf.h>
21#endif
1922#include <fontconfig/fontconfig.h>
2023#endif
2124#ifdef SDLMAME_MACOSX
r14439r14440
112115   { SDLOPTION_WAITVSYNC ";vs",              "0",        OPTION_BOOLEAN,    "enable waiting for the start of VBLANK before flipping screens; reduces tearing effects" },
113116   { SDLOPTION_SYNCREFRESH ";sr",            "0",        OPTION_BOOLEAN,    "enable using the start of VBLANK for throttling instead of the game time" },
114117   #endif
115#if (SDL_VERSION_ATLEAST(1,3,0))
118#if (SDLMAME_SDL2)
116119   { SDLOPTION_SCALEMODE ";sm",         SDLOPTVAL_NONE,  OPTION_STRING,     "Scale mode: none, hwblit, hwbest, yv12, yuy2, yv12x2, yuy2x2 (-video soft only)" },
117120#else
118121   { SDLOPTION_SCALEMODE ";sm",         SDLOPTVAL_NONE,  OPTION_STRING,     "Scale mode: none, async, yv12, yuy2, yv12x2, yuy2x2 (-video soft only)" },
r14439r14440
211214   { SDLOPTION_JOYINDEX "8",                SDLOPTVAL_AUTO, OPTION_STRING,         "name of joystick mapped to joystick #8" },
212215   { SDLOPTION_SIXAXIS,                  "0",    OPTION_BOOLEAN,    "Use special handling for PS3 Sixaxis controllers" },
213216
214#if (SDL_VERSION_ATLEAST(1,3,0))
217#if (SDLMAME_SDL2)
215218   { NULL,                                NULL,   OPTION_HEADER,     "SDL MOUSE MAPPING" },
216219   { SDLOPTION_MOUSEINDEX "1",              SDLOPTVAL_AUTO, OPTION_STRING,         "name of mouse mapped to mouse #1" },
217220   { SDLOPTION_MOUSEINDEX "2",              SDLOPTVAL_AUTO, OPTION_STRING,         "name of mouse mapped to mouse #2" },
r14439r14440
235238   // SDL low level driver options
236239   { NULL,                                NULL,   OPTION_HEADER,     "SDL LOWLEVEL DRIVER OPTIONS" },
237240   { SDLOPTION_VIDEODRIVER ";vd",           SDLOPTVAL_AUTO,  OPTION_STRING,        "sdl video driver to use ('x11', 'directfb', ... or 'auto' for SDL default" },
238#if (SDL_VERSION_ATLEAST(1,3,0))
241#if (SDLMAME_SDL2)
239242   { SDLOPTION_RENDERDRIVER ";rd",          SDLOPTVAL_AUTO,  OPTION_STRING,        "sdl render driver to use ('software', 'opengl', 'directfb' ... or 'auto' for SDL default" },
240243#endif
241244   { SDLOPTION_AUDIODRIVER ";ad",           SDLOPTVAL_AUTO,  OPTION_STRING,        "sdl audio driver to use ('alsa', 'arts', ... or 'auto' for SDL default" },
r14439r14440
298301{
299302   int res = 0;
300303
301#if   !(SDL_VERSION_ATLEAST(1,3,0))
304#if   !(SDLMAME_SDL2)
302305   /* Load SDL dynamic link library */
303306   if ( SDL_Init(SDL_INIT_NOPARACHUTE) < 0 ) {
304307      fprintf(stderr, "WinMain() error: %s", SDL_GetError());
r14439r14440
416419   #endif
417420
418421   if (!SDLMAME_INIT_IN_WORKER_THREAD)
422   {
423      /* FixMe: Bug in SDL2.0, Quitting joystick will cause SIGSEGV */
424#if SDLMAME_SDL2
425      SDL_QuitSubSystem(SDL_INIT_TIMER|SDL_INIT_AUDIO| SDL_INIT_VIDEO /*| SDL_INIT_JOYSTICK */);
426#else
419427      SDL_Quit();
428#endif
429   }
420430}
421431
422432//============================================================
r14439r14440
492502
493503static void osd_sdl_info(void)
494504{
495#if SDL_VERSION_ATLEAST(1,3,0)
505#if SDLMAME_SDL2
496506   int i, num = SDL_GetNumVideoDrivers();
497507
498508   mame_printf_verbose("Available videodrivers: ");
r14439r14440
572582      osd_setenv(SDLENV_VIDEODRIVER, stemp, 1);
573583   }
574584
575   if (SDL_VERSION_ATLEAST(1,3,0))
576   {
585#if (SDLMAME_SDL2)
577586      stemp = options.render_driver();
578587      if (stemp != NULL && strcmp(stemp, SDLOPTVAL_AUTO) != 0)
579588      {
580589         mame_printf_verbose("Setting SDL renderdriver '%s' ...\n", stemp);
581         osd_setenv(SDLENV_RENDERDRIVER, stemp, 1);
590         //osd_setenv(SDLENV_RENDERDRIVER, stemp, 1);
591         SDL_SetHint(SDL_HINT_RENDER_DRIVER, stemp);
582592      }
583   }
593#endif
584594
585595   /* Set the SDL environment variable for drivers wanting to load the
586596     * lib at startup.
r14439r14440
615625
616626   if (!SDLMAME_INIT_IN_WORKER_THREAD)
617627   {
618#if (SDL_VERSION_ATLEAST(1,3,0))
628#if (SDLMAME_SDL2)
619629      if (SDL_InitSubSystem(SDL_INIT_TIMER|SDL_INIT_AUDIO| SDL_INIT_VIDEO| SDL_INIT_JOYSTICK|SDL_INIT_NOPARACHUTE)) {
620630#else
621631      if (SDL_Init(SDL_INIT_TIMER|SDL_INIT_AUDIO| SDL_INIT_VIDEO| SDL_INIT_JOYSTICK|SDL_INIT_NOPARACHUTE)) {
r14439r14440
670680      m_watchdog->setTimeout(watchdog_timeout);
671681   }
672682
673#if (SDL_VERSION_ATLEAST(1,3,0))
683#if (SDLMAME_SDL2)
674684   SDL_EventState(SDL_TEXTINPUT, SDL_TRUE);
675685#else
676686   SDL_EnableUNICODE(SDL_TRUE);
src/osd/sdl/osdsdl.h
r14439r14440
11#ifndef _osdsdl_h_
22#define _osdsdl_h_
33
4#include <SDL/SDL.h>
4#include "sdlinc.h"
55
66#include "watchdog.h"
77#include "clifront.h"
88
99//============================================================
10//  Temporary SDL 1.3 defines
11//============================================================
12
13// set this to 0 if compiling against a "hg update 4464"
14// checkout of SDL 1.3
15
16#define SDL13_POST_HG4464   (1)
17
18//============================================================
1910//  System dependent defines
2011//============================================================
2112
2213// Process events in worker thread
23#if defined(SDLMAME_WIN32) || (SDL_VERSION_ATLEAST(1,3,0))
14#if defined(SDLMAME_WIN32) || (SDLMAME_SDL2)
2415#define SDLMAME_EVENTS_IN_WORKER_THREAD   (1)
2516#else
2617#define SDLMAME_EVENTS_IN_WORKER_THREAD   (0)
2718#endif
2819
2920#if defined(SDLMAME_WIN32)
30   #if (SDL_VERSION_ATLEAST(1,3,0))
21   #if (SDLMAME_SDL2)
3122      #define SDLMAME_INIT_IN_WORKER_THREAD   (0) //FIXME: breaks mt
3223      #define SDL13_COMBINE_RESIZE (1)
3324   #else
r14439r14440
215206   const char *joy_index(int index) const { astring temp; return value(temp.format("%s%d", SDLOPTION_JOYINDEX, index)); }
216207   bool sixaxis() const { return bool_value(SDLOPTION_SIXAXIS); }
217208
218#if (SDL_VERSION_ATLEAST(1,3,0))
209#if (SDLMAME_SDL2)
219210   const char *mouse_index(int index) const { astring temp; return value(temp.format("%s%d", SDLOPTION_MOUSEINDEX, index)); }
220211   const char *keyboard_index(int index) const { astring temp; return value(temp.format("%s%d", SDLOPTION_KEYBINDEX, index)); }
221212#endif
src/osd/sdl/osd_opengl.h
r14439r14440
1515   /* equivalent to #include <GL/gl.h>
1616     * #include <GL/glext.h>
1717     */
18   #if (SDLMAME_SDL2)
19   #include <SDL2/SDL_version.h>
20   #else
1821   #include <SDL/SDL_version.h>
22   #endif
1923
2024#if (SDL_VERSION_ATLEAST(1,2,10))
2125   #if defined(SDLMAME_WIN32)
2226      // Avoid that winnt.h (included via sdl_opengl.h, windows.h, windef.h includes intrin.h
2327      #define __INTRIN_H_
2428   #endif
29   #if (SDLMAME_SDL2)
30   #include <SDL2/SDL_opengl.h>
31   #else
2532   #include <SDL/SDL_opengl.h>
33   #endif
2634#else
2735   /*
2836     * SDL 1.2.9 does not provide everything we need
src/osd/sdl/drawogl.c
r14439r14440
2424#include "emuopts.h"
2525
2626// standard SDL headers
27#include <SDL/SDL.h>
27#include "sdlinc.h"
2828
2929// OpenGL headers
3030#include "osd_opengl.h"
r14439r14440
219219   INT32         blittimer;
220220   UINT32         extra_flags;
221221
222#if (SDL_VERSION_ATLEAST(1,3,0))
222#if (SDLMAME_SDL2)
223223   SDL_GLContext   gl_context_id;
224224#else
225225   // SDL surface
r14439r14440
437437
438438   dll_loaded = 0;
439439
440   if (SDL_VERSION_ATLEAST(1,3,0))
441      mame_printf_verbose("Using SDL multi-window OpenGL driver (SDL 1.3+)\n");
440   if (SDLMAME_SDL2)
441   {
442      mame_printf_verbose("Using SDL multi-window OpenGL driver (SDL 2.0+)\n");
443      load_gl_lib(machine);
444   }
442445   else
443446      mame_printf_verbose("Using SDL single-window OpenGL driver (SDL 1.2)\n");
444447
445#if (SDL_VERSION_ATLEAST(1,3,0))
446   load_gl_lib(machine);
447#endif
448
449448   return 0;
450449}
451450
r14439r14440
546545
547546   window->dxdata = sdl;
548547
549#if (SDL_VERSION_ATLEAST(1,3,0))
548#if (SDLMAME_SDL2)
550549   sdl->extra_flags = (window->fullscreen ?
551550         SDL_WINDOW_BORDERLESS | SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_FULLSCREEN : SDL_WINDOW_RESIZABLE);
552551   sdl->extra_flags |= SDL_WINDOW_OPENGL;
r14439r14440
556555   //load_gl_lib(window->machine());
557556
558557   // create the SDL window
558   window->sdl_window = SDL_CreateWindow(window->title, SDL_WINDOWPOS_UNDEFINED_DISPLAY(window->monitor->handle), SDL_WINDOWPOS_UNDEFINED,
559         width, height, sdl->extra_flags);
559560
561   if  (!window->sdl_window )
562   {
563      mame_printf_error("OpenGL not supported on this driver: %s\n", SDL_GetError());
564      return 1;
565   }
566
560567   if (window->fullscreen && video_config.switchres)
561568   {
562569      SDL_DisplayMode mode;
r14439r14440
570577   else
571578      SDL_SetWindowDisplayMode(window->sdl_window, NULL);   // Use desktop
572579
573   window->sdl_window = SDL_CreateWindow(window->title, SDL_WINDOWPOS_UNDEFINED_DISPLAY(window->monitor->handle), SDL_WINDOWPOS_UNDEFINED,
574         width, height, sdl->extra_flags);
575
576   if  (!window->sdl_window )
577   {
578      mame_printf_error("OpenGL not supported on this driver: %s\n", SDL_GetError());
579      return 1;
580   }
581
582580   SDL_ShowWindow(window->sdl_window);
583581   //SDL_SetWindowFullscreen(window->sdl_window, window->fullscreen);
584582   SDL_RaiseWindow(window->sdl_window);
r14439r14440
798796{
799797   sdl_info *sdl = (sdl_info *) window->dxdata;
800798
801#if (SDL_VERSION_ATLEAST(1,3,0))
799#if (SDLMAME_SDL2)
802800   //SDL_GL_MakeCurrent(window->sdl_window, sdl->gl_context_id);
803801   SDL_SetWindowSize(window->sdl_window, width, height);
804802   SDL_GetWindowSize(window->sdl_window, &window->width, &window->height);
r14439r14440
11901188      return 0;
11911189   }
11921190
1193#if (SDL_VERSION_ATLEAST(1,3,0))
1191#if (SDLMAME_SDL2)
11941192   SDL_GL_MakeCurrent(window->sdl_window, sdl->gl_context_id);
11951193#endif
11961194   if (sdl->init_context)
r14439r14440
15461544   window->primlist->release_lock();
15471545   sdl->init_context = 0;
15481546
1549#if (!SDL_VERSION_ATLEAST(1,3,0))
1547#if (!SDLMAME_SDL2)
15501548   SDL_GL_SwapBuffers();
15511549#else
15521550   SDL_GL_SwapWindow(window->sdl_window);
r14439r14440
17211719
17221720   drawogl_destroy_all_textures(window);
17231721
1724#if (SDL_VERSION_ATLEAST(1,3,0))
1722#if (SDLMAME_SDL2)
17251723   SDL_GL_DeleteContext(sdl->gl_context_id);
17261724   SDL_DestroyWindow(window->sdl_window);
17271725#else
r14439r14440
31353133   if ( !sdl->initialized )
31363134      return;
31373135
3138#if (SDL_VERSION_ATLEAST(1,3,0))
3136#if (SDLMAME_SDL2)
31393137   SDL_GL_MakeCurrent(window->sdl_window, sdl->gl_context_id);
31403138#endif
31413139
src/osd/sdl/sound.c
r14439r14440
1010//============================================================
1111
1212// standard sdl header
13#include <SDL/SDL.h>
13#include "sdlinc.h"
1414
1515// MAME headers
1616#include "emu.h"
r14439r14440
432432   }
433433
434434   mame_printf_verbose("Audio: Start initialization\n");
435#if (SDL_VERSION_ATLEAST(1,3,0))
435#if (SDLMAME_SDL2)
436436   strncpy(audio_driver, SDL_GetCurrentAudioDriver(), sizeof(audio_driver));
437437#else
438438   SDL_AudioDriverName(audio_driver, sizeof(audio_driver));
src/osd/sdl/input.c
r14439r14440
1313//============================================================
1414
1515// standard sdl header
16#include <SDL/SDL.h>
16#include "sdlinc.h"
1717#include <ctype.h>
1818#include <stddef.h>
1919
r14439r14440
206206   char      *   ui_name;
207207};
208208
209#if (SDL_VERSION_ATLEAST(1,3,0))
209#if (SDLMAME_SDL2)
210210
211211#define OSD_SDL_INDEX(x) (x)
212212#define OSD_SDL_INDEX_KEYSYM(keysym) ((keysym)->scancode)
r14439r14440
470470   const char *name;
471471};
472472
473#if (SDL_VERSION_ATLEAST(1,3,0))
473#if (SDLMAME_SDL2)
474474#define KE(x) { SDL_SCANCODE_ ## x, "SDL_SCANCODE_" #x },
475475#define KE8(A, B, C, D, E, F, G, H) KE(A) KE(B) KE(C) KE(D) KE(E) KE(F) KE(G) KE(H)
476476#define KE7(A, B, C, D, E, F, G) KE(A) KE(B) KE(C) KE(D) KE(E) KE(F) KE(G)
r14439r14440
790790//  sdlinput_register_mice
791791//============================================================
792792
793#if (!SDL13_POST_HG4464 && SDL_VERSION_ATLEAST(1,3,0))
793#if defined(SDL2_MULTIAPI) && 0
794794static void sdlinput_register_mice(running_machine &machine)
795795{
796796   int index, physical_mouse;
r14439r14440
10021002//  sdlinput_register_keyboards
10031003//============================================================
10041004
1005#if ((1 ||!SDL13_POST_HG4464) && SDL_VERSION_ATLEAST(1,3,0))
1005#ifdef SDL2_MULTIAPI
10061006static void sdlinput_register_keyboards(running_machine &machine)
10071007{
10081008   int physical_keyboard;
r14439r14440
11931193//  sdlinput_poll
11941194//============================================================
11951195
1196#if (SDL_VERSION_ATLEAST(1,3,0))
1196#if (SDLMAME_SDL2)
11971197INLINE sdl_window_info * window_from_id(Uint32 windowID)
11981198{
11991199   sdl_window_info *w;
r14439r14440
12381238   if (SDLMAME_EVENTS_IN_WORKER_THREAD)
12391239   {
12401240      osd_lock_acquire(input_lock);
1241   #if (SDL_VERSION_ATLEAST(1,3,0))
1241   #if (SDLMAME_SDL2)
12421242      /* Make sure we get all pending events */
12431243      SDL_PumpEvents();
12441244   #endif
r14439r14440
13061306      }
13071307      switch(event.type) {
13081308      case SDL_KEYDOWN:
1309#ifdef SDL2_MULTIAPI
13091310         devinfo = generic_device_find_index( keyboard_list, keyboard_map.logical[event.key.which]);
13101311         //printf("Key down %d %d %s => %d %s (scrlock keycode is %d)\n", event.key.which, event.key.keysym.scancode, devinfo->name, OSD_SDL_INDEX_KEYSYM(&event.key.keysym), sdl_key_trans_table[event.key.keysym.scancode].mame_key_name, KEYCODE_SCRLOCK);
1312#else
1313         devinfo = generic_device_find_index( keyboard_list, keyboard_map.logical[0]);
1314#endif
13111315         devinfo->keyboard.state[OSD_SDL_INDEX_KEYSYM(&event.key.keysym)] = 0x80;
1312#if (!SDL_VERSION_ATLEAST(1,3,0))
1316#if (!SDLMAME_SDL2)
13131317         ui_input_push_char_event(machine, sdl_window_list->target, (unicode_char) event.key.keysym.unicode);
13141318#endif
13151319         break;
13161320      case SDL_KEYUP:
1321#ifdef SDL2_MULTIAPI
13171322         devinfo = generic_device_find_index( keyboard_list, keyboard_map.logical[event.key.which]);
1323         //printf("Key up: %d %d\n", OSD_SDL_INDEX_KEYSYM(&event.key.keysym), event.key.which);
1324#else
1325         devinfo = generic_device_find_index( keyboard_list, keyboard_map.logical[0]);
1326#endif
13181327         devinfo->keyboard.state[OSD_SDL_INDEX_KEYSYM(&event.key.keysym)] = 0x00;
13191328         break;
13201329      case SDL_JOYAXISMOTION:
r14439r14440
13891398         }
13901399         break;
13911400      case SDL_MOUSEBUTTONDOWN:
1401#ifdef SDL2_MULTIAPI
13921402         devinfo = generic_device_find_index(mouse_list, mouse_map.logical[event.button.which]);
1403#else
1404         devinfo = generic_device_find_index(mouse_list, mouse_map.logical[0]);
1405#endif
13931406         devinfo->mouse.buttons[event.button.button-1] = 0x80;
13941407         //printf("But down %d %d %d %d %s\n", event.button.which, event.button.button, event.button.x, event.button.y, devinfo->name);
13951408         if (event.button.button == 1)
r14439r14440
14221435         }
14231436         break;
14241437      case SDL_MOUSEBUTTONUP:
1438#ifdef SDL2_MULTIAPI
14251439         devinfo = generic_device_find_index(mouse_list, mouse_map.logical[event.button.which]);
1440#else
1441         devinfo = generic_device_find_index(mouse_list, mouse_map.logical[0]);
1442#endif
14261443         devinfo->mouse.buttons[event.button.button-1] = 0;
14271444         //printf("But up %d %d %d %d\n", event.button.which, event.button.button, event.button.x, event.button.y);
14281445
r14439r14440
14381455         }
14391456         break;
14401457      case SDL_MOUSEMOTION:
1458#ifdef SDL2_MULTIAPI
14411459         devinfo = generic_device_find_index(mouse_list, mouse_map.logical[event.motion.which]);
1442#if (SDL_VERSION_ATLEAST(1,3,0))
1460#else
1461         devinfo = generic_device_find_index(mouse_list, mouse_map.logical[0]);
1462#endif
1463#if (SDLMAME_SDL2)
14431464         // FIXME: may apply to 1.2 as well ...
14441465         //printf("Motion %d %d %d %s\n", event.motion.which, event.motion.x, event.motion.y, devinfo->name);
14451466         devinfo->mouse.lX += event.motion.xrel * INPUT_RELATIVE_PER_PIXEL;
r14439r14440
14561477               ui_input_push_mouse_move_event(machine, window->target, cx, cy);
14571478         }
14581479         break;
1459#if (!SDL_VERSION_ATLEAST(1,3,0))
1480#if (!SDLMAME_SDL2)
14601481      case SDL_APPMOUSEFOCUS:
14611482         app_has_mouse_focus = event.active.gain;
14621483         if (!event.active.gain)
r14439r14440
15331554#endif
15341555      }
15351556   }
1536#if (SDL_VERSION_ATLEAST(1,3,0))
1557#if (SDLMAME_SDL2)
15371558   resize_all_windows();
15381559#endif
15391560}
r14439r14440
15491570   // FIXME: SDL >= 1.3 will nuke the window event buffer when
15501571   // a window is closed. This will leave keys in a pressed
15511572   // state when a window is destroyed and recreated.
1552#if (SDL_VERSION_ATLEAST(1,3,0))
1573#if (SDLMAME_SDL2)
15531574   device_info *devinfo;
15541575   int index;
15551576
src/osd/sdl/debugwin.c
r14439r14440
12761276
12771277#else
12781278
1279#include <SDL/SDL.h>
1280#include <SDL/SDL_version.h>
1279#include "sdlinc.h"
12811280
12821281#include "emu.h"
12831282#include "osdepend.h"
src/osd/sdl/window.c
r14439r14440
1010//============================================================
1111
1212// standard SDL headers
13#include <SDL/SDL.h>
14#include <SDL/SDL_syswm.h>
13#include "sdlinc.h"
14
15#if (SDLMAME_SDL2)
16#include <SDL2/SDL_thread.h>
17#else
1518#include <SDL/SDL_thread.h>
19#endif
1620
1721// standard C headers
1822#include <math.h>
r14439r14440
8488static int multithreading_enabled;
8589static osd_work_queue *work_queue;
8690
87#if !(SDL_VERSION_ATLEAST(1,3,0))
91#if !(SDLMAME_SDL2)
8892typedef int SDL_threadID;
8993#endif
9094
r14439r14440
184188
185189   if (SDLMAME_INIT_IN_WORKER_THREAD)
186190   {
187#if (SDL_VERSION_ATLEAST(1,3,0))
191#if (SDLMAME_SDL2)
188192      if (SDL_InitSubSystem(SDL_INIT_TIMER|SDL_INIT_AUDIO| SDL_INIT_VIDEO| SDL_INIT_JOYSTICK|SDL_INIT_NOPARACHUTE))
189193#else
190194      if (SDL_Init(SDL_INIT_TIMER|SDL_INIT_AUDIO| SDL_INIT_VIDEO| SDL_INIT_JOYSTICK|SDL_INIT_NOPARACHUTE))
r14439r14440
239243         video_config.mode = VIDEO_MODE_SOFT;
240244   }
241245#endif
242#if   SDL_VERSION_ATLEAST(1,3,0)
246#if   SDLMAME_SDL2
243247   if (video_config.mode == VIDEO_MODE_SDL13)
244248   {
245249      if (draw13_init(machine, &draw))
r14439r14440
408412
409413    //FIXME: really necessary to distinguish for yuv_modes ?
410414   if (window->target->zoom_to_screen()
411      && (window->scale_mode == VIDEO_SCALE_MODE_NONE ))
415      && (video_config.scale_mode == VIDEO_SCALE_MODE_NONE ))
412416      newwidth = window_width;
413417
414418   if ((window->blitwidth != newwidth) || (window->blitheight != newheight))
r14439r14440
595599
596600static void sdlwindow_update_cursor_state(running_machine &machine, sdl_window_info *window)
597601{
598#if (SDL_VERSION_ATLEAST(1,3,0))
602#if (SDLMAME_SDL2)
599603   // do not do mouse capture if the debugger's enabled to avoid
600604   // the possibility of losing control
601605   if (!(machine.debug_flags & DEBUG_FLAG_OSD_ENABLED))
r14439r14440
672676   //FIXME: these should be per_window in config-> or even better a bit set
673677   window->fullscreen = !video_config.windowed;
674678   window->prescale = video_config.prescale;
675   window->scale_mode = video_config.scale_mode;
676679
677680   // set the initial maximized state
678681   // FIXME: Does not belong here
r14439r14440
798801//  pick_best_mode
799802//============================================================
800803
801#if SDL_VERSION_ATLEAST(1,3,0)
804#if SDLMAME_SDL2
802805static void pick_best_mode(sdl_window_info *window, int *fswidth, int *fsheight)
803806{
804807   int minimum_width, minimum_height, target_width, target_height;
src/osd/sdl/sdlmisc_macosx.c
r14439r14440
1010//============================================================
1111
1212// standard sdl header
13#include <SDL/SDL.h>
13#include "sdlinc.h"
1414#include <sys/types.h>
1515#include <sys/mman.h>
1616#include <signal.h>
src/osd/sdl/testkeys.c
r14439r14440
1515#include <string.h>
1616#include <wchar.h>
1717
18#include <SDL/SDL.h>
18#include "sdlinc.h"
1919
2020#include "unicode.h"
2121
2222// Check whether SDL has compat interface
23#if defined(SDL_AllocSurface) || (!SDL_VERSION_ATLEAST(1,3,0))
23#if defined(SDL_AllocSurface) || (!SDLMAME_SDL2)
2424#define SDL_HAS_COMPAT      1
2525#else
2626#define SDL_HAS_COMPAT      0
r14439r14440
3535};
3636
3737#if SDL_HAS_COMPAT
38#if (SDL_VERSION_ATLEAST(1,3,0))
38#if (SDLMAME_SDL2)
3939#define KE(x) { SDL_SCANCODE_ ## x, "SDL_SCANCODE_" #x },
4040#define KE8(A, B, C, D, E, F, G, H) KE(A) KE(B) KE(C) KE(D) KE(E) KE(F) KE(G) KE(H)
4141#define KE7(A, B, C, D, E, F, G) KE(A) KE(B) KE(C) KE(D) KE(E) KE(F) KE(G)
r14439r14440
149149            memset(buf, 0, ARRAY_LENGTH(buf));
150150            utf8_from_uchar(buf, sizeof(buf), event.key.keysym.unicode);
151151            printf("ITEM_ID_XY %s 0x%x 0x%x %s \n",
152#if (SDL_VERSION_ATLEAST(1,3,0))
152#if (SDLMAME_SDL2)
153153                  lookup_key_name(sdl_lookup, event.key.keysym.scancode),
154154#else
155155                  lookup_key_name(sdl_lookup, event.key.keysym.sym),
r14439r14440
163163         memset(buf, 0, 19);
164164         utf8_from_uchar(buf, sizeof(buf), event.key.keysym.unicode);
165165         printf("ITEM_ID_XY %s 0x%x 0x%x %s \n",
166#if (SDL_VERSION_ATLEAST(1,3,0))
166#if (SDLMAME_SDL2)
167167               lookup_key_name(sdl_lookup, event.key.keysym.scancode),
168168#else
169169               lookup_key_name(sdl_lookup, event.key.keysym.sym),
src/osd/sdl/window.h
r14439r14440
1212#ifndef __SDLWINDOW__
1313#define __SDLWINDOW__
1414
15#include <SDL/SDL.h>
15#include "sdlinc.h"
1616#include "video.h"
1717#include "render.h"
1818#include "sdlsync.h"
r14439r14440
8888   int               totalColors;      // total colors from machine/sdl_window_config
8989   int               start_viewscreen;
9090
91   // per window modes ...
92   int               scale_mode;
93
9491   // GL specific
9592   int               prescale;
9693
97#if (SDL_VERSION_ATLEAST(1,3,0))
94#if (SDLMAME_SDL2)
9895   // Needs to be here as well so we can identify window
9996   SDL_Window         *sdl_window;
100   SDL_Renderer      *sdl_renderer;
10197   // These are used in combine resizing events ... #if SDL13_COMBINE_RESIZE
10298   int             resize_width;
10399   int               resize_height;
src/osd/sdl/sdlinc.h
r0r14440
1#ifndef _sdlinc_h_
2#define _sdlinc_h_
3 
4#if (SDLMAME_SDL2)
5#include <SDL2/SDL.h>
6#include <SDL2/SDL_version.h>
7// on win32 this includes windows.h by itself and breaks us!
8#ifndef SDLMAME_WIN32
9#include <SDL2/SDL_syswm.h>
10#endif
11#else
12#include <SDL/SDL.h>
13#include <SDL/SDL_version.h>
14// on win32 this includes windows.h by itself and breaks us!
15#ifndef SDLMAME_WIN32
16#include <SDL/SDL_syswm.h>
17#endif
18#endif
19 
20#endif
src/osd/sdl/sdlsync_ntc.c
r14439r14440
1313#define _GNU_SOURCE    // for PTHREAD_MUTEX_RECURSIVE; needs to be here before other glibc headers are included
1414#endif
1515
16#include "SDL/SDL.h"
16#include "sdlinc.h"
1717
1818#ifdef SDLMAME_MACOSX
1919#include <mach/mach.h>
src/osd/sdl/gl_shader_mgr.c
r14439r14440
11
2#include <SDL/SDL.h>
2#include "sdlinc.h"
33
44#include "osd_opengl.h"
55
src/emu/fileio.c
r14439r14440
3737
3838***************************************************************************/
3939
40
41
42
4043#include "emu.h"
4144#include "unzip.h"
45#include "un7z.h"
4246#include "fileio.h"
4347
4448
r14439r14440
174178     m_zipfile(NULL),
175179     m_zipdata(NULL),
176180     m_ziplength(0),
181     m__7zfile(NULL),
182     m__7zdata(NULL),
183     m__7zlength(0),
177184     m_remove_on_close(false)
178185{
179186   // sanity check the open flags
r14439r14440
189196     m_zipfile(NULL),
190197     m_zipdata(NULL),
191198     m_ziplength(0),
199     m__7zfile(NULL),
200     m__7zdata(NULL),
201     m__7zlength(0),
192202     m_remove_on_close(false)
193203{
194204   // sanity check the open flags
r14439r14440
216226emu_file::operator core_file *()
217227{
218228   // load the ZIP file now if we haven't yet
219   if (m_zipfile != NULL && load_zipped_file() != FILERR_NONE)
229   if (compressed_file_ready())
220230      return NULL;
221231
222232   // return the core file
r14439r14440
226236emu_file::operator core_file &()
227237{
228238   // load the ZIP file now if we haven't yet
229   if (m_zipfile != NULL && load_zipped_file() != FILERR_NONE)
239   if (compressed_file_ready())
230240      throw emu_fatalerror("operator core_file & used on invalid file");
231241
232242   // return the core file
r14439r14440
251261      return m_hashes;
252262
253263   // load the ZIP file if needed
254   if (m_zipfile != NULL && load_zipped_file() != FILERR_NONE)
264   if (compressed_file_ready())
255265      return m_hashes;
256266   if (m_file == NULL)
257267      return m_hashes;
258268
259269   // if we have ZIP data, just hash that directly
270   if (m__7zdata != NULL)
271   {
272      m_hashes.compute(m__7zdata, m__7zlength, needed);
273      return m_hashes;
274   }
275
260276   if (m_zipdata != NULL)
261277   {
262278      m_hashes.compute(m_zipdata, m_ziplength, needed);
r14439r14440
368384      // if we're opening for read-only we have other options
369385      if ((m_openflags & (OPEN_FLAG_READ | OPEN_FLAG_WRITE)) == OPEN_FLAG_READ)
370386      {
387         astring tempfullpath = m_fullpath;
388
389         filerr = attempt__7zped();
390         if (filerr == FILERR_NONE)
391            break;
392
393         m_fullpath = tempfullpath;
394
371395         filerr = attempt_zipped();
372396         if (filerr == FILERR_NONE)
373397            break;
398
399
374400      }
375401   }
376402   return filerr;
r14439r14440
401427void emu_file::close()
402428{
403429   // close files and free memory
430   if (m__7zfile != NULL)
431      _7z_file_close(m__7zfile);
432   m__7zfile = NULL;
433
404434   if (m_zipfile != NULL)
405435      zip_file_close(m_zipfile);
406436   m_zipfile = NULL;
r14439r14440
409439      core_fclose(m_file);
410440   m_file = NULL;
411441
442   if (m__7zdata != NULL)
443      global_free(m__7zdata);
444   m__7zdata = NULL;
445
412446   if (m_zipdata != NULL)
413447      global_free(m_zipdata);
414448   m_zipdata = NULL;
r14439r14440
436470
437471
438472//-------------------------------------------------
473//  compressed_file_ready - ensure our zip is ready
474//   loading if needed
475//-------------------------------------------------
476
477bool emu_file::compressed_file_ready(void)
478{
479   // load the ZIP file now if we haven't yet
480   if (m__7zfile != NULL && load__7zped_file() != FILERR_NONE)
481      return true;
482
483   if (m_zipfile != NULL && load_zipped_file() != FILERR_NONE)
484      return true;
485
486   return false;
487}
488
489//-------------------------------------------------
439490//  seek - seek within a file
440491//-------------------------------------------------
441492
442493int emu_file::seek(INT64 offset, int whence)
443494{
444495   // load the ZIP file now if we haven't yet
445   if (m_zipfile != NULL && load_zipped_file() != FILERR_NONE)
496   if (compressed_file_ready())
446497      return 1;
447498
448499   // seek if we can
r14439r14440
460511UINT64 emu_file::tell()
461512{
462513   // load the ZIP file now if we haven't yet
463   if (m_zipfile != NULL && load_zipped_file() != FILERR_NONE)
514   if (compressed_file_ready())
464515      return 0;
465516
466517   // tell if we can
r14439r14440
478529bool emu_file::eof()
479530{
480531   // load the ZIP file now if we haven't yet
481   if (m_zipfile != NULL && load_zipped_file() != FILERR_NONE)
532   if (compressed_file_ready())
482533      return 0;
483534
484535   // return EOF if we can
r14439r14440
496547UINT64 emu_file::size()
497548{
498549   // use the ZIP length if present
550   if (m__7zfile != NULL)
551      return m__7zlength;
552
499553   if (m_zipfile != NULL)
500554      return m_ziplength;
501555
r14439r14440
514568UINT32 emu_file::read(void *buffer, UINT32 length)
515569{
516570   // load the ZIP file now if we haven't yet
517   if (m_zipfile != NULL && load_zipped_file() != FILERR_NONE)
571   if (compressed_file_ready())
518572      return 0;
519573
520574   // read the data if we can
r14439r14440
532586int emu_file::getc()
533587{
534588   // load the ZIP file now if we haven't yet
535   if (m_zipfile != NULL && load_zipped_file() != FILERR_NONE)
589   if (compressed_file_ready())
536590      return EOF;
537591
538592   // read the data if we can
r14439r14440
550604int emu_file::ungetc(int c)
551605{
552606   // load the ZIP file now if we haven't yet
553   if (m_zipfile != NULL && load_zipped_file() != FILERR_NONE)
607   if (compressed_file_ready())
554608      return 1;
555609
556610   // read the data if we can
r14439r14440
568622char *emu_file::gets(char *s, int n)
569623{
570624   // load the ZIP file now if we haven't yet
571   if (m_zipfile != NULL && load_zipped_file() != FILERR_NONE)
625   if (compressed_file_ready())
572626      return NULL;
573627
574628   // read the data if we can
r14439r14440
766820   const char *zipfile = header.filename + header.filename_length - 1;
767821   return (zipfile >= header.filename && zipfile[0] == '/');
768822}
823
824//-------------------------------------------------
825//  attempt__7zped - attempt to open a .7z file
826//-------------------------------------------------
827
828file_error emu_file::attempt__7zped()
829{
830   astring filename;
831
832   // loop over directory parts up to the start of filename
833   while (1)
834   {
835      // find the final path separator
836      int dirsep = m_fullpath.rchr(0, PATH_SEPARATOR[0]);
837      if (dirsep == -1)
838         return FILERR_NOT_FOUND;
839
840      // insert the part from the right of the separator into the head of the filename
841      if (filename.len() > 0)
842         filename.ins(0, "/");
843      filename.inssubstr(0, m_fullpath, dirsep + 1, -1);
844
845      // remove this part of the filename and append a .7z extension
846      m_fullpath.substr(0, dirsep).cat(".7z");
847
848      // attempt to open the _7Z file
849      _7z_file *_7z;
850      _7z_error _7zerr = _7z_file_open(m_fullpath, &_7z);
851
852      // chop the ._7z back off the filename before continuing
853      m_fullpath.substr(0, dirsep);
854
855      // if we failed to open this file, continue scanning
856      if (_7zerr != _7ZERR_NONE)
857         continue;
858
859      int fileno = -1;
860
861      // see if we can find a file with the right name and (if available) crc
862      if (m_openflags & OPEN_FLAG_HAS_CRC) fileno = _7z_search_crc_match(_7z, m_crc, filename.cstr(), filename.len(), true, true);
863
864      // if that failed, look for a file with the right crc, but the wrong filename
865      if (fileno==-1)
866         if (m_openflags & OPEN_FLAG_HAS_CRC) fileno = _7z_search_crc_match(_7z, m_crc, filename.cstr(), filename.len(), true, false);
867
868      // if that failed, look for a file with the right name; reporting a bad checksum
869      // is more helpful and less confusing than reporting "rom not found"
870      if (fileno==-1)
871         fileno = _7z_search_crc_match(_7z, m_crc, filename.cstr(), filename.len(), false, true);
872
873      if (fileno != -1)
874      {
875         m__7zfile = _7z;
876         m__7zlength = _7z->uncompressed_length;
877
878         // build a hash with just the CRC
879         m_hashes.reset();
880         m_hashes.add_crc(_7z->crc);
881         return (m_openflags & OPEN_FLAG_NO_PRELOAD) ? FILERR_NONE : load__7zped_file();
882      }
883
884      // close up the _7Z file and try the next level
885      _7z_file_close(_7z);
886   }
887}
888
889
890//-------------------------------------------------
891//  load__7zped_file - load a _7Zped file
892//-------------------------------------------------
893
894file_error emu_file::load__7zped_file()
895{
896   assert(m_file == NULL);
897   assert(m__7zdata == NULL);
898   assert(m__7zfile != NULL);
899
900   // allocate some memory
901   m__7zdata = global_alloc_array(UINT8, m__7zlength);
902
903   // read the data into our buffer and return
904   _7z_error _7zerr = _7z_file_decompress(m__7zfile, m__7zdata, m__7zlength);
905   if (_7zerr != _7ZERR_NONE)
906   {
907      global_free(m__7zdata);
908      m__7zdata = NULL;
909      return FILERR_FAILURE;
910   }
911
912   // convert to RAM file
913   file_error filerr = core_fopen_ram(m__7zdata, m__7zlength, m_openflags, &m_file);
914   if (filerr != FILERR_NONE)
915   {
916      global_free(m__7zdata);
917      m__7zdata = NULL;
918      return FILERR_FAILURE;
919   }
920
921   // close out the _7Z file
922   _7z_file_close(m__7zfile);
923   m__7zfile = NULL;
924   return FILERR_NONE;
925}
src/emu/fileio.h
r14439r14440
5858typedef struct _zip_file_header zip_file_header;
5959typedef struct _zip_file zip_file;
6060
61typedef struct __7z_file_header _7z_file_header;
62typedef struct __7z_file _7z_file;
6163
6264// ======================> path_iterator
6365
r14439r14440
162164   int printf(const char *fmt, ...);
163165
164166private:
167   bool compressed_file_ready(void);
168
165169   // internal helpers
166170   file_error attempt_zipped();
167171   file_error load_zipped_file();
168172   bool zip_filename_match(const zip_file_header &header, const astring &filename);
169173   bool zip_header_is_path(const zip_file_header &header);
170174
175   file_error attempt__7zped();
176   file_error load__7zped_file();
177
171178   // internal state
172179   astring         m_filename;                  // original filename provided
173180   astring         m_fullpath;                  // full filename
r14439r14440
176183   UINT32         m_crc;                     // iterator for paths
177184   UINT32         m_openflags;               // flags we used for the open
178185   hash_collection m_hashes;                  // collection of hashes
186
179187   zip_file *      m_zipfile;                  // ZIP file pointer
180188   UINT8 *         m_zipdata;                  // ZIP file data
181189   UINT64         m_ziplength;               // ZIP file length
190
191   _7z_file *      m__7zfile;                  // 7Z file pointer
192   UINT8 *         m__7zdata;                  // 7Z file data
193   UINT64         m__7zlength;               // 7Z file length
194
182195   bool         m_remove_on_close;            // flag: remove the file when closing
183196};
184197
src/lib/lib7z/Threads.h
r0r14440
1/* Threads.h -- multithreading library
22009-03-27 : Igor Pavlov : Public domain */
3 
4#ifndef __7Z_THREADS_H
5#define __7Z_THREADS_H
6 
7#include "Types.h"
8 
9#ifdef __cplusplus
10extern "C" {
11#endif
12 
13WRes HandlePtr_Close(HANDLE *h);
14WRes Handle_WaitObject(HANDLE h);
15 
16typedef HANDLE CThread;
17#define Thread_Construct(p) *(p) = NULL
18#define Thread_WasCreated(p) (*(p) != NULL)
19#define Thread_Close(p) HandlePtr_Close(p)
20#define Thread_Wait(p) Handle_WaitObject(*(p))
21typedef unsigned THREAD_FUNC_RET_TYPE;
22#define THREAD_FUNC_CALL_TYPE MY_STD_CALL
23#define THREAD_FUNC_DECL THREAD_FUNC_RET_TYPE THREAD_FUNC_CALL_TYPE
24typedef THREAD_FUNC_RET_TYPE (THREAD_FUNC_CALL_TYPE * THREAD_FUNC_TYPE)(void *);
25WRes Thread_Create(CThread *p, THREAD_FUNC_TYPE func, LPVOID param);
26 
27typedef HANDLE CEvent;
28typedef CEvent CAutoResetEvent;
29typedef CEvent CManualResetEvent;
30#define Event_Construct(p) *(p) = NULL
31#define Event_IsCreated(p) (*(p) != NULL)
32#define Event_Close(p) HandlePtr_Close(p)
33#define Event_Wait(p) Handle_WaitObject(*(p))
34WRes Event_Set(CEvent *p);
35WRes Event_Reset(CEvent *p);
36WRes ManualResetEvent_Create(CManualResetEvent *p, int signaled);
37WRes ManualResetEvent_CreateNotSignaled(CManualResetEvent *p);
38WRes AutoResetEvent_Create(CAutoResetEvent *p, int signaled);
39WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *p);
40 
41typedef HANDLE CSemaphore;
42#define Semaphore_Construct(p) (*p) = NULL
43#define Semaphore_Close(p) HandlePtr_Close(p)
44#define Semaphore_Wait(p) Handle_WaitObject(*(p))
45WRes Semaphore_Create(CSemaphore *p, UInt32 initCount, UInt32 maxCount);
46WRes Semaphore_ReleaseN(CSemaphore *p, UInt32 num);
47WRes Semaphore_Release1(CSemaphore *p);
48 
49typedef CRITICAL_SECTION CCriticalSection;
50WRes CriticalSection_Init(CCriticalSection *p);
51#define CriticalSection_Delete(p) DeleteCriticalSection(p)
52#define CriticalSection_Enter(p) EnterCriticalSection(p)
53#define CriticalSection_Leave(p) LeaveCriticalSection(p)
54 
55#ifdef __cplusplus
56}
57#endif
58 
59#endif
src/lib/lib7z/LzmaLib.h
r0r14440
1/* LzmaLib.h -- LZMA library interface
22009-04-07 : Igor Pavlov : Public domain */
3 
4#ifndef __LZMA_LIB_H
5#define __LZMA_LIB_H
6 
7#include "Types.h"
8 
9#ifdef __cplusplus
10extern "C" {
11#endif
12 
13#define MY_STDAPI int MY_STD_CALL
14 
15#define LZMA_PROPS_SIZE 5
16 
17/*
18RAM requirements for LZMA:
19  for compression:   (dictSize * 11.5 + 6 MB) + state_size
20  for decompression: dictSize + state_size
21    state_size = (4 + (1.5 << (lc + lp))) KB
22    by default (lc=3, lp=0), state_size = 16 KB.
23 
24LZMA properties (5 bytes) format
25    Offset Size  Description
26      0     1    lc, lp and pb in encoded form.
27      1     4    dictSize (little endian).
28*/
29 
30/*
31LzmaCompress
32------------
33 
34outPropsSize -
35     In:  the pointer to the size of outProps buffer; *outPropsSize = LZMA_PROPS_SIZE = 5.
36     Out: the pointer to the size of written properties in outProps buffer; *outPropsSize = LZMA_PROPS_SIZE = 5.
37 
38  LZMA Encoder will use defult values for any parameter, if it is
39  -1  for any from: level, loc, lp, pb, fb, numThreads
40   0  for dictSize
41   
42level - compression level: 0 <= level <= 9;
43 
44  level dictSize algo  fb
45    0:    16 KB   0    32
46    1:    64 KB   0    32
47    2:   256 KB   0    32
48    3:     1 MB   0    32
49    4:     4 MB   0    32
50    5:    16 MB   1    32
51    6:    32 MB   1    32
52    7+:   64 MB   1    64
53 
54  The default value for "level" is 5.
55 
56  algo = 0 means fast method
57  algo = 1 means normal method
58 
59dictSize - The dictionary size in bytes. The maximum value is
60        128 MB = (1 << 27) bytes for 32-bit version
61          1 GB = (1 << 30) bytes for 64-bit version
62     The default value is 16 MB = (1 << 24) bytes.
63     It's recommended to use the dictionary that is larger than 4 KB and
64     that can be calculated as (1 << N) or (3 << N) sizes.
65 
66lc - The number of literal context bits (high bits of previous literal).
67     It can be in the range from 0 to 8. The default value is 3.
68     Sometimes lc=4 gives the gain for big files.
69 
70lp - The number of literal pos bits (low bits of current position for literals).
71     It can be in the range from 0 to 4. The default value is 0.
72     The lp switch is intended for periodical data when the period is equal to 2^lp.
73     For example, for 32-bit (4 bytes) periodical data you can use lp=2. Often it's
74     better to set lc=0, if you change lp switch.
75 
76pb - The number of pos bits (low bits of current position).
77     It can be in the range from 0 to 4. The default value is 2.
78     The pb switch is intended for periodical data when the period is equal 2^pb.
79 
80fb - Word size (the number of fast bytes).
81     It can be in the range from 5 to 273. The default value is 32.
82     Usually, a big number gives a little bit better compression ratio and
83     slower compression process.
84 
85numThreads - The number of thereads. 1 or 2. The default value is 2.
86     Fast mode (algo = 0) can use only 1 thread.
87 
88Out:
89  destLen  - processed output size
90Returns:
91  SZ_OK               - OK
92  SZ_ERROR_MEM        - Memory allocation error
93  SZ_ERROR_PARAM      - Incorrect paramater
94  SZ_ERROR_OUTPUT_EOF - output buffer overflow
95  SZ_ERROR_THREAD     - errors in multithreading functions (only for Mt version)
96*/
97 
98MY_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen,
99  unsigned char *outProps, size_t *outPropsSize, /* *outPropsSize must be = 5 */
100  int level,      /* 0 <= level <= 9, default = 5 */
101  unsigned dictSize,  /* default = (1 << 24) */
102  int lc,        /* 0 <= lc <= 8, default = 3  */
103  int lp,        /* 0 <= lp <= 4, default = 0  */
104  int pb,        /* 0 <= pb <= 4, default = 2  */
105  int fb,        /* 5 <= fb <= 273, default = 32 */
106  int numThreads /* 1 or 2, default = 2 */
107  );
108 
109/*
110LzmaUncompress
111--------------
112In:
113  dest     - output data
114  destLen  - output data size
115  src      - input data
116  srcLen   - input data size
117Out:
118  destLen  - processed output size
119  srcLen   - processed input size
120Returns:
121  SZ_OK                - OK
122  SZ_ERROR_DATA        - Data error
123  SZ_ERROR_MEM         - Memory allocation arror
124  SZ_ERROR_UNSUPPORTED - Unsupported properties
125  SZ_ERROR_INPUT_EOF   - it needs more bytes in input buffer (src)
126*/
127 
128MY_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, SizeT *srcLen,
129  const unsigned char *props, size_t propsSize);
130 
131#ifdef __cplusplus
132}
133#endif
134 
135#endif
src/lib/lib7z/7zBuf.h
r0r14440
1/* 7zBuf.h -- Byte Buffer
22009-02-07 : Igor Pavlov : Public domain */
3 
4#ifndef __7Z_BUF_H
5#define __7Z_BUF_H
6 
7#include "Types.h"
8 
9#ifdef __cplusplus
10extern "C" {
11#endif
12 
13typedef struct
14{
15  Byte *data;
16  size_t size;
17} CBuf;
18 
19void Buf_Init(CBuf *p);
20int Buf_Create(CBuf *p, size_t size, ISzAlloc *alloc);
21void Buf_Free(CBuf *p, ISzAlloc *alloc);
22 
23typedef struct
24{
25  Byte *data;
26  size_t size;
27  size_t pos;
28} CDynBuf;
29 
30void DynBuf_Construct(CDynBuf *p);
31void DynBuf_SeekToBeg(CDynBuf *p);
32int DynBuf_Write(CDynBuf *p, const Byte *buf, size_t size, ISzAlloc *alloc);
33void DynBuf_Free(CDynBuf *p, ISzAlloc *alloc);
34 
35#ifdef __cplusplus
36}
37#endif
38 
39#endif
src/lib/lib7z/MtCoder.h
r0r14440
1/* MtCoder.h -- Multi-thread Coder
22009-11-19 : Igor Pavlov : Public domain */
3 
4#ifndef __MT_CODER_H
5#define __MT_CODER_H
6 
7#include "Threads.h"
8 
9EXTERN_C_BEGIN
10 
11typedef struct
12{
13  CThread thread;
14  CAutoResetEvent startEvent;
15  CAutoResetEvent finishedEvent;
16  int stop;
17   
18  THREAD_FUNC_TYPE func;
19  LPVOID param;
20  THREAD_FUNC_RET_TYPE res;
21} CLoopThread;
22 
23void LoopThread_Construct(CLoopThread *p);
24void LoopThread_Close(CLoopThread *p);
25WRes LoopThread_Create(CLoopThread *p);
26WRes LoopThread_StopAndWait(CLoopThread *p);
27WRes LoopThread_StartSubThread(CLoopThread *p);
28WRes LoopThread_WaitSubThread(CLoopThread *p);
29 
30#ifndef _7ZIP_ST
31#define NUM_MT_CODER_THREADS_MAX 32
32#else
33#define NUM_MT_CODER_THREADS_MAX 1
34#endif
35 
36typedef struct
37{
38  UInt64 totalInSize;
39  UInt64 totalOutSize;
40  ICompressProgress *progress;
41  SRes res;
42  CCriticalSection cs;
43  UInt64 inSizes[NUM_MT_CODER_THREADS_MAX];
44  UInt64 outSizes[NUM_MT_CODER_THREADS_MAX];
45} CMtProgress;
46 
47SRes MtProgress_Set(CMtProgress *p, unsigned index, UInt64 inSize, UInt64 outSize);
48 
49struct _CMtCoder;
50 
51typedef struct
52{
53  struct _CMtCoder *mtCoder;
54  Byte *outBuf;
55  size_t outBufSize;
56  Byte *inBuf;
57  size_t inBufSize;
58  unsigned index;
59  CLoopThread thread;
60 
61  Bool stopReading;
62  Bool stopWriting;
63  CAutoResetEvent canRead;
64  CAutoResetEvent canWrite;
65} CMtThread;
66 
67typedef struct
68{
69  SRes (*Code)(void *p, unsigned index, Byte *dest, size_t *destSize,
70      const Byte *src, size_t srcSize, int finished);
71} IMtCoderCallback;
72 
73typedef struct _CMtCoder
74{
75  size_t blockSize;
76  size_t destBlockSize;
77  unsigned numThreads;
78   
79  ISeqInStream *inStream;
80  ISeqOutStream *outStream;
81  ICompressProgress *progress;
82  ISzAlloc *alloc;
83 
84  IMtCoderCallback *mtCallback;
85  CCriticalSection cs;
86  SRes res;
87 
88  CMtProgress mtProgress;
89  CMtThread threads[NUM_MT_CODER_THREADS_MAX];
90} CMtCoder;
91 
92void MtCoder_Construct(CMtCoder* p);
93void MtCoder_Destruct(CMtCoder* p);
94SRes MtCoder_Code(CMtCoder *p);
95 
96EXTERN_C_END
97 
98#endif
src/lib/lib7z/Ppmd7Dec.c
r0r14440
1/* Ppmd7Dec.c -- PPMdH Decoder
22010-03-12 : Igor Pavlov : Public domain
3This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
4 
5#include "Ppmd7.h"
6 
7#define kTopValue (1 << 24)
8 
9Bool Ppmd7z_RangeDec_Init(CPpmd7z_RangeDec *p)
10{
11  unsigned i;
12  p->Code = 0;
13  p->Range = 0xFFFFFFFF;
14  if (p->Stream->Read((void *)p->Stream) != 0)
15    return False;
16  for (i = 0; i < 4; i++)
17    p->Code = (p->Code << 8) | p->Stream->Read((void *)p->Stream);
18  return (p->Code < 0xFFFFFFFF);
19}
20 
21static UInt32 Range_GetThreshold(void *pp, UInt32 total)
22{
23  CPpmd7z_RangeDec *p = (CPpmd7z_RangeDec *)pp;
24  return (p->Code) / (p->Range /= total);
25}
26 
27static void Range_Normalize(CPpmd7z_RangeDec *p)
28{
29  if (p->Range < kTopValue)
30  {
31    p->Code = (p->Code << 8) | p->Stream->Read((void *)p->Stream);
32    p->Range <<= 8;
33    if (p->Range < kTopValue)
34    {
35      p->Code = (p->Code << 8) | p->Stream->Read((void *)p->Stream);
36      p->Range <<= 8;
37    }
38  }
39}
40 
41static void Range_Decode(void *pp, UInt32 start, UInt32 size)
42{
43  CPpmd7z_RangeDec *p = (CPpmd7z_RangeDec *)pp;
44  p->Code -= start * p->Range;
45  p->Range *= size;
46  Range_Normalize(p);
47}
48 
49static UInt32 Range_DecodeBit(void *pp, UInt32 size0)
50{
51  CPpmd7z_RangeDec *p = (CPpmd7z_RangeDec *)pp;
52  UInt32 newBound = (p->Range >> 14) * size0;
53  UInt32 symbol;
54  if (p->Code < newBound)
55  {
56    symbol = 0;
57    p->Range = newBound;
58  }
59  else
60  {
61    symbol = 1;
62    p->Code -= newBound;
63    p->Range -= newBound;
64  }
65  Range_Normalize(p);
66  return symbol;
67}
68 
69void Ppmd7z_RangeDec_CreateVTable(CPpmd7z_RangeDec *p)
70{
71  p->p.GetThreshold = Range_GetThreshold;
72  p->p.Decode = Range_Decode;
73  p->p.DecodeBit = Range_DecodeBit;
74}
75 
76 
77#define MASK(sym) ((signed char *)charMask)[sym]
78 
79int Ppmd7_DecodeSymbol(CPpmd7 *p, IPpmd7_RangeDec *rc)
80{
81  size_t charMask[256 / sizeof(size_t)];
82  if (p->MinContext->NumStats != 1)
83  {
84    CPpmd_State *s = Ppmd7_GetStats(p, p->MinContext);
85    unsigned i;
86    UInt32 count, hiCnt;
87    if ((count = rc->GetThreshold(rc, p->MinContext->SummFreq)) < (hiCnt = s->Freq))
88    {
89      Byte symbol;
90      rc->Decode(rc, 0, s->Freq);
91      p->FoundState = s;
92      symbol = s->Symbol;
93      Ppmd7_Update1_0(p);
94      return symbol;
95    }
96    p->PrevSuccess = 0;
97    i = p->MinContext->NumStats - 1;
98    do
99    {
100      if ((hiCnt += (++s)->Freq) > count)
101      {
102        Byte symbol;
103        rc->Decode(rc, hiCnt - s->Freq, s->Freq);
104        p->FoundState = s;
105        symbol = s->Symbol;
106        Ppmd7_Update1(p);
107        return symbol;
108      }
109    }
110    while (--i);
111    if (count >= p->MinContext->SummFreq)
112      return -2;
113    p->HiBitsFlag = p->HB2Flag[p->FoundState->Symbol];
114    rc->Decode(rc, hiCnt, p->MinContext->SummFreq - hiCnt);
115    PPMD_SetAllBitsIn256Bytes(charMask);
116    MASK(s->Symbol) = 0;
117    i = p->MinContext->NumStats - 1;
118    do { MASK((--s)->Symbol) = 0; } while (--i);
119  }
120  else
121  {
122    UInt16 *prob = Ppmd7_GetBinSumm(p);
123    if (rc->DecodeBit(rc, *prob) == 0)
124    {
125      Byte symbol;
126      *prob = (UInt16)PPMD_UPDATE_PROB_0(*prob);
127      symbol = (p->FoundState = Ppmd7Context_OneState(p->MinContext))->Symbol;
128      Ppmd7_UpdateBin(p);
129      return symbol;
130    }
131    *prob = (UInt16)PPMD_UPDATE_PROB_1(*prob);
132    p->InitEsc = PPMD7_kExpEscape[*prob >> 10];
133    PPMD_SetAllBitsIn256Bytes(charMask);
134    MASK(Ppmd7Context_OneState(p->MinContext)->Symbol) = 0;
135    p->PrevSuccess = 0;
136  }
137  for (;;)
138  {
139    CPpmd_State *ps[256], *s;
140    UInt32 freqSum, count, hiCnt;
141    CPpmd_See *see;
142    unsigned i, num, numMasked = p->MinContext->NumStats;
143    do
144    {
145      p->OrderFall++;
146      if (!p->MinContext->Suffix)
147        return -1;
148      p->MinContext = Ppmd7_GetContext(p, p->MinContext->Suffix);
149    }
150    while (p->MinContext->NumStats == numMasked);
151    hiCnt = 0;
152    s = Ppmd7_GetStats(p, p->MinContext);
153    i = 0;
154    num = p->MinContext->NumStats - numMasked;
155    do
156    {
157      int k = (int)(MASK(s->Symbol));
158      hiCnt += (s->Freq & k);
159      ps[i] = s++;
160      i -= k;
161    }
162    while (i != num);
163     
164    see = Ppmd7_MakeEscFreq(p, numMasked, &freqSum);
165    freqSum += hiCnt;
166    count = rc->GetThreshold(rc, freqSum);
167     
168    if (count < hiCnt)
169    {
170      Byte symbol;
171      CPpmd_State **pps = ps;
172      for (hiCnt = 0; (hiCnt += (*pps)->Freq) <= count; pps++);
173      s = *pps;
174      rc->Decode(rc, hiCnt - s->Freq, s->Freq);
175      Ppmd_See_Update(see);
176      p->FoundState = s;
177      symbol = s->Symbol;
178      Ppmd7_Update2(p);
179      return symbol;
180    }
181    if (count >= freqSum)
182      return -2;
183    rc->Decode(rc, hiCnt, freqSum - hiCnt);
184    see->Summ = (UInt16)(see->Summ + freqSum);
185    do { MASK(ps[--i]->Symbol) = 0; } while (i != 0);
186  }
187}
src/lib/lib7z/RotateDefs.h
r0r14440
1/* RotateDefs.h -- Rotate functions
22009-02-07 : Igor Pavlov : Public domain */
3 
4#ifndef __ROTATE_DEFS_H
5#define __ROTATE_DEFS_H
6 
7#ifdef _MSC_VER
8 
9#include <stdlib.h>
10#define rotlFixed(x, n) _rotl((x), (n))
11#define rotrFixed(x, n) _rotr((x), (n))
12 
13#else
14 
15#define rotlFixed(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
16#define rotrFixed(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
17 
18#endif
19 
20#endif
src/lib/lib7z/Aes.c
r0r14440
1/* Aes.c -- AES encryption / decryption
22009-11-23 : Igor Pavlov : Public domain */
3 
4#include "Aes.h"
5#include "CpuArch.h"
6 
7static UInt32 T[256 * 4];
8static Byte Sbox[256] = {
9  0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
10  0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
11  0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
12  0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
13  0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
14  0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
15  0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
16  0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
17  0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
18  0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
19  0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
20  0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
21  0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
22  0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
23  0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
24  0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16};
25 
26void MY_FAST_CALL AesCbc_Encode(UInt32 *ivAes, Byte *data, size_t numBlocks);
27void MY_FAST_CALL AesCbc_Decode(UInt32 *ivAes, Byte *data, size_t numBlocks);
28void MY_FAST_CALL AesCtr_Code(UInt32 *ivAes, Byte *data, size_t numBlocks);
29 
30void MY_FAST_CALL AesCbc_Encode_Intel(UInt32 *ivAes, Byte *data, size_t numBlocks);
31void MY_FAST_CALL AesCbc_Decode_Intel(UInt32 *ivAes, Byte *data, size_t numBlocks);
32void MY_FAST_CALL AesCtr_Code_Intel(UInt32 *ivAes, Byte *data, size_t numBlocks);
33 
34AES_CODE_FUNC g_AesCbc_Encode;
35AES_CODE_FUNC g_AesCbc_Decode;
36AES_CODE_FUNC g_AesCtr_Code;
37 
38static UInt32 D[256 * 4];
39static Byte InvS[256];
40 
41static Byte Rcon[11] = { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 };
42 
43#define xtime(x) ((((x) << 1) ^ (((x) & 0x80) != 0 ? 0x1B : 0)) & 0xFF)
44 
45#define Ui32(a0, a1, a2, a3) ((UInt32)(a0) | ((UInt32)(a1) << 8) | ((UInt32)(a2) << 16) | ((UInt32)(a3) << 24))
46 
47#define gb0(x) ( (x)          & 0xFF)
48#define gb1(x) (((x) >> ( 8)) & 0xFF)
49#define gb2(x) (((x) >> (16)) & 0xFF)
50#define gb3(x) (((x) >> (24)) & 0xFF)
51 
52void AesGenTables(void)
53{
54  unsigned i;
55  for (i = 0; i < 256; i++)
56    InvS[Sbox[i]] = (Byte)i;
57  for (i = 0; i < 256; i++)
58  {
59    {
60      UInt32 a1 = Sbox[i];
61      UInt32 a2 = xtime(a1);
62      UInt32 a3 = a2 ^ a1;
63      T[        i] = Ui32(a2, a1, a1, a3);
64      T[0x100 + i] = Ui32(a3, a2, a1, a1);
65      T[0x200 + i] = Ui32(a1, a3, a2, a1);
66      T[0x300 + i] = Ui32(a1, a1, a3, a2);
67    }
68    {
69      UInt32 a1 = InvS[i];
70      UInt32 a2 = xtime(a1);
71      UInt32 a4 = xtime(a2);
72      UInt32 a8 = xtime(a4);
73      UInt32 a9 = a8 ^ a1;
74      UInt32 aB = a8 ^ a2 ^ a1;
75      UInt32 aD = a8 ^ a4 ^ a1;
76      UInt32 aE = a8 ^ a4 ^ a2;
77      D[        i] = Ui32(aE, a9, aD, aB);
78      D[0x100 + i] = Ui32(aB, aE, a9, aD);
79      D[0x200 + i] = Ui32(aD, aB, aE, a9);
80      D[0x300 + i] = Ui32(a9, aD, aB, aE);
81    }
82  }
83  g_AesCbc_Encode = AesCbc_Encode;
84  g_AesCbc_Decode = AesCbc_Decode;
85  g_AesCtr_Code = AesCtr_Code;
86  #ifdef MY_CPU_X86_OR_AMD64
87  if (CPU_Is_Aes_Supported())
88  {
89    g_AesCbc_Encode = AesCbc_Encode_Intel;
90    g_AesCbc_Decode = AesCbc_Decode_Intel;
91    g_AesCtr_Code = AesCtr_Code_Intel;
92  }
93  #endif
94}
95 
96#define HT(i, x, s) (T + (x << 8))[gb ## x(s[(i + x) & 3])]
97#define HT4(m, i, s, p) m[i] = \
98    HT(i, 0, s) ^ \
99    HT(i, 1, s) ^ \
100    HT(i, 2, s) ^ \
101    HT(i, 3, s) ^ w[p + i]
102/* such order (2031) in HT16 is for VC6/K8 speed optimization) */
103#define HT16(m, s, p) \
104    HT4(m, 2, s, p); \
105    HT4(m, 0, s, p); \
106    HT4(m, 3, s, p); \
107    HT4(m, 1, s, p); \
108 
109#define FT(i, x) Sbox[gb ## x(m[(i + x) & 3])]
110#define FT4(i) dest[i] = Ui32(FT(i, 0), FT(i, 1), FT(i, 2), FT(i, 3)) ^ w[i];
111 
112#define HD(i, x, s) (D + (x << 8))[gb ## x(s[(i - x) & 3])]
113#define HD4(m, i, s, p) m[i] = \
114    HD(i, 0, s) ^ \
115    HD(i, 1, s) ^ \
116    HD(i, 2, s) ^ \
117    HD(i, 3, s) ^ w[p + i];
118/* such order (0231) in HD16 is for VC6/K8 speed optimization) */
119#define HD16(m, s, p) \
120    HD4(m, 0, s, p); \
121    HD4(m, 2, s, p); \
122    HD4(m, 3, s, p); \
123    HD4(m, 1, s, p); \
124 
125#define FD(i, x) InvS[gb ## x(m[(i - x) & 3])]
126#define FD4(i) dest[i] = Ui32(FD(i, 0), FD(i, 1), FD(i, 2), FD(i, 3)) ^ w[i];
127 
128void MY_FAST_CALL Aes_SetKey_Enc(UInt32 *w, const Byte *key, unsigned keySize)
129{
130  unsigned i, wSize;
131  wSize = keySize + 28;
132  keySize /= 4;
133  w[0] = ((UInt32)keySize / 2) + 3;
134  w += 4;
135 
136  for (i = 0; i < keySize; i++, key += 4)
137    w[i] = GetUi32(key);
138 
139  for (; i < wSize; i++)
140  {
141    UInt32 t = w[i - 1];
142    unsigned rem = i % keySize;
143    if (rem == 0)
144      t = Ui32(Sbox[gb1(t)] ^ Rcon[i / keySize], Sbox[gb2(t)], Sbox[gb3(t)], Sbox[gb0(t)]);
145    else if (keySize > 6 && rem == 4)
146      t = Ui32(Sbox[gb0(t)], Sbox[gb1(t)], Sbox[gb2(t)], Sbox[gb3(t)]);
147    w[i] = w[i - keySize] ^ t;
148  }
149}
150 
151void MY_FAST_CALL Aes_SetKey_Dec(UInt32 *w, const Byte *key, unsigned keySize)
152{
153  unsigned i, num;
154  Aes_SetKey_Enc(w, key, keySize);
155  num = keySize + 20;
156  w += 8;
157  for (i = 0; i < num; i++)
158  {
159    UInt32 r = w[i];
160    w[i] =
161      D[        Sbox[gb0(r)]] ^
162      D[0x100 + Sbox[gb1(r)]] ^
163      D[0x200 + Sbox[gb2(r)]] ^
164      D[0x300 + Sbox[gb3(r)]];
165  }
166}
167 
168/* Aes_Encode and Aes_Decode functions work with little-endian words.
169  src and dest are pointers to 4 UInt32 words.
170  arc and dest can point to same block */
171 
172static void Aes_Encode(const UInt32 *w, UInt32 *dest, const UInt32 *src)
173{
174  UInt32 s[4];
175  UInt32 m[4];
176  UInt32 numRounds2 = w[0];
177  w += 4;
178  s[0] = src[0] ^ w[0];
179  s[1] = src[1] ^ w[1];
180  s[2] = src[2] ^ w[2];
181  s[3] = src[3] ^ w[3];
182  w += 4;
183  for (;;)
184  {
185    HT16(m, s, 0);
186    if (--numRounds2 == 0)
187      break;
188    HT16(s, m, 4);
189    w += 8;
190  }
191  w += 4;
192  FT4(0); FT4(1); FT4(2); FT4(3);
193}
194 
195static void Aes_Decode(const UInt32 *w, UInt32 *dest, const UInt32 *src)
196{
197  UInt32 s[4];
198  UInt32 m[4];
199  UInt32 numRounds2 = w[0];
200  w += 4 + numRounds2 * 8;
201  s[0] = src[0] ^ w[0];
202  s[1] = src[1] ^ w[1];
203  s[2] = src[2] ^ w[2];
204  s[3] = src[3] ^ w[3];
205  for (;;)
206  {
207    w -= 8;
208    HD16(m, s, 4);
209    if (--numRounds2 == 0)
210      break;
211    HD16(s, m, 0);
212  }
213  FD4(0); FD4(1); FD4(2); FD4(3);
214}
215 
216void AesCbc_Init(UInt32 *p, const Byte *iv)
217{
218  unsigned i;
219  for (i = 0; i < 4; i++)
220    p[i] = GetUi32(iv + i * 4);
221}
222 
223void MY_FAST_CALL AesCbc_Encode(UInt32 *p, Byte *data, size_t numBlocks)
224{
225  for (; numBlocks != 0; numBlocks--, data += AES_BLOCK_SIZE)
226  {
227    p[0] ^= GetUi32(data);
228    p[1] ^= GetUi32(data + 4);
229    p[2] ^= GetUi32(data + 8);
230    p[3] ^= GetUi32(data + 12);
231     
232    Aes_Encode(p + 4, p, p);
233     
234    SetUi32(data,      p[0]);
235    SetUi32(data + 4,  p[1]);
236    SetUi32(data + 8,  p[2]);
237    SetUi32(data + 12, p[3]);
238  }
239}
240 
241void MY_FAST_CALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks)
242{
243  UInt32 in[4], out[4];
244  for (; numBlocks != 0; numBlocks--, data += AES_BLOCK_SIZE)
245  {
246    in[0] = GetUi32(data);
247    in[1] = GetUi32(data + 4);
248    in[2] = GetUi32(data + 8);
249    in[3] = GetUi32(data + 12);
250 
251    Aes_Decode(p + 4, out, in);
252 
253    SetUi32(data,      p[0] ^ out[0]);
254    SetUi32(data + 4,  p[1] ^ out[1]);
255    SetUi32(data + 8,  p[2] ^ out[2]);
256    SetUi32(data + 12, p[3] ^ out[3]);
257     
258    p[0] = in[0];
259    p[1] = in[1];
260    p[2] = in[2];
261    p[3] = in[3];
262  }
263}
264 
265void MY_FAST_CALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks)
266{
267  for (; numBlocks != 0; numBlocks--)
268  {
269    UInt32 temp[4];
270    Byte buf[16];
271    int i;
272    if (++p[0] == 0)
273      p[1]++;
274    Aes_Encode(p + 4, temp, p);
275    SetUi32(buf,      temp[0]);
276    SetUi32(buf + 4,  temp[1]);
277    SetUi32(buf + 8,  temp[2]);
278    SetUi32(buf + 12, temp[3]);
279    for (i = 0; i < 16; i++)
280      *data++ ^= buf[i];
281  }
282}
src/lib/lib7z/Lzma2Enc.c
r0r14440
1/* Lzma2Enc.c -- LZMA2 Encoder
22010-09-24 : Igor Pavlov : Public domain */
3 
4/* #include <stdio.h> */
5#include <string.h>
6 
7/* #define _7ZIP_ST */
8 
9#include "Lzma2Enc.h"
10 
11#ifndef _7ZIP_ST
12#include "MtCoder.h"
13#else
14#define NUM_MT_CODER_THREADS_MAX 1
15#endif
16 
17#define LZMA2_CONTROL_LZMA (1 << 7)
18#define LZMA2_CONTROL_COPY_NO_RESET 2
19#define LZMA2_CONTROL_COPY_RESET_DIC 1
20#define LZMA2_CONTROL_EOF 0
21 
22#define LZMA2_LCLP_MAX 4
23 
24#define LZMA2_DIC_SIZE_FROM_PROP(p) (((UInt32)2 | ((p) & 1)) << ((p) / 2 + 11))
25 
26#define LZMA2_PACK_SIZE_MAX (1 << 16)
27#define LZMA2_COPY_CHUNK_SIZE LZMA2_PACK_SIZE_MAX
28#define LZMA2_UNPACK_SIZE_MAX (1 << 21)
29#define LZMA2_KEEP_WINDOW_SIZE LZMA2_UNPACK_SIZE_MAX
30 
31#define LZMA2_CHUNK_SIZE_COMPRESSED_MAX ((1 << 16) + 16)
32 
33 
34#define PRF(x) /* x */
35 
36/* ---------- CLzma2EncInt ---------- */
37 
38typedef struct
39{
40  CLzmaEncHandle enc;
41  UInt64 srcPos;
42  Byte props;
43  Bool needInitState;
44  Bool needInitProp;
45} CLzma2EncInt;
46 
47static SRes Lzma2EncInt_Init(CLzma2EncInt *p, const CLzma2EncProps *props)
48{
49  Byte propsEncoded[LZMA_PROPS_SIZE];
50  SizeT propsSize = LZMA_PROPS_SIZE;
51  RINOK(LzmaEnc_SetProps(p->enc, &props->lzmaProps));
52  RINOK(LzmaEnc_WriteProperties(p->enc, propsEncoded, &propsSize));
53  p->srcPos = 0;
54  p->props = propsEncoded[0];
55  p->needInitState = True;
56  p->needInitProp = True;
57  return SZ_OK;
58}
59 
60SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp, ISeqInStream *inStream, UInt32 keepWindowSize,
61    ISzAlloc *alloc, ISzAlloc *allocBig);
62SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen,
63    UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig);
64SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, Bool reInit,
65    Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize);
66const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp);
67void LzmaEnc_Finish(CLzmaEncHandle pp);
68void LzmaEnc_SaveState(CLzmaEncHandle pp);
69void LzmaEnc_RestoreState(CLzmaEncHandle pp);
70 
71 
72static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf,
73    size_t *packSizeRes, ISeqOutStream *outStream)
74{
75  size_t packSizeLimit = *packSizeRes;
76  size_t packSize = packSizeLimit;
77  UInt32 unpackSize = LZMA2_UNPACK_SIZE_MAX;
78  unsigned lzHeaderSize = 5 + (p->needInitProp ? 1 : 0);
79  Bool useCopyBlock;
80  SRes res;
81 
82  *packSizeRes = 0;
83  if (packSize < lzHeaderSize)
84    return SZ_ERROR_OUTPUT_EOF;
85  packSize -= lzHeaderSize;
86   
87  LzmaEnc_SaveState(p->enc);
88  res = LzmaEnc_CodeOneMemBlock(p->enc, p->needInitState,
89      outBuf + lzHeaderSize, &packSize, LZMA2_PACK_SIZE_MAX, &unpackSize);
90   
91  PRF(printf("\npackSize = %7d unpackSize = %7d  ", packSize, unpackSize));
92 
93  if (unpackSize == 0)
94    return res;
95 
96  if (res == SZ_OK)
97    useCopyBlock = (packSize + 2 >= unpackSize || packSize > (1 << 16));
98  else
99  {
100    if (res != SZ_ERROR_OUTPUT_EOF)
101      return res;
102    res = SZ_OK;
103    useCopyBlock = True;
104  }
105 
106  if (useCopyBlock)
107  {
108    size_t destPos = 0;
109    PRF(printf("################# COPY           "));
110    while (unpackSize > 0)
111    {
112      UInt32 u = (unpackSize < LZMA2_COPY_CHUNK_SIZE) ? unpackSize : LZMA2_COPY_CHUNK_SIZE;
113      if (packSizeLimit - destPos < u + 3)
114        return SZ_ERROR_OUTPUT_EOF;
115      outBuf[destPos++] = (Byte)(p->srcPos == 0 ? LZMA2_CONTROL_COPY_RESET_DIC : LZMA2_CONTROL_COPY_NO_RESET);
116      outBuf[destPos++] = (Byte)((u - 1) >> 8);
117      outBuf[destPos++] = (Byte)(u - 1);
118      memcpy(outBuf + destPos, LzmaEnc_GetCurBuf(p->enc) - unpackSize, u);
119      unpackSize -= u;
120      destPos += u;
121      p->srcPos += u;
122      if (outStream)
123      {
124        *packSizeRes += destPos;
125        if (outStream->Write(outStream, outBuf, destPos) != destPos)
126          return SZ_ERROR_WRITE;
127        destPos = 0;
128      }
129      else
130        *packSizeRes = destPos;
131      /* needInitState = True; */
132    }
133    LzmaEnc_RestoreState(p->enc);
134    return SZ_OK;
135  }
136  {
137    size_t destPos = 0;
138    UInt32 u = unpackSize - 1;
139    UInt32 pm = (UInt32)(packSize - 1);
140    unsigned mode = (p->srcPos == 0) ? 3 : (p->needInitState ? (p->needInitProp ? 2 : 1) : 0);
141 
142    PRF(printf("               "));
143 
144    outBuf[destPos++] = (Byte)(LZMA2_CONTROL_LZMA | (mode << 5) | ((u >> 16) & 0x1F));
145    outBuf[destPos++] = (Byte)(u >> 8);
146    outBuf[destPos++] = (Byte)u;
147    outBuf[destPos++] = (Byte)(pm >> 8);
148    outBuf[destPos++] = (Byte)pm;
149     
150    if (p->needInitProp)
151      outBuf[destPos++] = p->props;
152     
153    p->needInitProp = False;
154    p->needInitState = False;
155    destPos += packSize;
156    p->srcPos += unpackSize;
157 
158    if (outStream)
159      if (outStream->Write(outStream, outBuf, destPos) != destPos)
160        return SZ_ERROR_WRITE;
161    *packSizeRes = destPos;
162    return SZ_OK;
163  }
164}
165 
166/* ---------- Lzma2 Props ---------- */
167 
168void Lzma2EncProps_Init(CLzma2EncProps *p)
169{
170  LzmaEncProps_Init(&p->lzmaProps);
171  p->numTotalThreads = -1;
172  p->numBlockThreads = -1;
173  p->blockSize = 0;
174}
175 
176void Lzma2EncProps_Normalize(CLzma2EncProps *p)
177{
178  int t1, t1n, t2, t3;
179  {
180    CLzmaEncProps lzmaProps = p->lzmaProps;
181    LzmaEncProps_Normalize(&lzmaProps);
182    t1n = lzmaProps.numThreads;
183  }
184 
185  t1 = p->lzmaProps.numThreads;
186  t2 = p->numBlockThreads;
187  t3 = p->numTotalThreads;
188 
189  if (t2 > NUM_MT_CODER_THREADS_MAX)
190    t2 = NUM_MT_CODER_THREADS_MAX;
191 
192  if (t3 <= 0)
193  {
194    if (t2 <= 0)
195      t2 = 1;
196    t3 = t1n * t2;
197  }
198  else if (t2 <= 0)
199  {
200    t2 = t3 / t1n;
201    if (t2 == 0)
202    {
203      t1 = 1;
204      t2 = t3;
205    }
206    if (t2 > NUM_MT_CODER_THREADS_MAX)
207      t2 = NUM_MT_CODER_THREADS_MAX;
208  }
209  else if (t1 <= 0)
210  {
211    t1 = t3 / t2;
212    if (t1 == 0)
213      t1 = 1;
214  }
215  else
216    t3 = t1n * t2;
217 
218  p->lzmaProps.numThreads = t1;
219  p->numBlockThreads = t2;
220  p->numTotalThreads = t3;
221  LzmaEncProps_Normalize(&p->lzmaProps);
222 
223  if (p->blockSize == 0)
224  {
225    UInt32 dictSize = p->lzmaProps.dictSize;
226    UInt64 blockSize = (UInt64)dictSize << 2;
227    const UInt32 kMinSize = (UInt32)1 << 20;
228    const UInt32 kMaxSize = (UInt32)1 << 28;
229    if (blockSize < kMinSize) blockSize = kMinSize;
230    if (blockSize > kMaxSize) blockSize = kMaxSize;
231    if (blockSize < dictSize) blockSize = dictSize;
232    p->blockSize = (size_t)blockSize;
233  }
234}
235 
236static SRes Progress(ICompressProgress *p, UInt64 inSize, UInt64 outSize)
237{
238  return (p && p->Progress(p, inSize, outSize) != SZ_OK) ? SZ_ERROR_PROGRESS : SZ_OK;
239}
240 
241/* ---------- Lzma2 ---------- */
242 
243typedef struct
244{
245  Byte propEncoded;
246  CLzma2EncProps props;
247   
248  Byte *outBuf;
249 
250  ISzAlloc *alloc;
251  ISzAlloc *allocBig;
252 
253  CLzma2EncInt coders[NUM_MT_CODER_THREADS_MAX];
254 
255  #ifndef _7ZIP_ST
256  CMtCoder mtCoder;
257  #endif
258 
259} CLzma2Enc;
260 
261 
262/* ---------- Lzma2EncThread ---------- */
263 
264static SRes Lzma2Enc_EncodeMt1(CLzma2EncInt *p, CLzma2Enc *mainEncoder,
265  ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress)
266{
267  UInt64 packTotal = 0;
268  SRes res = SZ_OK;
269 
270  if (mainEncoder->outBuf == 0)
271  {
272    mainEncoder->outBuf = (Byte *)IAlloc_Alloc(mainEncoder->alloc, LZMA2_CHUNK_SIZE_COMPRESSED_MAX);
273    if (mainEncoder->outBuf == 0)
274      return SZ_ERROR_MEM;
275  }
276  RINOK(Lzma2EncInt_Init(p, &mainEncoder->props));
277  RINOK(LzmaEnc_PrepareForLzma2(p->enc, inStream, LZMA2_KEEP_WINDOW_SIZE,
278      mainEncoder->alloc, mainEncoder->allocBig));
279  for (;;)
280  {
281    size_t packSize = LZMA2_CHUNK_SIZE_COMPRESSED_MAX;
282    res = Lzma2EncInt_EncodeSubblock(p, mainEncoder->outBuf, &packSize, outStream);
283    if (res != SZ_OK)
284      break;
285    packTotal += packSize;
286    res = Progress(progress, p->srcPos, packTotal);
287    if (res != SZ_OK)
288      break;
289    if (packSize == 0)
290      break;
291  }
292  LzmaEnc_Finish(p->enc);
293  if (res == SZ_OK)
294  {
295    Byte b = 0;
296    if (outStream->Write(outStream, &b, 1) != 1)
297      return SZ_ERROR_WRITE;
298  }
299  return res;
300}
301 
302#ifndef _7ZIP_ST
303 
304typedef struct
305{
306  IMtCoderCallback funcTable;
307  CLzma2Enc *lzma2Enc;
308} CMtCallbackImp;
309 
310static SRes MtCallbackImp_Code(void *pp, unsigned index, Byte *dest, size_t *destSize,
311      const Byte *src, size_t srcSize, int finished)
312{
313  CMtCallbackImp *imp = (CMtCallbackImp *)pp;
314  CLzma2Enc *mainEncoder = imp->lzma2Enc;
315  CLzma2EncInt *p = &mainEncoder->coders[index];
316 
317  SRes res = SZ_OK;
318  {
319    size_t destLim = *destSize;
320    *destSize = 0;
321 
322    if (srcSize != 0)
323    {
324      RINOK(Lzma2EncInt_Init(p, &mainEncoder->props));
325     
326      RINOK(LzmaEnc_MemPrepare(p->enc, src, srcSize, LZMA2_KEEP_WINDOW_SIZE,
327          mainEncoder->alloc, mainEncoder->allocBig));
328     
329      while (p->srcPos < srcSize)
330      {
331        size_t packSize = destLim - *destSize;
332        res = Lzma2EncInt_EncodeSubblock(p, dest + *destSize, &packSize, NULL);
333        if (res != SZ_OK)
334          break;
335        *destSize += packSize;
336 
337        if (packSize == 0)
338        {
339          res = SZ_ERROR_FAIL;
340          break;
341        }
342 
343        if (MtProgress_Set(&mainEncoder->mtCoder.mtProgress, index, p->srcPos, *destSize) != SZ_OK)
344        {
345          res = SZ_ERROR_PROGRESS;
346          break;
347        }
348      }
349      LzmaEnc_Finish(p->enc);
350      if (res != SZ_OK)
351        return res;
352    }
353    if (finished)
354    {
355      if (*destSize == destLim)
356        return SZ_ERROR_OUTPUT_EOF;
357      dest[(*destSize)++] = 0;
358    }
359  }
360  return res;
361}
362 
363#endif
364 
365/* ---------- Lzma2Enc ---------- */
366 
367CLzma2EncHandle Lzma2Enc_Create(ISzAlloc *alloc, ISzAlloc *allocBig)
368{
369  CLzma2Enc *p = (CLzma2Enc *)alloc->Alloc(alloc, sizeof(CLzma2Enc));
370  if (p == 0)
371    return NULL;
372  Lzma2EncProps_Init(&p->props);
373  Lzma2EncProps_Normalize(&p->props);
374  p->outBuf = 0;
375  p->alloc = alloc;
376  p->allocBig = allocBig;
377  {
378    unsigned i;
379    for (i = 0; i < NUM_MT_CODER_THREADS_MAX; i++)
380      p->coders[i].enc = 0;
381  }
382  #ifndef _7ZIP_ST
383  MtCoder_Construct(&p->mtCoder);
384  #endif
385 
386  return p;
387}
388 
389void Lzma2Enc_Destroy(CLzma2EncHandle pp)
390{
391  CLzma2Enc *p = (CLzma2Enc *)pp;
392  unsigned i;
393  for (i = 0; i < NUM_MT_CODER_THREADS_MAX; i++)
394  {
395    CLzma2EncInt *t = &p->coders[i];
396    if (t->enc)
397    {
398      LzmaEnc_Destroy(t->enc, p->alloc, p->allocBig);
399      t->enc = 0;
400    }
401  }
402 
403  #ifndef _7ZIP_ST
404  MtCoder_Destruct(&p->mtCoder);
405  #endif
406 
407  IAlloc_Free(p->alloc, p->outBuf);
408  IAlloc_Free(p->alloc, pp);
409}
410 
411SRes Lzma2Enc_SetProps(CLzma2EncHandle pp, const CLzma2EncProps *props)
412{
413  CLzma2Enc *p = (CLzma2Enc *)pp;
414  CLzmaEncProps lzmaProps = props->lzmaProps;
415  LzmaEncProps_Normalize(&lzmaProps);
416  if (lzmaProps.lc + lzmaProps.lp > LZMA2_LCLP_MAX)
417    return SZ_ERROR_PARAM;
418  p->props = *props;
419  Lzma2EncProps_Normalize(&p->props);
420  return SZ_OK;
421}
422 
423Byte Lzma2Enc_WriteProperties(CLzma2EncHandle pp)
424{
425  CLzma2Enc *p = (CLzma2Enc *)pp;
426  unsigned i;
427  UInt32 dicSize = LzmaEncProps_GetDictSize(&p->props.lzmaProps);
428  for (i = 0; i < 40; i++)
429    if (dicSize <= LZMA2_DIC_SIZE_FROM_PROP(i))
430      break;
431  return (Byte)i;
432}
433 
434SRes Lzma2Enc_Encode(CLzma2EncHandle pp,
435    ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress)
436{
437  CLzma2Enc *p = (CLzma2Enc *)pp;
438  int i;
439 
440  for (i = 0; i < p->props.numBlockThreads; i++)
441  {
442    CLzma2EncInt *t = &p->coders[i];
443    if (t->enc == NULL)
444    {
445      t->enc = LzmaEnc_Create(p->alloc);
446      if (t->enc == NULL)
447        return SZ_ERROR_MEM;
448    }
449  }
450 
451  #ifndef _7ZIP_ST
452  if (p->props.numBlockThreads <= 1)
453  #endif
454    return Lzma2Enc_EncodeMt1(&p->coders[0], p, outStream, inStream, progress);
455 
456  #ifndef _7ZIP_ST
457 
458  {
459    CMtCallbackImp mtCallback;
460 
461    mtCallback.funcTable.Code = MtCallbackImp_Code;
462    mtCallback.lzma2Enc = p;
463     
464    p->mtCoder.progress = progress;
465    p->mtCoder.inStream = inStream;
466    p->mtCoder.outStream = outStream;
467    p->mtCoder.alloc = p->alloc;
468    p->mtCoder.mtCallback = &mtCallback.funcTable;
469 
470    p->mtCoder.blockSize = p->props.blockSize;
471    p->mtCoder.destBlockSize = p->props.blockSize + (p->props.blockSize >> 10) + 16;
472    p->mtCoder.numThreads = p->props.numBlockThreads;
473     
474    return MtCoder_Code(&p->mtCoder);
475  }
476  #endif
477}
src/lib/lib7z/XzDec.c
r0r14440
1/* XzDec.c -- Xz Decode
22011-02-07 : Igor Pavlov : Public domain */
3 
4/* #define XZ_DUMP */
5 
6#ifdef XZ_DUMP
7#include <stdio.h>
8#endif
9 
10#include <stdlib.h>
11#include <string.h>
12 
13#include "7zCrc.h"
14#include "Alloc.h"
15#include "Bra.h"
16#include "CpuArch.h"
17#include "Delta.h"
18#include "Lzma2Dec.h"
19 
20#ifdef USE_SUBBLOCK
21#include "Bcj3Dec.c"
22#include "SbDec.c"
23#endif
24 
25#include "Xz.h"
26 
27#define XZ_CHECK_SIZE_MAX 64
28 
29#define CODER_BUF_SIZE (1 << 17)
30 
31unsigned Xz_ReadVarInt(const Byte *p, size_t maxSize, UInt64 *value)
32{
33  int i, limit;
34  *value = 0;
35  limit = (maxSize > 9) ? 9 : (int)maxSize;
36 
37  for (i = 0; i < limit;)
38  {
39    Byte b = p[i];
40    *value |= (UInt64)(b & 0x7F) << (7 * i++);
41    if ((b & 0x80) == 0)
42      return (b == 0 && i != 1) ? 0 : i;
43  }
44  return 0;
45}
46 
47/* ---------- BraState ---------- */
48 
49#define BRA_BUF_SIZE (1 << 14)
50 
51typedef struct
52{
53  size_t bufPos;
54  size_t bufConv;
55  size_t bufTotal;
56 
57  UInt32 methodId;
58  int encodeMode;
59  UInt32 delta;
60  UInt32 ip;
61  UInt32 x86State;
62  Byte deltaState[DELTA_STATE_SIZE];
63 
64  Byte buf[BRA_BUF_SIZE];
65} CBraState;
66 
67void BraState_Free(void *pp, ISzAlloc *alloc)
68{
69  alloc->Free(alloc, pp);
70}
71 
72SRes BraState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAlloc *alloc)
73{
74  CBraState *p = ((CBraState *)pp);
75  alloc = alloc;
76  p->ip = 0;
77  if (p->methodId == XZ_ID_Delta)
78  {
79    if (propSize != 1)
80      return SZ_ERROR_UNSUPPORTED;
81    p->delta = (unsigned)props[0] + 1;
82  }
83  else
84  {
85    if (propSize == 4)
86    {
87      UInt32 v = GetUi32(props);
88      switch(p->methodId)
89      {
90        case XZ_ID_PPC:
91        case XZ_ID_ARM:
92        case XZ_ID_SPARC:
93          if ((v & 3) != 0)
94            return SZ_ERROR_UNSUPPORTED;
95          break;
96        case XZ_ID_ARMT:
97          if ((v & 1) != 0)
98            return SZ_ERROR_UNSUPPORTED;
99          break;
100        case XZ_ID_IA64:
101          if ((v & 0xF) != 0)
102            return SZ_ERROR_UNSUPPORTED;
103          break;
104      }
105      p->ip = v;
106    }
107    else if (propSize != 0)
108      return SZ_ERROR_UNSUPPORTED;
109  }
110  return SZ_OK;
111}
112 
113void BraState_Init(void *pp)
114{
115  CBraState *p = ((CBraState *)pp);
116  p->bufPos = p->bufConv = p->bufTotal = 0;
117  x86_Convert_Init(p->x86State);
118  if (p->methodId == XZ_ID_Delta)
119    Delta_Init(p->deltaState);
120}
121 
122#define CASE_BRA_CONV(isa) case XZ_ID_ ## isa: p->bufConv = isa ## _Convert(p->buf, p->bufTotal, p->ip, p->encodeMode); break;
123 
124static SRes BraState_Code(void *pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
125    int srcWasFinished, ECoderFinishMode finishMode, int *wasFinished)
126{
127  CBraState *p = ((CBraState *)pp);
128  SizeT destLenOrig = *destLen;
129  SizeT srcLenOrig = *srcLen;
130  *destLen = 0;
131  *srcLen = 0;
132  finishMode = finishMode;
133  *wasFinished = 0;
134  while (destLenOrig > 0)
135  {
136    if (p->bufPos != p->bufConv)
137    {
138      size_t curSize = p->bufConv - p->bufPos;
139      if (curSize > destLenOrig)
140        curSize = destLenOrig;
141      memcpy(dest, p->buf + p->bufPos, curSize);
142      p->bufPos += curSize;
143      *destLen += curSize;
144      dest += curSize;
145      destLenOrig -= curSize;
146      continue;
147    }
148    p->bufTotal -= p->bufPos;
149    memmove(p->buf, p->buf + p->bufPos, p->bufTotal);
150    p->bufPos = 0;
151    p->bufConv = 0;
152    {
153      size_t curSize = BRA_BUF_SIZE - p->bufTotal;
154      if (curSize > srcLenOrig)
155        curSize = srcLenOrig;
156      memcpy(p->buf + p->bufTotal, src, curSize);
157      *srcLen += curSize;
158      src += curSize;
159      srcLenOrig -= curSize;
160      p->bufTotal += curSize;
161    }
162    if (p->bufTotal == 0)
163      break;
164    switch(p->methodId)
165    {
166      case XZ_ID_Delta:
167        if (p->encodeMode)
168          Delta_Encode(p->deltaState, p->delta, p->buf, p->bufTotal);
169        else
170          Delta_Decode(p->deltaState, p->delta, p->buf, p->bufTotal);
171        p->bufConv = p->bufTotal;
172        break;
173      case XZ_ID_X86:
174        p->bufConv = x86_Convert(p->buf, p->bufTotal, p->ip, &p->x86State, p->encodeMode);
175        break;
176      CASE_BRA_CONV(PPC)
177      CASE_BRA_CONV(IA64)
178      CASE_BRA_CONV(ARM)
179      CASE_BRA_CONV(ARMT)
180      CASE_BRA_CONV(SPARC)
181      default:
182        return SZ_ERROR_UNSUPPORTED;
183    }
184    p->ip += (UInt32)p->bufConv;
185 
186    if (p->bufConv == 0)
187    {
188      if (!srcWasFinished)
189        break;
190      p->bufConv = p->bufTotal;
191    }
192  }
193  if (p->bufTotal == p->bufPos && srcLenOrig == 0 && srcWasFinished)
194    *wasFinished = 1;
195  return SZ_OK;
196}
197 
198SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, int encodeMode, ISzAlloc *alloc)
199{
200  CBraState *decoder;
201  if (id != XZ_ID_Delta &&
202      id != XZ_ID_X86 &&
203      id != XZ_ID_PPC &&
204      id != XZ_ID_IA64 &&
205      id != XZ_ID_ARM &&
206      id != XZ_ID_ARMT &&
207      id != XZ_ID_SPARC)
208    return SZ_ERROR_UNSUPPORTED;
209  p->p = 0;
210  decoder = alloc->Alloc(alloc, sizeof(CBraState));
211  if (decoder == 0)
212    return SZ_ERROR_MEM;
213  decoder->methodId = (UInt32)id;
214  decoder->encodeMode = encodeMode;
215  p->p = decoder;
216  p->Free = BraState_Free;
217  p->SetProps = BraState_SetProps;
218  p->Init = BraState_Init;
219  p->Code = BraState_Code;
220  return SZ_OK;
221}
222 
223/* ---------- SbState ---------- */
224 
225#ifdef USE_SUBBLOCK
226 
227static void SbState_Free(void *pp, ISzAlloc *alloc)
228{
229  CSbDec *p = (CSbDec *)pp;
230  SbDec_Free(p);
231  alloc->Free(alloc, pp);
232}
233 
234static SRes SbState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAlloc *alloc)
235{
236  pp = pp;
237  props = props;
238  alloc = alloc;
239  return (propSize == 0) ? SZ_OK : SZ_ERROR_UNSUPPORTED;
240}
241 
242static void SbState_Init(void *pp)
243{
244  SbDec_Init((CSbDec *)pp);
245}
246 
247static SRes SbState_Code(void *pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
248    int srcWasFinished, ECoderFinishMode finishMode, int *wasFinished)
249{
250  CSbDec *p = (CSbDec *)pp;
251  SRes res;
252  srcWasFinished = srcWasFinished;
253  p->dest = dest;
254  p->destLen = *destLen;
255  p->src = src;
256  p->srcLen = *srcLen;
257  p->finish = finishMode; /* change it */
258  res = SbDec_Decode((CSbDec *)pp);
259  *destLen -= p->destLen;
260  *srcLen -= p->srcLen;
261  *wasFinished = (*destLen == 0 && *srcLen == 0); /* change it */
262  return res;
263}
264 
265SRes SbState_SetFromMethod(IStateCoder *p, ISzAlloc *alloc)
266{
267  CSbDec *decoder;
268  p->p = 0;
269  decoder = alloc->Alloc(alloc, sizeof(CSbDec));
270  if (decoder == 0)
271    return SZ_ERROR_MEM;
272  p->p = decoder;
273  p->Free = SbState_Free;
274  p->SetProps = SbState_SetProps;
275  p->Init = SbState_Init;
276  p->Code = SbState_Code;
277  SbDec_Construct(decoder);
278  SbDec_SetAlloc(decoder, alloc);
279  return SZ_OK;
280}
281#endif
282 
283/* ---------- Lzma2State ---------- */
284 
285static void Lzma2State_Free(void *pp, ISzAlloc *alloc)
286{
287  Lzma2Dec_Free((CLzma2Dec *)pp, alloc);
288  alloc->Free(alloc, pp);
289}
290 
291static SRes Lzma2State_SetProps(void *pp, const Byte *props, size_t propSize, ISzAlloc *alloc)
292{
293  if (propSize != 1)
294    return SZ_ERROR_UNSUPPORTED;
295  return Lzma2Dec_Allocate((CLzma2Dec *)pp, props[0], alloc);
296}
297 
298static void Lzma2State_Init(void *pp)
299{
300  Lzma2Dec_Init((CLzma2Dec *)pp);
301}
302 
303static SRes Lzma2State_Code(void *pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
304    int srcWasFinished, ECoderFinishMode finishMode, int *wasFinished)
305{
306  ELzmaStatus status;
307  /* ELzmaFinishMode fm = (finishMode == LZMA_FINISH_ANY) ? LZMA_FINISH_ANY : LZMA_FINISH_END; */
308  SRes res = Lzma2Dec_DecodeToBuf((CLzma2Dec *)pp, dest, destLen, src, srcLen, finishMode, &status);
309  srcWasFinished = srcWasFinished;
310  *wasFinished = (status == LZMA_STATUS_FINISHED_WITH_MARK);
311  return res;
312}
313 
314static SRes Lzma2State_SetFromMethod(IStateCoder *p, ISzAlloc *alloc)
315{
316  CLzma2Dec *decoder = alloc->Alloc(alloc, sizeof(CLzma2Dec));
317  p->p = decoder;
318  if (decoder == 0)
319    return SZ_ERROR_MEM;
320  p->Free = Lzma2State_Free;
321  p->SetProps = Lzma2State_SetProps;
322  p->Init = Lzma2State_Init;
323  p->Code = Lzma2State_Code;
324  Lzma2Dec_Construct(decoder);
325  return SZ_OK;
326}
327 
328 
329void MixCoder_Construct(CMixCoder *p, ISzAlloc *alloc)
330{
331  int i;
332  p->alloc = alloc;
333  p->buf = 0;
334  p->numCoders = 0;
335  for (i = 0; i < MIXCODER_NUM_FILTERS_MAX; i++)
336    p->coders[i].p = NULL;
337}
338 
339void MixCoder_Free(CMixCoder *p)
340{
341  int i;
342  for (i = 0; i < p->numCoders; i++)
343  {
344    IStateCoder *sc = &p->coders[i];
345    if (p->alloc && sc->p)
346      sc->Free(sc->p, p->alloc);
347  }
348  p->numCoders = 0;
349  if (p->buf)
350    p->alloc->Free(p->alloc, p->buf);
351}
352 
353void MixCoder_Init(CMixCoder *p)
354{
355  int i;
356  for (i = 0; i < p->numCoders - 1; i++)
357  {
358    p->size[i] = 0;
359    p->pos[i] = 0;
360    p->finished[i] = 0;
361  }
362  for (i = 0; i < p->numCoders; i++)
363  {
364    IStateCoder *coder = &p->coders[i];
365    coder->Init(coder->p);
366  }
367}
368 
369SRes MixCoder_SetFromMethod(CMixCoder *p, int coderIndex, UInt64 methodId)
370{
371  IStateCoder *sc = &p->coders[coderIndex];
372  p->ids[coderIndex] = methodId;
373  switch(methodId)
374  {
375    case XZ_ID_LZMA2: return Lzma2State_SetFromMethod(sc, p->alloc);
376    #ifdef USE_SUBBLOCK
377    case XZ_ID_Subblock: return SbState_SetFromMethod(sc, p->alloc);
378    #endif
379  }
380  if (coderIndex == 0)
381    return SZ_ERROR_UNSUPPORTED;
382  return BraState_SetFromMethod(sc, methodId, 0, p->alloc);
383}
384 
385SRes MixCoder_Code(CMixCoder *p, Byte *dest, SizeT *destLen,
386    const Byte *src, SizeT *srcLen, int srcWasFinished,
387    ECoderFinishMode finishMode, ECoderStatus *status)
388{
389  SizeT destLenOrig = *destLen;
390  SizeT srcLenOrig = *srcLen;
391  Bool allFinished = True;
392  *destLen = 0;
393  *srcLen = 0;
394  *status = CODER_STATUS_NOT_FINISHED;
395 
396  if (p->buf == 0)
397  {
398    p->buf = p->alloc->Alloc(p->alloc, CODER_BUF_SIZE * (MIXCODER_NUM_FILTERS_MAX - 1));
399    if (p->buf == 0)
400      return SZ_ERROR_MEM;
401  }
402 
403  if (p->numCoders != 1)
404    finishMode = CODER_FINISH_ANY;
405 
406  for (;;)
407  {
408    Bool processed = False;
409    int i;
410    /*
411    if (p->numCoders == 1 && *destLen == destLenOrig && finishMode == LZMA_FINISH_ANY)
412      break;
413    */
414 
415    for (i = 0; i < p->numCoders; i++)
416    {
417      SRes res;
418      IStateCoder *coder = &p->coders[i];
419      Byte *destCur;
420      SizeT destLenCur, srcLenCur;
421      const Byte *srcCur;
422      int srcFinishedCur;
423      int encodingWasFinished;
424       
425      if (i == 0)
426      {
427        srcCur = src;
428        srcLenCur = srcLenOrig - *srcLen;
429        srcFinishedCur = srcWasFinished;
430      }
431      else
432      {
433        srcCur = p->buf + (CODER_BUF_SIZE * (i - 1)) + p->pos[i - 1];
434        srcLenCur = p->size[i - 1] - p->pos[i - 1];
435        srcFinishedCur = p->finished[i - 1];
436      }
437       
438      if (i == p->numCoders - 1)
439      {
440        destCur = dest;
441        destLenCur = destLenOrig - *destLen;
442      }
443      else
444      {
445        if (p->pos[i] != p->size[i])
446          continue;
447        destCur = p->buf + (CODER_BUF_SIZE * i);
448        destLenCur = CODER_BUF_SIZE;
449      }
450       
451      res = coder->Code(coder->p, destCur, &destLenCur, srcCur, &srcLenCur, srcFinishedCur, finishMode, &encodingWasFinished);
452 
453      if (!encodingWasFinished)
454        allFinished = False;
455 
456      if (i == 0)
457      {
458        *srcLen += srcLenCur;
459        src += srcLenCur;
460      }
461      else
462      {
463        p->pos[i - 1] += srcLenCur;
464      }
465 
466      if (i == p->numCoders - 1)
467      {
468        *destLen += destLenCur;
469        dest += destLenCur;
470      }
471      else
472      {
473        p->size[i] = destLenCur;
474        p->pos[i] = 0;
475        p->finished[i] = encodingWasFinished;
476      }
477       
478      if (res != SZ_OK)
479        return res;
480 
481      if (destLenCur != 0 || srcLenCur != 0)
482        processed = True;
483    }
484    if (!processed)
485      break;
486  }
487  if (allFinished)
488    *status = CODER_STATUS_FINISHED_WITH_MARK;
489  return SZ_OK;
490}
491 
492SRes Xz_ParseHeader(CXzStreamFlags *p, const Byte *buf)
493{
494  *p = (CXzStreamFlags)GetBe16(buf + XZ_SIG_SIZE);
495  if (CrcCalc(buf + XZ_SIG_SIZE, XZ_STREAM_FLAGS_SIZE) !=
496      GetUi32(buf + XZ_SIG_SIZE + XZ_STREAM_FLAGS_SIZE))
497    return SZ_ERROR_NO_ARCHIVE;
498  return XzFlags_IsSupported(*p) ? SZ_OK : SZ_ERROR_UNSUPPORTED;
499}
500 
501static Bool Xz_CheckFooter(CXzStreamFlags flags, UInt64 indexSize, const Byte *buf)
502{
503  return
504      indexSize == (((UInt64)GetUi32(buf + 4) + 1) << 2) &&
505      (GetUi32(buf) == CrcCalc(buf + 4, 6) &&
506      flags == GetBe16(buf + 8) &&
507      memcmp(buf + 10, XZ_FOOTER_SIG, XZ_FOOTER_SIG_SIZE) == 0);
508}
509 
510#define READ_VARINT_AND_CHECK(buf, pos, size, res) \
511  { unsigned s = Xz_ReadVarInt(buf + pos, size - pos, res); \
512  if (s == 0) return SZ_ERROR_ARCHIVE; pos += s; }
513 
514 
515SRes XzBlock_Parse(CXzBlock *p, const Byte *header)
516{
517  unsigned pos;
518  int numFilters, i;
519  UInt32 headerSize = (UInt32)header[0] << 2;
520 
521  if (CrcCalc(header, headerSize) != GetUi32(header + headerSize))
522    return SZ_ERROR_ARCHIVE;
523 
524  pos = 1;
525  if (pos == headerSize)
526    return SZ_ERROR_ARCHIVE;
527  p->flags = header[pos++];
528 
529  if (XzBlock_HasPackSize(p))
530  {
531    READ_VARINT_AND_CHECK(header, pos, headerSize, &p->packSize);
532    if (p->packSize == 0 || p->packSize + headerSize >= (UInt64)1 << 63)
533      return SZ_ERROR_ARCHIVE;
534  }
535 
536  if (XzBlock_HasUnpackSize(p))
537    READ_VARINT_AND_CHECK(header, pos, headerSize, &p->unpackSize);
538 
539  numFilters = XzBlock_GetNumFilters(p);
540  for (i = 0; i < numFilters; i++)
541  {
542    CXzFilter *filter = p->filters + i;
543    UInt64 size;
544    READ_VARINT_AND_CHECK(header, pos, headerSize, &filter->id);
545    READ_VARINT_AND_CHECK(header, pos, headerSize, &size);
546    if (size > headerSize - pos || size > XZ_FILTER_PROPS_SIZE_MAX)
547      return SZ_ERROR_ARCHIVE;
548    filter->propsSize = (UInt32)size;
549    memcpy(filter->props, header + pos, (size_t)size);
550    pos += (unsigned)size;
551 
552    #ifdef XZ_DUMP
553    printf("\nf[%d] = %2X: ", i, filter->id);
554    {
555      int i;
556      for (i = 0; i < size; i++)
557        printf(" %2X", filter->props[i]);
558    }
559    #endif
560  }
561 
562  while (pos < headerSize)
563    if (header[pos++] != 0)
564      return SZ_ERROR_ARCHIVE;
565  return SZ_OK;
566}
567 
568SRes XzDec_Init(CMixCoder *p, const CXzBlock *block)
569{
570  int i;
571  Bool needReInit = True;
572  int numFilters = XzBlock_GetNumFilters(block);
573  if (numFilters == p->numCoders)
574  {
575    for (i = 0; i < numFilters; i++)
576      if (p->ids[i] != block->filters[numFilters - 1 - i].id)
577        break;
578    needReInit = (i != numFilters);
579  }
580  if (needReInit)
581  {
582    MixCoder_Free(p);
583    p->numCoders = numFilters;
584    for (i = 0; i < numFilters; i++)
585    {
586      const CXzFilter *f = &block->filters[numFilters - 1 - i];
587      RINOK(MixCoder_SetFromMethod(p, i, f->id));
588    }
589  }
590  for (i = 0; i < numFilters; i++)
591  {
592    const CXzFilter *f = &block->filters[numFilters - 1 - i];
593    IStateCoder *sc = &p->coders[i];
594    RINOK(sc->SetProps(sc->p, f->props, f->propsSize, p->alloc));
595  }
596  MixCoder_Init(p);
597  return SZ_OK;
598}
599 
600void XzUnpacker_Init(CXzUnpacker *p)
601{
602  p->state = XZ_STATE_STREAM_HEADER;
603  p->pos = 0;
604  p->numStreams = 0;
605}
606 
607void XzUnpacker_Construct(CXzUnpacker *p, ISzAlloc *alloc)
608{
609  MixCoder_Construct(&p->decoder, alloc);
610  XzUnpacker_Init(p);
611}
612 
613void XzUnpacker_Free(CXzUnpacker *p)
614{
615  MixCoder_Free(&p->decoder);
616}
617 
618SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen,
619    const Byte *src, SizeT *srcLen, int finishMode, ECoderStatus *status)
620{
621  SizeT destLenOrig = *destLen;
622  SizeT srcLenOrig = *srcLen;
623  *destLen = 0;
624  *srcLen = 0;
625  *status = CODER_STATUS_NOT_SPECIFIED;
626  for (;;)
627  {
628    SizeT srcRem = srcLenOrig - *srcLen;
629 
630    if (p->state == XZ_STATE_BLOCK)
631    {
632      SizeT destLen2 = destLenOrig - *destLen;
633      SizeT srcLen2 = srcLenOrig - *srcLen;
634      SRes res;
635      if (srcLen2 == 0 && destLen2 == 0)
636      {
637        *status = CODER_STATUS_NOT_FINISHED;
638        return SZ_OK;
639      }
640       
641      res = MixCoder_Code(&p->decoder, dest, &destLen2, src, &srcLen2, False, finishMode, status);
642      XzCheck_Update(&p->check, dest, destLen2);
643       
644      (*srcLen) += srcLen2;
645      src += srcLen2;
646      p->packSize += srcLen2;
647       
648      (*destLen) += destLen2;
649      dest += destLen2;
650      p->unpackSize += destLen2;
651       
652      RINOK(res);
653       
654      if (*status == CODER_STATUS_FINISHED_WITH_MARK)
655      {
656        Byte temp[32];
657        unsigned num = Xz_WriteVarInt(temp, p->packSize + p->blockHeaderSize + XzFlags_GetCheckSize(p->streamFlags));
658        num += Xz_WriteVarInt(temp + num, p->unpackSize);
659        Sha256_Update(&p->sha, temp, num);
660        p->indexSize += num;
661        p->numBlocks++;
662         
663        p->state = XZ_STATE_BLOCK_FOOTER;
664        p->pos = 0;
665        p->alignPos = 0;
666      }
667      else if (srcLen2 == 0 && destLen2 == 0)
668        return SZ_OK;
669       
670      continue;
671    }
672 
673    if (srcRem == 0)
674    {
675      *status = CODER_STATUS_NEEDS_MORE_INPUT;
676      return SZ_OK;
677    }
678 
679    switch(p->state)
680    {
681      case XZ_STATE_STREAM_HEADER:
682      {
683        if (p->pos < XZ_STREAM_HEADER_SIZE)
684        {
685          if (p->pos < XZ_SIG_SIZE && *src != XZ_SIG[p->pos])
686            return SZ_ERROR_NO_ARCHIVE;
687          p->buf[p->pos++] = *src++;
688          (*srcLen)++;
689        }
690        else
691        {
692          RINOK(Xz_ParseHeader(&p->streamFlags, p->buf));
693          p->state = XZ_STATE_BLOCK_HEADER;
694          Sha256_Init(&p->sha);
695          p->indexSize = 0;
696          p->numBlocks = 0;
697          p->pos = 0;
698        }
699        break;
700      }
701 
702      case XZ_STATE_BLOCK_HEADER:
703      {
704        if (p->pos == 0)
705        {
706          p->buf[p->pos++] = *src++;
707          (*srcLen)++;
708          if (p->buf[0] == 0)
709          {
710            p->indexPreSize = 1 + Xz_WriteVarInt(p->buf + 1, p->numBlocks);
711            p->indexPos = p->indexPreSize;
712            p->indexSize += p->indexPreSize;
713            Sha256_Final(&p->sha, p->shaDigest);
714            Sha256_Init(&p->sha);
715            p->crc = CrcUpdate(CRC_INIT_VAL, p->buf, p->indexPreSize);
716            p->state = XZ_STATE_STREAM_INDEX;
717          }
718          p->blockHeaderSize = ((UInt32)p->buf[0] << 2) + 4;
719        }
720        else if (p->pos != p->blockHeaderSize)
721        {
722          UInt32 cur = p->blockHeaderSize - p->pos;
723          if (cur > srcRem)
724            cur = (UInt32)srcRem;
725          memcpy(p->buf + p->pos, src, cur);
726          p->pos += cur;
727          (*srcLen) += cur;
728          src += cur;
729        }
730        else
731        {
732          RINOK(XzBlock_Parse(&p->block, p->buf));
733          p->state = XZ_STATE_BLOCK;
734          p->packSize = 0;
735          p->unpackSize = 0;
736          XzCheck_Init(&p->check, XzFlags_GetCheckType(p->streamFlags));
737          RINOK(XzDec_Init(&p->decoder, &p->block));
738        }
739        break;
740      }
741 
742      case XZ_STATE_BLOCK_FOOTER:
743      {
744        if (((p->packSize + p->alignPos) & 3) != 0)
745        {
746          (*srcLen)++;
747          p->alignPos++;
748          if (*src++ != 0)
749            return SZ_ERROR_CRC;
750        }
751        else
752        {
753          UInt32 checkSize = XzFlags_GetCheckSize(p->streamFlags);
754          UInt32 cur = checkSize - p->pos;
755          if (cur != 0)
756          {
757            if (cur > srcRem)
758              cur = (UInt32)srcRem;
759            memcpy(p->buf + p->pos, src, cur);
760            p->pos += cur;
761            (*srcLen) += cur;
762            src += cur;
763          }
764          else
765          {
766            Byte digest[XZ_CHECK_SIZE_MAX];
767            p->state = XZ_STATE_BLOCK_HEADER;
768            p->pos = 0;
769            if (XzCheck_Final(&p->check, digest) && memcmp(digest, p->buf, checkSize) != 0)
770              return SZ_ERROR_CRC;
771          }
772        }
773        break;
774      }
775 
776      case XZ_STATE_STREAM_INDEX:
777      {
778        if (p->pos < p->indexPreSize)
779        {
780          (*srcLen)++;
781          if (*src++ != p->buf[p->pos++])
782            return SZ_ERROR_CRC;
783        }
784        else
785        {
786          if (p->indexPos < p->indexSize)
787          {
788            UInt64 cur = p->indexSize - p->indexPos;
789            if (srcRem > cur)
790              srcRem = (SizeT)cur;
791            p->crc = CrcUpdate(p->crc, src, srcRem);
792            Sha256_Update(&p->sha, src, srcRem);
793            (*srcLen) += srcRem;
794            src += srcRem;
795            p->indexPos += srcRem;
796          }
797          else if ((p->indexPos & 3) != 0)
798          {
799            Byte b = *src++;
800            p->crc = CRC_UPDATE_BYTE(p->crc, b);
801            (*srcLen)++;
802            p->indexPos++;
803            p->indexSize++;
804            if (b != 0)
805              return SZ_ERROR_CRC;
806          }
807          else
808          {
809            Byte digest[SHA256_DIGEST_SIZE];
810            p->state = XZ_STATE_STREAM_INDEX_CRC;
811            p->indexSize += 4;
812            p->pos = 0;
813            Sha256_Final(&p->sha, digest);
814            if (memcmp(digest, p->shaDigest, SHA256_DIGEST_SIZE) != 0)
815              return SZ_ERROR_CRC;
816          }
817        }
818        break;
819      }
820 
821      case XZ_STATE_STREAM_INDEX_CRC:
822      {
823        if (p->pos < 4)
824        {
825          (*srcLen)++;
826          p->buf[p->pos++] = *src++;
827        }
828        else
829        {
830          p->state = XZ_STATE_STREAM_FOOTER;
831          p->pos = 0;
832          if (CRC_GET_DIGEST(p->crc) != GetUi32(p->buf))
833            return SZ_ERROR_CRC;
834        }
835        break;
836      }
837 
838      case XZ_STATE_STREAM_FOOTER:
839      {
840        UInt32 cur = XZ_STREAM_FOOTER_SIZE - p->pos;
841        if (cur > srcRem)
842          cur = (UInt32)srcRem;
843        memcpy(p->buf + p->pos, src, cur);
844        p->pos += cur;
845        (*srcLen) += cur;
846        src += cur;
847        if (p->pos == XZ_STREAM_FOOTER_SIZE)
848        {
849          p->state = XZ_STATE_STREAM_PADDING;
850          p->numStreams++;
851          p->padSize = 0;
852          if (!Xz_CheckFooter(p->streamFlags, p->indexSize, p->buf))
853            return SZ_ERROR_CRC;
854        }
855        break;
856      }
857 
858      case XZ_STATE_STREAM_PADDING:
859      {
860        if (*src != 0)
861        {
862          if (((UInt32)p->padSize & 3) != 0)
863            return SZ_ERROR_NO_ARCHIVE;
864          p->pos = 0;
865          p->state = XZ_STATE_STREAM_HEADER;
866        }
867        else
868        {
869          (*srcLen)++;
870          src++;
871          p->padSize++;
872        }
873        break;
874      }
875       
876      case XZ_STATE_BLOCK: break; /* to disable GCC warning */
877    }
878  }
879  /*
880  if (p->state == XZ_STATE_FINISHED)
881    *status = CODER_STATUS_FINISHED_WITH_MARK;
882  return SZ_OK;
883  */
884}
885 
886Bool XzUnpacker_IsStreamWasFinished(CXzUnpacker *p)
887{
888  return (p->state == XZ_STATE_STREAM_PADDING) && (((UInt32)p->padSize & 3) == 0);
889}
src/lib/lib7z/Aes.h
r0r14440
1/* Aes.h -- AES encryption / decryption
22009-11-23 : Igor Pavlov : Public domain */
3 
4#ifndef __AES_H
5#define __AES_H
6 
7#include "Types.h"
8 
9EXTERN_C_BEGIN
10 
11#define AES_BLOCK_SIZE 16
12 
13/* Call AesGenTables one time before other AES functions */
14void AesGenTables(void);
15 
16/* UInt32 pointers must be 16-byte aligned */
17 
18/* 16-byte (4 * 32-bit words) blocks: 1 (IV) + 1 (keyMode) + 15 (AES-256 roundKeys) */
19#define AES_NUM_IVMRK_WORDS ((1 + 1 + 15) * 4)
20 
21/* aes - 16-byte aligned pointer to keyMode+roundKeys sequence */
22/* keySize = 16 or 24 or 32 (bytes) */
23typedef void (MY_FAST_CALL *AES_SET_KEY_FUNC)(UInt32 *aes, const Byte *key, unsigned keySize);
24void MY_FAST_CALL Aes_SetKey_Enc(UInt32 *aes, const Byte *key, unsigned keySize);
25void MY_FAST_CALL Aes_SetKey_Dec(UInt32 *aes, const Byte *key, unsigned keySize);
26 
27/* ivAes - 16-byte aligned pointer to iv+keyMode+roundKeys sequence: UInt32[AES_NUM_IVMRK_WORDS] */
28void AesCbc_Init(UInt32 *ivAes, const Byte *iv); /* iv size is AES_BLOCK_SIZE */
29/* data - 16-byte aligned pointer to data */
30/* numBlocks - the number of 16-byte blocks in data array */
31typedef void (MY_FAST_CALL *AES_CODE_FUNC)(UInt32 *ivAes, Byte *data, size_t numBlocks);
32extern AES_CODE_FUNC g_AesCbc_Encode;
33extern AES_CODE_FUNC g_AesCbc_Decode;
34extern AES_CODE_FUNC g_AesCtr_Code;
35 
36EXTERN_C_END
37 
38#endif
src/lib/lib7z/HuffEnc.c
r0r14440
1/* HuffEnc.c -- functions for Huffman encoding
22009-09-02 : Igor Pavlov : Public domain */
3 
4#include "HuffEnc.h"
5#include "Sort.h"
6 
7#define kMaxLen 16
8#define NUM_BITS 10
9#define MASK ((1 << NUM_BITS) - 1)
10 
11#define NUM_COUNTERS 64
12 
13#define HUFFMAN_SPEED_OPT
14 
15void Huffman_Generate(const UInt32 *freqs, UInt32 *p, Byte *lens, UInt32 numSymbols, UInt32 maxLen)
16{
17  UInt32 num = 0;
18  /* if (maxLen > 10) maxLen = 10; */
19  {
20    UInt32 i;
21     
22    #ifdef HUFFMAN_SPEED_OPT
23     
24    UInt32 counters[NUM_COUNTERS];
25    for (i = 0; i < NUM_COUNTERS; i++)
26      counters[i] = 0;
27    for (i = 0; i < numSymbols; i++)
28    {
29      UInt32 freq = freqs[i];
30      counters[(freq < NUM_COUNTERS - 1) ? freq : NUM_COUNTERS - 1]++;
31    }
32 
33    for (i = 1; i < NUM_COUNTERS; i++)
34    {
35      UInt32 temp = counters[i];
36      counters[i] = num;
37      num += temp;
38    }
39 
40    for (i = 0; i < numSymbols; i++)
41    {
42      UInt32 freq = freqs[i];
43      if (freq == 0)
44        lens[i] = 0;
45      else
46        p[counters[((freq < NUM_COUNTERS - 1) ? freq : NUM_COUNTERS - 1)]++] = i | (freq << NUM_BITS);
47    }
48    counters[0] = 0;
49    HeapSort(p + counters[NUM_COUNTERS - 2], counters[NUM_COUNTERS - 1] - counters[NUM_COUNTERS - 2]);
50     
51    #else
52 
53    for (i = 0; i < numSymbols; i++)
54    {
55      UInt32 freq = freqs[i];
56      if (freq == 0)
57        lens[i] = 0;
58      else
59        p[num++] = i | (freq << NUM_BITS);
60    }
61    HeapSort(p, num);
62 
63    #endif
64  }
65 
66  if (num < 2)
67  {
68    unsigned minCode = 0;
69    unsigned maxCode = 1;
70    if (num == 1)
71    {
72      maxCode = (unsigned)p[0] & MASK;
73      if (maxCode == 0)
74        maxCode++;
75    }
76    p[minCode] = 0;
77    p[maxCode] = 1;
78    lens[minCode] = lens[maxCode] = 1;
79    return;
80  }
81   
82  {
83    UInt32 b, e, i;
84   
85    i = b = e = 0;
86    do
87    {
88      UInt32 n, m, freq;
89      n = (i != num && (b == e || (p[i] >> NUM_BITS) <= (p[b] >> NUM_BITS))) ? i++ : b++;
90      freq = (p[n] & ~MASK);
91      p[n] = (p[n] & MASK) | (e << NUM_BITS);
92      m = (i != num && (b == e || (p[i] >> NUM_BITS) <= (p[b] >> NUM_BITS))) ? i++ : b++;
93      freq += (p[m] & ~MASK);
94      p[m] = (p[m] & MASK) | (e << NUM_BITS);
95      p[e] = (p[e] & MASK) | freq;
96      e++;
97    }
98    while (num - e > 1);
99     
100    {
101      UInt32 lenCounters[kMaxLen + 1];
102      for (i = 0; i <= kMaxLen; i++)
103        lenCounters[i] = 0;
104       
105      p[--e] &= MASK;
106      lenCounters[1] = 2;
107      while (e > 0)
108      {
109        UInt32 len = (p[p[--e] >> NUM_BITS] >> NUM_BITS) + 1;
110        p[e] = (p[e] & MASK) | (len << NUM_BITS);
111        if (len >= maxLen)
112          for (len = maxLen - 1; lenCounters[len] == 0; len--);
113        lenCounters[len]--;
114        lenCounters[len + 1] += 2;
115      }
116       
117      {
118        UInt32 len;
119        i = 0;
120        for (len = maxLen; len != 0; len--)
121        {
122          UInt32 num;
123          for (num = lenCounters[len]; num != 0; num--)
124            lens[p[i++] & MASK] = (Byte)len;
125        }
126      }
127       
128      {
129        UInt32 nextCodes[kMaxLen + 1];
130        {
131          UInt32 code = 0;
132          UInt32 len;
133          for (len = 1; len <= kMaxLen; len++)
134            nextCodes[len] = code = (code + lenCounters[len - 1]) << 1;
135        }
136        /* if (code + lenCounters[kMaxLen] - 1 != (1 << kMaxLen) - 1) throw 1; */
137 
138        {
139          UInt32 i;
140          for (i = 0; i < numSymbols; i++)
141            p[i] = nextCodes[lens[i]]++;
142        }
143      }
144    }
145  }
146}
src/lib/lib7z/Ppmd8Enc.c
r0r14440
1/* Ppmd8Enc.c -- PPMdI Encoder
22010-04-16 : Igor Pavlov : Public domain
3This code is based on:
4  PPMd var.I (2002): Dmitry Shkarin : Public domain
5  Carryless rangecoder (1999): Dmitry Subbotin : Public domain */
6 
7#include "Ppmd8.h"
8 
9#define kTop (1 << 24)
10#define kBot (1 << 15)
11 
12void Ppmd8_RangeEnc_FlushData(CPpmd8 *p)
13{
14  unsigned i;
15  for (i = 0; i < 4; i++, p->Low <<= 8 )
16    p->Stream.Out->Write(p->Stream.Out, (Byte)(p->Low >> 24));
17}
18 
19static void RangeEnc_Normalize(CPpmd8 *p)
20{
21  while ((p->Low ^ (p->Low + p->Range)) < kTop ||
22      (p->Range < kBot && ((p->Range = (0 - p->Low) & (kBot - 1)), 1)))
23  {
24    p->Stream.Out->Write(p->Stream.Out, (Byte)(p->Low >> 24));
25    p->Range <<= 8;
26    p->Low <<= 8;
27  }
28}
29 
30static void RangeEnc_Encode(CPpmd8 *p, UInt32 start, UInt32 size, UInt32 total)
31{
32  p->Low += start * (p->Range /= total);
33  p->Range *= size;
34  RangeEnc_Normalize(p);
35}
36 
37static void RangeEnc_EncodeBit_0(CPpmd8 *p, UInt32 size0)
38{
39  p->Range >>= 14;
40  p->Range *= size0;
41  RangeEnc_Normalize(p);
42}
43 
44static void RangeEnc_EncodeBit_1(CPpmd8 *p, UInt32 size0)
45{
46  p->Low += size0 * (p->Range >>= 14);
47  p->Range *= ((1 << 14) - size0);
48  RangeEnc_Normalize(p);
49}
50 
51 
52#define MASK(sym) ((signed char *)charMask)[sym]
53 
54void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol)
55{
56  size_t charMask[256 / sizeof(size_t)];
57  if (p->MinContext->NumStats != 0)
58  {
59    CPpmd_State *s = Ppmd8_GetStats(p, p->MinContext);
60    UInt32 sum;
61    unsigned i;
62    if (s->Symbol == symbol)
63    {
64      RangeEnc_Encode(p, 0, s->Freq, p->MinContext->SummFreq);
65      p->FoundState = s;
66      Ppmd8_Update1_0(p);
67      return;
68    }
69    p->PrevSuccess = 0;
70    sum = s->Freq;
71    i = p->MinContext->NumStats;
72    do
73    {
74      if ((++s)->Symbol == symbol)
75      {
76        RangeEnc_Encode(p, sum, s->Freq, p->MinContext->SummFreq);
77        p->FoundState = s;
78        Ppmd8_Update1(p);
79        return;
80      }
81      sum += s->Freq;
82    }
83    while (--i);
84     
85    PPMD_SetAllBitsIn256Bytes(charMask);
86    MASK(s->Symbol) = 0;
87    i = p->MinContext->NumStats;
88    do { MASK((--s)->Symbol) = 0; } while (--i);
89    RangeEnc_Encode(p, sum, p->MinContext->SummFreq - sum, p->MinContext->SummFreq);
90  }
91  else
92  {
93    UInt16 *prob = Ppmd8_GetBinSumm(p);
94    CPpmd_State *s = Ppmd8Context_OneState(p->MinContext);
95    if (s->Symbol == symbol)
96    {
97      RangeEnc_EncodeBit_0(p, *prob);
98      *prob = (UInt16)PPMD_UPDATE_PROB_0(*prob);
99      p->FoundState = s;
100      Ppmd8_UpdateBin(p);
101      return;
102    }
103    else
104    {
105      RangeEnc_EncodeBit_1(p, *prob);
106      *prob = (UInt16)PPMD_UPDATE_PROB_1(*prob);
107      p->InitEsc = PPMD8_kExpEscape[*prob >> 10];
108      PPMD_SetAllBitsIn256Bytes(charMask);
109      MASK(s->Symbol) = 0;
110      p->PrevSuccess = 0;
111    }
112  }
113  for (;;)
114  {
115    UInt32 escFreq;
116    CPpmd_See *see;
117    CPpmd_State *s;
118    UInt32 sum;
119    unsigned i, numMasked = p->MinContext->NumStats;
120    do
121    {
122      p->OrderFall++;
123      if (!p->MinContext->Suffix)
124        return; /* EndMarker (symbol = -1) */
125      p->MinContext = Ppmd8_GetContext(p, p->MinContext->Suffix);
126    }
127    while (p->MinContext->NumStats == numMasked);
128     
129    see = Ppmd8_MakeEscFreq(p, numMasked, &escFreq);
130    s = Ppmd8_GetStats(p, p->MinContext);
131    sum = 0;
132    i = p->MinContext->NumStats + 1;
133    do
134    {
135      int cur = s->Symbol;
136      if (cur == symbol)
137      {
138        UInt32 low = sum;
139        CPpmd_State *s1 = s;
140        do
141        {
142          sum += (s->Freq & (int)(MASK(s->Symbol)));
143          s++;
144        }
145        while (--i);
146        RangeEnc_Encode(p, low, s1->Freq, sum + escFreq);
147        Ppmd_See_Update(see);
148        p->FoundState = s1;
149        Ppmd8_Update2(p);
150        return;
151      }
152      sum += (s->Freq & (int)(MASK(cur)));
153      MASK(cur) = 0;
154      s++;
155    }
156    while (--i);
157     
158    RangeEnc_Encode(p, sum, escFreq, sum + escFreq);
159    see->Summ = (UInt16)(see->Summ + sum + escFreq);
160  }
161}
src/lib/lib7z/Bcj2.c
r0r14440
1/* Bcj2.c -- Converter for x86 code (BCJ2)
22008-10-04 : Igor Pavlov : Public domain */
3 
4#include "Bcj2.h"
5 
6#ifdef _LZMA_PROB32
7#define CProb UInt32
8#else
9#define CProb UInt16
10#endif
11 
12#define IsJcc(b0, b1) ((b0) == 0x0F && ((b1) & 0xF0) == 0x80)
13#define IsJ(b0, b1) ((b1 & 0xFE) == 0xE8 || IsJcc(b0, b1))
14 
15#define kNumTopBits 24
16#define kTopValue ((UInt32)1 << kNumTopBits)
17 
18#define kNumBitModelTotalBits 11
19#define kBitModelTotal (1 << kNumBitModelTotalBits)
20#define kNumMoveBits 5
21 
22#define RC_READ_BYTE (*buffer++)
23#define RC_TEST { if (buffer == bufferLim) return SZ_ERROR_DATA; }
24#define RC_INIT2 code = 0; range = 0xFFFFFFFF; \
25  { int i; for (i = 0; i < 5; i++) { RC_TEST; code = (code << 8) | RC_READ_BYTE; }}
26 
27#define NORMALIZE if (range < kTopValue) { RC_TEST; range <<= 8; code = (code << 8) | RC_READ_BYTE; }
28 
29#define IF_BIT_0(p) ttt = *(p); bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound)
30#define UPDATE_0(p) range = bound; *(p) = (CProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); NORMALIZE;
31#define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CProb)(ttt - (ttt >> kNumMoveBits)); NORMALIZE;
32 
33int Bcj2_Decode(
34    const Byte *buf0, SizeT size0,
35    const Byte *buf1, SizeT size1,
36    const Byte *buf2, SizeT size2,
37    const Byte *buf3, SizeT size3,
38    Byte *outBuf, SizeT outSize)
39{
40  CProb p[256 + 2];
41  SizeT inPos = 0, outPos = 0;
42 
43  const Byte *buffer, *bufferLim;
44  UInt32 range, code;
45  Byte prevByte = 0;
46 
47  unsigned int i;
48  for (i = 0; i < sizeof(p) / sizeof(p[0]); i++)
49    p[i] = kBitModelTotal >> 1;
50 
51  buffer = buf3;
52  bufferLim = buffer + size3;
53  RC_INIT2
54 
55  if (outSize == 0)
56    return SZ_OK;
57 
58  for (;;)
59  {
60    Byte b;
61    CProb *prob;
62    UInt32 bound;
63    UInt32 ttt;
64 
65    SizeT limit = size0 - inPos;
66    if (outSize - outPos < limit)
67      limit = outSize - outPos;
68    while (limit != 0)
69    {
70      Byte b = buf0[inPos];
71      outBuf[outPos++] = b;
72      if (IsJ(prevByte, b))
73        break;
74      inPos++;
75      prevByte = b;
76      limit--;
77    }
78 
79    if (limit == 0 || outPos == outSize)
80      break;
81 
82    b = buf0[inPos++];
83 
84    if (b == 0xE8)
85      prob = p + prevByte;
86    else if (b == 0xE9)
87      prob = p + 256;
88    else
89      prob = p + 257;
90 
91    IF_BIT_0(prob)
92    {
93      UPDATE_0(prob)
94      prevByte = b;
95    }
96    else
97    {
98      UInt32 dest;
99      const Byte *v;
100      UPDATE_1(prob)
101      if (b == 0xE8)
102      {
103        v = buf1;
104        if (size1 < 4)
105          return SZ_ERROR_DATA;
106        buf1 += 4;
107        size1 -= 4;
108      }
109      else
110      {
111        v = buf2;
112        if (size2 < 4)
113          return SZ_ERROR_DATA;
114        buf2 += 4;
115        size2 -= 4;
116      }
117      dest = (((UInt32)v[0] << 24) | ((UInt32)v[1] << 16) |
118          ((UInt32)v[2] << 8) | ((UInt32)v[3])) - ((UInt32)outPos + 4);
119      outBuf[outPos++] = (Byte)dest;
120      if (outPos == outSize)
121        break;
122      outBuf[outPos++] = (Byte)(dest >> 8);
123      if (outPos == outSize)
124        break;
125      outBuf[outPos++] = (Byte)(dest >> 16);
126      if (outPos == outSize)
127        break;
128      outBuf[outPos++] = prevByte = (Byte)(dest >> 24);
129    }
130  }
131  return (outPos == outSize) ? SZ_OK : SZ_ERROR_DATA;
132}
src/lib/lib7z/Lzma2Enc.h
r0r14440
1/* Lzma2Enc.h -- LZMA2 Encoder
22009-02-07 : Igor Pavlov : Public domain */
3 
4#ifndef __LZMA2_ENC_H
5#define __LZMA2_ENC_H
6 
7#include "LzmaEnc.h"
8 
9#ifdef __cplusplus
10extern "C" {
11#endif
12 
13typedef struct
14{
15  CLzmaEncProps lzmaProps;
16  size_t blockSize;
17  int numBlockThreads;
18  int numTotalThreads;
19} CLzma2EncProps;
20 
21void Lzma2EncProps_Init(CLzma2EncProps *p);
22void Lzma2EncProps_Normalize(CLzma2EncProps *p);
23 
24/* ---------- CLzmaEnc2Handle Interface ---------- */
25 
26/* Lzma2Enc_* functions can return the following exit codes:
27Returns:
28  SZ_OK           - OK
29  SZ_ERROR_MEM    - Memory allocation error
30  SZ_ERROR_PARAM  - Incorrect paramater in props
31  SZ_ERROR_WRITE  - Write callback error
32  SZ_ERROR_PROGRESS - some break from progress callback
33  SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version)
34*/
35 
36typedef void * CLzma2EncHandle;
37 
38CLzma2EncHandle Lzma2Enc_Create(ISzAlloc *alloc, ISzAlloc *allocBig);
39void Lzma2Enc_Destroy(CLzma2EncHandle p);
40SRes Lzma2Enc_SetProps(CLzma2EncHandle p, const CLzma2EncProps *props);
41Byte Lzma2Enc_WriteProperties(CLzma2EncHandle p);
42SRes Lzma2Enc_Encode(CLzma2EncHandle p,
43    ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress);
44 
45/* ---------- One Call Interface ---------- */
46 
47/* Lzma2Encode
48Return code:
49  SZ_OK               - OK
50  SZ_ERROR_MEM        - Memory allocation error
51  SZ_ERROR_PARAM      - Incorrect paramater
52  SZ_ERROR_OUTPUT_EOF - output buffer overflow
53  SZ_ERROR_THREAD     - errors in multithreading functions (only for Mt version)
54*/
55 
56/*
57SRes Lzma2Encode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
58    const CLzmaEncProps *props, Byte *propsEncoded, int writeEndMark,
59    ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
60*/
61 
62#ifdef __cplusplus
63}
64#endif
65 
66#endif
src/lib/lib7z/Bra86.c
r0r14440
1/* Bra86.c -- Converter for x86 code (BCJ)
22008-10-04 : Igor Pavlov : Public domain */
3 
4#include "Bra.h"
5 
6#define Test86MSByte(b) ((b) == 0 || (b) == 0xFF)
7 
8const Byte kMaskToAllowedStatus[8] = {1, 1, 1, 0, 1, 0, 0, 0};
9const Byte kMaskToBitNumber[8] = {0, 1, 2, 2, 3, 3, 3, 3};
10 
11SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding)
12{
13  SizeT bufferPos = 0, prevPosT;
14  UInt32 prevMask = *state & 0x7;
15  if (size < 5)
16    return 0;
17  ip += 5;
18  prevPosT = (SizeT)0 - 1;
19 
20  for (;;)
21  {
22    Byte *p = data + bufferPos;
23    Byte *limit = data + size - 4;
24    for (; p < limit; p++)
25      if ((*p & 0xFE) == 0xE8)
26        break;
27    bufferPos = (SizeT)(p - data);
28    if (p >= limit)
29      break;
30    prevPosT = bufferPos - prevPosT;
31    if (prevPosT > 3)
32      prevMask = 0;
33    else
34    {
35      prevMask = (prevMask << ((int)prevPosT - 1)) & 0x7;
36      if (prevMask != 0)
37      {
38        Byte b = p[4 - kMaskToBitNumber[prevMask]];
39        if (!kMaskToAllowedStatus[prevMask] || Test86MSByte(b))
40        {
41          prevPosT = bufferPos;
42          prevMask = ((prevMask << 1) & 0x7) | 1;
43          bufferPos++;
44          continue;
45        }
46      }
47    }
48    prevPosT = bufferPos;
49 
50    if (Test86MSByte(p[4]))
51    {
52      UInt32 src = ((UInt32)p[4] << 24) | ((UInt32)p[3] << 16) | ((UInt32)p[2] << 8) | ((UInt32)p[1]);
53      UInt32 dest;
54      for (;;)
55      {
56        Byte b;
57        int index;
58        if (encoding)
59          dest = (ip + (UInt32)bufferPos) + src;
60        else
61          dest = src - (ip + (UInt32)bufferPos);
62        if (prevMask == 0)
63          break;
64        index = kMaskToBitNumber[prevMask] * 8;
65        b = (Byte)(dest >> (24 - index));
66        if (!Test86MSByte(b))
67          break;
68        src = dest ^ ((1 << (32 - index)) - 1);
69      }
70      p[4] = (Byte)(~(((dest >> 24) & 1) - 1));
71      p[3] = (Byte)(dest >> 16);
72      p[2] = (Byte)(dest >> 8);
73      p[1] = (Byte)dest;
74      bufferPos += 5;
75    }
76    else
77    {
78      prevMask = ((prevMask << 1) & 0x7) | 1;
79      bufferPos++;
80    }
81  }
82  prevPosT = bufferPos - prevPosT;
83  *state = ((prevPosT > 3) ? 0 : ((prevMask << ((int)prevPosT - 1)) & 0x7));
84  return bufferPos;
85}
src/lib/lib7z/HuffEnc.h
r0r14440
1/* HuffEnc.h -- Huffman encoding
22009-02-07 : Igor Pavlov : Public domain */
3 
4#ifndef __HUFF_ENC_H
5#define __HUFF_ENC_H
6 
7#include "Types.h"
8 
9#ifdef __cplusplus
10extern "C" {
11#endif
12 
13/*
14Conditions:
15  num <= 1024 = 2 ^ NUM_BITS
16  Sum(freqs) < 4M = 2 ^ (32 - NUM_BITS)
17  maxLen <= 16 = kMaxLen
18  Num_Items(p) >= HUFFMAN_TEMP_SIZE(num)
19*/
20 
21void Huffman_Generate(const UInt32 *freqs, UInt32 *p, Byte *lens, UInt32 num, UInt32 maxLen);
22 
23#ifdef __cplusplus
24}
25#endif
26 
27#endif
src/lib/lib7z/Bcj2.h
r0r14440
1/* Bcj2.h -- Converter for x86 code (BCJ2)
22009-02-07 : Igor Pavlov : Public domain */
3 
4#ifndef __BCJ2_H
5#define __BCJ2_H
6 
7#include "Types.h"
8 
9#ifdef __cplusplus
10extern "C" {
11#endif
12 
13/*
14Conditions:
15  outSize <= FullOutputSize,
16  where FullOutputSize is full size of output stream of x86_2 filter.
17 
18If buf0 overlaps outBuf, there are two required conditions:
19  1) (buf0 >= outBuf)
20  2) (buf0 + size0 >= outBuf + FullOutputSize).
21 
22Returns:
23  SZ_OK
24  SZ_ERROR_DATA - Data error
25*/
26 
27int Bcj2_Decode(
28    const Byte *buf0, SizeT size0,
29    const Byte *buf1, SizeT size1,
30    const Byte *buf2, SizeT size2,
31    const Byte *buf3, SizeT size3,
32    Byte *outBuf, SizeT outSize);
33 
34#ifdef __cplusplus
35}
36#endif
37 
38#endif
src/lib/lib7z/LzFind.c
r0r14440
1/* LzFind.c -- Match finder for LZ algorithms
22009-04-22 : Igor Pavlov : Public domain */
3 
4#include <string.h>
5 
6#include "LzFind.h"
7#include "LzHash.h"
8 
9#define kEmptyHashValue 0
10#define kMaxValForNormalize ((UInt32)0xFFFFFFFF)
11#define kNormalizeStepMin (1 << 10) /* it must be power of 2 */
12#define kNormalizeMask (~(kNormalizeStepMin - 1))
13#define kMaxHistorySize ((UInt32)3 << 30)
14 
15#define kStartMaxLen 3
16 
17static void LzInWindow_Free(CMatchFinder *p, ISzAlloc *alloc)
18{
19  if (!p->directInput)
20  {
21    alloc->Free(alloc, p->bufferBase);
22    p->bufferBase = 0;
23  }
24}
25 
26/* keepSizeBefore + keepSizeAfter + keepSizeReserv must be < 4G) */
27 
28static int LzInWindow_Create(CMatchFinder *p, UInt32 keepSizeReserv, ISzAlloc *alloc)
29{
30  UInt32 blockSize = p->keepSizeBefore + p->keepSizeAfter + keepSizeReserv;
31  if (p->directInput)
32  {
33    p->blockSize = blockSize;
34    return 1;
35  }
36  if (p->bufferBase == 0 || p->blockSize != blockSize)
37  {
38    LzInWindow_Free(p, alloc);
39    p->blockSize = blockSize;
40    p->bufferBase = (Byte *)alloc->Alloc(alloc, (size_t)blockSize);
41  }
42  return (p->bufferBase != 0);
43}
44 
45Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return p->buffer; }
46Byte MatchFinder_GetIndexByte(CMatchFinder *p, Int32 index) { return p->buffer[index]; }
47 
48UInt32 MatchFinder_GetNumAvailableBytes(CMatchFinder *p) { return p->streamPos - p->pos; }
49 
50void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue)
51{
52  p->posLimit -= subValue;
53  p->pos -= subValue;
54  p->streamPos -= subValue;
55}
56 
57static void MatchFinder_ReadBlock(CMatchFinder *p)
58{
59  if (p->streamEndWasReached || p->result != SZ_OK)
60    return;
61  if (p->directInput)
62  {
63    UInt32 curSize = 0xFFFFFFFF - p->streamPos;
64    if (curSize > p->directInputRem)
65      curSize = (UInt32)p->directInputRem;
66    p->directInputRem -= curSize;
67    p->streamPos += curSize;
68    if (p->directInputRem == 0)
69      p->streamEndWasReached = 1;
70    return;
71  }
72  for (;;)
73  {
74    Byte *dest = p->buffer + (p->streamPos - p->pos);
75    size_t size = (p->bufferBase + p->blockSize - dest);
76    if (size == 0)
77      return;
78    p->result = p->stream->Read(p->stream, dest, &size);
79    if (p->result != SZ_OK)
80      return;
81    if (size == 0)
82    {
83      p->streamEndWasReached = 1;
84      return;
85    }
86    p->streamPos += (UInt32)size;
87    if (p->streamPos - p->pos > p->keepSizeAfter)
88      return;
89  }
90}
91 
92void MatchFinder_MoveBlock(CMatchFinder *p)
93{
94  memmove(p->bufferBase,
95    p->buffer - p->keepSizeBefore,
96    (size_t)(p->streamPos - p->pos + p->keepSizeBefore));
97  p->buffer = p->bufferBase + p->keepSizeBefore;
98}
99 
100int MatchFinder_NeedMove(CMatchFinder *p)
101{
102  if (p->directInput)
103    return 0;
104  /* if (p->streamEndWasReached) return 0; */
105  return ((size_t)(p->bufferBase + p->blockSize - p->buffer) <= p->keepSizeAfter);
106}
107 
108void MatchFinder_ReadIfRequired(CMatchFinder *p)
109{
110  if (p->streamEndWasReached)
111    return;
112  if (p->keepSizeAfter >= p->streamPos - p->pos)
113    MatchFinder_ReadBlock(p);
114}
115 
116static void MatchFinder_CheckAndMoveAndRead(CMatchFinder *p)
117{
118  if (MatchFinder_NeedMove(p))
119    MatchFinder_MoveBlock(p);
120  MatchFinder_ReadBlock(p);
121}
122 
123static void MatchFinder_SetDefaultSettings(CMatchFinder *p)
124{
125  p->cutValue = 32;
126  p->btMode = 1;
127  p->numHashBytes = 4;
128  p->bigHash = 0;
129}
130 
131#define kCrcPoly 0xEDB88320
132 
133void MatchFinder_Construct(CMatchFinder *p)
134{
135  UInt32 i;
136  p->bufferBase = 0;
137  p->directInput = 0;
138  p->hash = 0;
139  MatchFinder_SetDefaultSettings(p);
140 
141  for (i = 0; i < 256; i++)
142  {
143    UInt32 r = i;
144    int j;
145    for (j = 0; j < 8; j++)
146      r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1));
147    p->crc[i] = r;
148  }
149}
150 
151static void MatchFinder_FreeThisClassMemory(CMatchFinder *p, ISzAlloc *alloc)
152{
153  alloc->Free(alloc, p->hash);
154  p->hash = 0;
155}
156 
157void MatchFinder_Free(CMatchFinder *p, ISzAlloc *alloc)
158{
159  MatchFinder_FreeThisClassMemory(p, alloc);
160  LzInWindow_Free(p, alloc);
161}
162 
163static CLzRef* AllocRefs(UInt32 num, ISzAlloc *alloc)
164{
165  size_t sizeInBytes = (size_t)num * sizeof(CLzRef);
166  if (sizeInBytes / sizeof(CLzRef) != num)
167    return 0;
168  return (CLzRef *)alloc->Alloc(alloc, sizeInBytes);
169}
170 
171int MatchFinder_Create(CMatchFinder *p, UInt32 historySize,
172    UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter,
173    ISzAlloc *alloc)
174{
175  UInt32 sizeReserv;
176  if (historySize > kMaxHistorySize)
177  {
178    MatchFinder_Free(p, alloc);
179    return 0;
180  }
181  sizeReserv = historySize >> 1;
182  if (historySize > ((UInt32)2 << 30))
183    sizeReserv = historySize >> 2;
184  sizeReserv += (keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + (1 << 19);
185 
186  p->keepSizeBefore = historySize + keepAddBufferBefore + 1;
187  p->keepSizeAfter = matchMaxLen + keepAddBufferAfter;
188  /* we need one additional byte, since we use MoveBlock after pos++ and before dictionary using */
189  if (LzInWindow_Create(p, sizeReserv, alloc))
190  {
191    UInt32 newCyclicBufferSize = historySize + 1;
192    UInt32 hs;
193    p->matchMaxLen = matchMaxLen;
194    {
195      p->fixedHashSize = 0;
196      if (p->numHashBytes == 2)
197        hs = (1 << 16) - 1;
198      else
199      {
200        hs = historySize - 1;
201        hs |= (hs >> 1);
202        hs |= (hs >> 2);
203        hs |= (hs >> 4);
204        hs |= (hs >> 8);
205        hs >>= 1;
206        hs |= 0xFFFF; /* don't change it! It's required for Deflate */
207        if (hs > (1 << 24))
208        {
209          if (p->numHashBytes == 3)
210            hs = (1 << 24) - 1;
211          else
212            hs >>= 1;
213        }
214      }
215      p->hashMask = hs;
216      hs++;
217      if (p->numHashBytes > 2) p->fixedHashSize += kHash2Size;
218      if (p->numHashBytes > 3) p->fixedHashSize += kHash3Size;
219      if (p->numHashBytes > 4) p->fixedHashSize += kHash4Size;
220      hs += p->fixedHashSize;
221    }
222 
223    {
224      UInt32 prevSize = p->hashSizeSum + p->numSons;
225      UInt32 newSize;
226      p->historySize = historySize;
227      p->hashSizeSum = hs;
228      p->cyclicBufferSize = newCyclicBufferSize;
229      p->numSons = (p->btMode ? newCyclicBufferSize * 2 : newCyclicBufferSize);
230      newSize = p->hashSizeSum + p->numSons;
231      if (p->hash != 0 && prevSize == newSize)
232        return 1;
233      MatchFinder_FreeThisClassMemory(p, alloc);
234      p->hash = AllocRefs(newSize, alloc);
235      if (p->hash != 0)
236      {
237        p->son = p->hash + p->hashSizeSum;
238        return 1;
239      }
240    }
241  }
242  MatchFinder_Free(p, alloc);
243  return 0;
244}
245 
246static void MatchFinder_SetLimits(CMatchFinder *p)
247{
248  UInt32 limit = kMaxValForNormalize - p->pos;
249  UInt32 limit2 = p->cyclicBufferSize - p->cyclicBufferPos;
250  if (limit2 < limit)
251    limit = limit2;
252  limit2 = p->streamPos - p->pos;
253  if (limit2 <= p->keepSizeAfter)
254  {
255    if (limit2 > 0)
256      limit2 = 1;
257  }
258  else
259    limit2 -= p->keepSizeAfter;
260  if (limit2 < limit)
261    limit = limit2;
262  {
263    UInt32 lenLimit = p->streamPos - p->pos;
264    if (lenLimit > p->matchMaxLen)
265      lenLimit = p->matchMaxLen;
266    p->lenLimit = lenLimit;
267  }
268  p->posLimit = p->pos + limit;
269}
270 
271void MatchFinder_Init(CMatchFinder *p)
272{
273  UInt32 i;
274  for (i = 0; i < p->hashSizeSum; i++)
275    p->hash[i] = kEmptyHashValue;
276  p->cyclicBufferPos = 0;
277  p->buffer = p->bufferBase;
278  p->pos = p->streamPos = p->cyclicBufferSize;
279  p->result = SZ_OK;
280  p->streamEndWasReached = 0;
281  MatchFinder_ReadBlock(p);
282  MatchFinder_SetLimits(p);
283}
284 
285static UInt32 MatchFinder_GetSubValue(CMatchFinder *p)
286{
287  return (p->pos - p->historySize - 1) & kNormalizeMask;
288}
289 
290void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems)
291{
292  UInt32 i;
293  for (i = 0; i < numItems; i++)
294  {
295    UInt32 value = items[i];
296    if (value <= subValue)
297      value = kEmptyHashValue;
298    else
299      value -= subValue;
300    items[i] = value;
301  }
302}
303 
304static void MatchFinder_Normalize(CMatchFinder *p)
305{
306  UInt32 subValue = MatchFinder_GetSubValue(p);
307  MatchFinder_Normalize3(subValue, p->hash, p->hashSizeSum + p->numSons);
308  MatchFinder_ReduceOffsets(p, subValue);
309}
310 
311static void MatchFinder_CheckLimits(CMatchFinder *p)
312{
313  if (p->pos == kMaxValForNormalize)
314    MatchFinder_Normalize(p);
315  if (!p->streamEndWasReached && p->keepSizeAfter == p->streamPos - p->pos)
316    MatchFinder_CheckAndMoveAndRead(p);
317  if (p->cyclicBufferPos == p->cyclicBufferSize)
318    p->cyclicBufferPos = 0;
319  MatchFinder_SetLimits(p);
320}
321 
322static UInt32 * Hc_GetMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
323    UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue,
324    UInt32 *distances, UInt32 maxLen)
325{
326  son[_cyclicBufferPos] = curMatch;
327  for (;;)
328  {
329    UInt32 delta = pos - curMatch;
330    if (cutValue-- == 0 || delta >= _cyclicBufferSize)
331      return distances;
332    {
333      const Byte *pb = cur - delta;
334      curMatch = son[_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)];
335      if (pb[maxLen] == cur[maxLen] && *pb == *cur)
336      {
337        UInt32 len = 0;
338        while (++len != lenLimit)
339          if (pb[len] != cur[len])
340            break;
341        if (maxLen < len)
342        {
343          *distances++ = maxLen = len;
344          *distances++ = delta - 1;
345          if (len == lenLimit)
346            return distances;
347        }
348      }
349    }
350  }
351}
352 
353UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
354    UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue,
355    UInt32 *distances, UInt32 maxLen)
356{
357  CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1;
358  CLzRef *ptr1 = son + (_cyclicBufferPos << 1);
359  UInt32 len0 = 0, len1 = 0;
360  for (;;)
361  {
362    UInt32 delta = pos - curMatch;
363    if (cutValue-- == 0 || delta >= _cyclicBufferSize)
364    {
365      *ptr0 = *ptr1 = kEmptyHashValue;
366      return distances;
367    }
368    {
369      CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1);
370      const Byte *pb = cur - delta;
371      UInt32 len = (len0 < len1 ? len0 : len1);
372      if (pb[len] == cur[len])
373      {
374        if (++len != lenLimit && pb[len] == cur[len])
375          while (++len != lenLimit)
376            if (pb[len] != cur[len])
377              break;
378        if (maxLen < len)
379        {
380          *distances++ = maxLen = len;
381          *distances++ = delta - 1;
382          if (len == lenLimit)
383          {
384            *ptr1 = pair[0];
385            *ptr0 = pair[1];
386            return distances;
387          }
388        }
389      }
390      if (pb[len] < cur[len])
391      {
392        *ptr1 = curMatch;
393        ptr1 = pair + 1;
394        curMatch = *ptr1;
395        len1 = len;
396      }
397      else
398      {
399        *ptr0 = curMatch;
400        ptr0 = pair;
401        curMatch = *ptr0;
402        len0 = len;
403      }
404    }
405  }
406}
407 
408static void SkipMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
409    UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue)
410{
411  CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1;
412  CLzRef *ptr1 = son + (_cyclicBufferPos << 1);
413  UInt32 len0 = 0, len1 = 0;
414  for (;;)
415  {
416    UInt32 delta = pos - curMatch;
417    if (cutValue-- == 0 || delta >= _cyclicBufferSize)
418    {
419      *ptr0 = *ptr1 = kEmptyHashValue;
420      return;
421    }
422    {
423      CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1);
424      const Byte *pb = cur - delta;
425      UInt32 len = (len0 < len1 ? len0 : len1);
426      if (pb[len] == cur[len])
427      {
428        while (++len != lenLimit)
429          if (pb[len] != cur[len])
430            break;
431        {
432          if (len == lenLimit)
433          {
434            *ptr1 = pair[0];
435            *ptr0 = pair[1];
436            return;
437          }
438        }
439      }
440      if (pb[len] < cur[len])
441      {
442        *ptr1 = curMatch;
443        ptr1 = pair + 1;
444        curMatch = *ptr1;
445        len1 = len;
446      }
447      else
448      {
449        *ptr0 = curMatch;
450        ptr0 = pair;
451        curMatch = *ptr0;
452        len0 = len;
453      }
454    }
455  }
456}
457 
458#define MOVE_POS \
459  ++p->cyclicBufferPos; \
460  p->buffer++; \
461  if (++p->pos == p->posLimit) MatchFinder_CheckLimits(p);
462 
463#define MOVE_POS_RET MOVE_POS return offset;
464 
465static void MatchFinder_MovePos(CMatchFinder *p) { MOVE_POS; }
466 
467#define GET_MATCHES_HEADER2(minLen, ret_op) \
468  UInt32 lenLimit; UInt32 hashValue; const Byte *cur; UInt32 curMatch; \
469  lenLimit = p->lenLimit; { if (lenLimit < minLen) { MatchFinder_MovePos(p); ret_op; }} \
470  cur = p->buffer;
471 
472#define GET_MATCHES_HEADER(minLen) GET_MATCHES_HEADER2(minLen, return 0)
473#define SKIP_HEADER(minLen)        GET_MATCHES_HEADER2(minLen, continue)
474 
475#define MF_PARAMS(p) p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue
476 
477#define GET_MATCHES_FOOTER(offset, maxLen) \
478  offset = (UInt32)(GetMatchesSpec1(lenLimit, curMatch, MF_PARAMS(p), \
479  distances + offset, maxLen) - distances); MOVE_POS_RET;
480 
481#define SKIP_FOOTER \
482  SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); MOVE_POS;
483 
484static UInt32 Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
485{
486  UInt32 offset;
487  GET_MATCHES_HEADER(2)
488  HASH2_CALC;
489  curMatch = p->hash[hashValue];
490  p->hash[hashValue] = p->pos;
491  offset = 0;
492  GET_MATCHES_FOOTER(offset, 1)
493}
494 
495UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
496{
497  UInt32 offset;
498  GET_MATCHES_HEADER(3)
499  HASH_ZIP_CALC;
500  curMatch = p->hash[hashValue];
501  p->hash[hashValue] = p->pos;
502  offset = 0;
503  GET_MATCHES_FOOTER(offset, 2)
504}
505 
506static UInt32 Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
507{
508  UInt32 hash2Value, delta2, maxLen, offset;
509  GET_MATCHES_HEADER(3)
510 
511  HASH3_CALC;
512 
513  delta2 = p->pos - p->hash[hash2Value];
514  curMatch = p->hash[kFix3HashSize + hashValue];
515   
516  p->hash[hash2Value] =
517  p->hash[kFix3HashSize + hashValue] = p->pos;
518 
519 
520  maxLen = 2;
521  offset = 0;
522  if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur)
523  {
524    for (; maxLen != lenLimit; maxLen++)
525      if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen])
526        break;
527    distances[0] = maxLen;
528    distances[1] = delta2 - 1;
529    offset = 2;
530    if (maxLen == lenLimit)
531    {
532      SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p));
533      MOVE_POS_RET;
534    }
535  }
536  GET_MATCHES_FOOTER(offset, maxLen)
537}
538 
539static UInt32 Bt4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
540{
541  UInt32 hash2Value, hash3Value, delta2, delta3, maxLen, offset;
542  GET_MATCHES_HEADER(4)
543 
544  HASH4_CALC;
545 
546  delta2 = p->pos - p->hash[                hash2Value];
547  delta3 = p->pos - p->hash[kFix3HashSize + hash3Value];
548  curMatch = p->hash[kFix4HashSize + hashValue];
549   
550  p->hash[                hash2Value] =
551  p->hash[kFix3HashSize + hash3Value] =
552  p->hash[kFix4HashSize + hashValue] = p->pos;
553 
554  maxLen = 1;
555  offset = 0;
556  if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur)
557  {
558    distances[0] = maxLen = 2;
559    distances[1] = delta2 - 1;
560    offset = 2;
561  }
562  if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur)
563  {
564    maxLen = 3;
565    distances[offset + 1] = delta3 - 1;
566    offset += 2;
567    delta2 = delta3;
568  }
569  if (offset != 0)
570  {
571    for (; maxLen != lenLimit; maxLen++)
572      if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen])
573        break;
574    distances[offset - 2] = maxLen;
575    if (maxLen == lenLimit)
576    {
577      SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p));
578      MOVE_POS_RET;
579    }
580  }
581  if (maxLen < 3)
582    maxLen = 3;
583  GET_MATCHES_FOOTER(offset, maxLen)
584}
585 
586static UInt32 Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
587{
588  UInt32 hash2Value, hash3Value, delta2, delta3, maxLen, offset;
589  GET_MATCHES_HEADER(4)
590 
591  HASH4_CALC;
592 
593  delta2 = p->pos - p->hash[                hash2Value];
594  delta3 = p->pos - p->hash[kFix3HashSize + hash3Value];
595  curMatch = p->hash[kFix4HashSize + hashValue];
596 
597  p->hash[                hash2Value] =
598  p->hash[kFix3HashSize + hash3Value] =
599  p->hash[kFix4HashSize + hashValue] = p->pos;
600 
601  maxLen = 1;
602  offset = 0;
603  if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur)
604  {
605    distances[0] = maxLen = 2;
606    distances[1] = delta2 - 1;
607    offset = 2;
608  }
609  if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur)
610  {
611    maxLen = 3;
612    distances[offset + 1] = delta3 - 1;
613    offset += 2;
614    delta2 = delta3;
615  }
616  if (offset != 0)
617  {
618    for (; maxLen != lenLimit; maxLen++)
619      if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen])
620        break;
621    distances[offset - 2] = maxLen;
622    if (maxLen == lenLimit)
623    {
624      p->son[p->cyclicBufferPos] = curMatch;
625      MOVE_POS_RET;
626    }
627  }
628  if (maxLen < 3)
629    maxLen = 3;
630  offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p),
631    distances + offset, maxLen) - (distances));
632  MOVE_POS_RET
633}
634 
635UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
636{
637  UInt32 offset;
638  GET_MATCHES_HEADER(3)
639  HASH_ZIP_CALC;
640  curMatch = p->hash[hashValue];
641  p->hash[hashValue] = p->pos;
642  offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p),
643    distances, 2) - (distances));
644  MOVE_POS_RET
645}
646 
647static void Bt2_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
648{
649  do
650  {
651    SKIP_HEADER(2)
652    HASH2_CALC;
653    curMatch = p->hash[hashValue];
654    p->hash[hashValue] = p->pos;
655    SKIP_FOOTER
656  }
657  while (--num != 0);
658}
659 
660void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
661{
662  do
663  {
664    SKIP_HEADER(3)
665    HASH_ZIP_CALC;
666    curMatch = p->hash[hashValue];
667    p->hash[hashValue] = p->pos;
668    SKIP_FOOTER
669  }
670  while (--num != 0);
671}
672 
673static void Bt3_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
674{
675  do
676  {
677    UInt32 hash2Value;
678    SKIP_HEADER(3)
679    HASH3_CALC;
680    curMatch = p->hash[kFix3HashSize + hashValue];
681    p->hash[hash2Value] =
682    p->hash[kFix3HashSize + hashValue] = p->pos;
683    SKIP_FOOTER
684  }
685  while (--num != 0);
686}
687 
688static void Bt4_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
689{
690  do
691  {
692    UInt32 hash2Value, hash3Value;
693    SKIP_HEADER(4)
694    HASH4_CALC;
695    curMatch = p->hash[kFix4HashSize + hashValue];
696    p->hash[                hash2Value] =
697    p->hash[kFix3HashSize + hash3Value] = p->pos;
698    p->hash[kFix4HashSize + hashValue] = p->pos;
699    SKIP_FOOTER
700  }
701  while (--num != 0);
702}
703 
704static void Hc4_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
705{
706  do
707  {
708    UInt32 hash2Value, hash3Value;
709    SKIP_HEADER(4)
710    HASH4_CALC;
711    curMatch = p->hash[kFix4HashSize + hashValue];
712    p->hash[                hash2Value] =
713    p->hash[kFix3HashSize + hash3Value] =
714    p->hash[kFix4HashSize + hashValue] = p->pos;
715    p->son[p->cyclicBufferPos] = curMatch;
716    MOVE_POS
717  }
718  while (--num != 0);
719}
720 
721void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
722{
723  do
724  {
725    SKIP_HEADER(3)
726    HASH_ZIP_CALC;
727    curMatch = p->hash[hashValue];
728    p->hash[hashValue] = p->pos;
729    p->son[p->cyclicBufferPos] = curMatch;
730    MOVE_POS
731  }
732  while (--num != 0);
733}
734 
735void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable)
736{
737  vTable->Init = (Mf_Init_Func)MatchFinder_Init;
738  vTable->GetIndexByte = (Mf_GetIndexByte_Func)MatchFinder_GetIndexByte;
739  vTable->GetNumAvailableBytes = (Mf_GetNumAvailableBytes_Func)MatchFinder_GetNumAvailableBytes;
740  vTable->GetPointerToCurrentPos = (Mf_GetPointerToCurrentPos_Func)MatchFinder_GetPointerToCurrentPos;
741  if (!p->btMode)
742  {
743    vTable->GetMatches = (Mf_GetMatches_Func)Hc4_MatchFinder_GetMatches;
744    vTable->Skip = (Mf_Skip_Func)Hc4_MatchFinder_Skip;
745  }
746  else if (p->numHashBytes == 2)
747  {
748    vTable->GetMatches = (Mf_GetMatches_Func)Bt2_MatchFinder_GetMatches;
749    vTable->Skip = (Mf_Skip_Func)Bt2_MatchFinder_Skip;
750  }
751  else if (p->numHashBytes == 3)
752  {
753    vTable->GetMatches = (Mf_GetMatches_Func)Bt3_MatchFinder_GetMatches;
754    vTable->Skip = (Mf_Skip_Func)Bt3_MatchFinder_Skip;
755  }
756  else
757  {
758    vTable->GetMatches = (Mf_GetMatches_Func)Bt4_MatchFinder_GetMatches;
759    vTable->Skip = (Mf_Skip_Func)Bt4_MatchFinder_Skip;
760  }
761}
src/lib/lib7z/Sort.c
r0r14440
1/* Sort.c -- Sort functions
22010-09-17 : Igor Pavlov : Public domain */
3 
4#include "Sort.h"
5 
6#define HeapSortDown(p, k, size, temp) \
7  { for (;;) { \
8    UInt32 s = (k << 1); \
9    if (s > size) break; \
10    if (s < size && p[s + 1] > p[s]) s++; \
11    if (temp >= p[s]) break; \
12    p[k] = p[s]; k = s; \
13  } p[k] = temp; }
14 
15void HeapSort(UInt32 *p, UInt32 size)
16{
17  if (size <= 1)
18    return;
19  p--;
20  {
21    UInt32 i = size / 2;
22    do
23    {
24      UInt32 temp = p[i];
25      UInt32 k = i;
26      HeapSortDown(p, k, size, temp)
27    }
28    while (--i != 0);
29  }
30  /*
31  do
32  {
33    UInt32 k = 1;
34    UInt32 temp = p[size];
35    p[size--] = p[1];
36    HeapSortDown(p, k, size, temp)
37  }
38  while (size > 1);
39  */
40  while (size > 3)
41  {
42    UInt32 temp = p[size];
43    UInt32 k = (p[3] > p[2]) ? 3 : 2;
44    p[size--] = p[1];
45    p[1] = p[k];
46    HeapSortDown(p, k, size, temp)
47  }
48  {
49    UInt32 temp = p[size];
50    p[size] = p[1];
51    if (size > 2 && p[2] < temp)
52    {
53      p[1] = p[2];
54      p[2] = temp;
55    }
56    else
57      p[1] = temp;
58  }
59}
60 
61/*
62#define HeapSortRefDown(p, vals, n, size, temp) \
63  { UInt32 k = n; UInt32 val = vals[temp]; for (;;) { \
64    UInt32 s = (k << 1); \
65    if (s > size) break; \
66    if (s < size && vals[p[s + 1]] > vals[p[s]]) s++; \
67    if (val >= vals[p[s]]) break; \
68    p[k] = p[s]; k = s; \
69  } p[k] = temp; }
70 
71void HeapSortRef(UInt32 *p, UInt32 *vals, UInt32 size)
72{
73  if (size <= 1)
74    return;
75  p--;
76  {
77    UInt32 i = size / 2;
78    do
79    {
80      UInt32 temp = p[i];
81      HeapSortRefDown(p, vals, i, size, temp);
82    }
83    while (--i != 0);
84  }
85  do
86  {
87    UInt32 temp = p[size];
88    p[size--] = p[1];
89    HeapSortRefDown(p, vals, 1, size, temp);
90  }
91  while (size > 1);
92}
93*/
src/lib/lib7z/Ppmd8.c
r0r14440
1/* Ppmd8.c -- PPMdI codec
22010-03-24 : Igor Pavlov : Public domain
3This code is based on PPMd var.I (2002): Dmitry Shkarin : Public domain */
4 
5#include <memory.h>
6 
7#include "Ppmd8.h"
8 
9const Byte PPMD8_kExpEscape[16] = { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 };
10static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051};
11 
12#define MAX_FREQ 124
13#define UNIT_SIZE 12
14 
15#define U2B(nu) ((UInt32)(nu) * UNIT_SIZE)
16#define U2I(nu) (p->Units2Indx[(nu) - 1])
17#define I2U(indx) (p->Indx2Units[indx])
18 
19#ifdef PPMD_32BIT
20  #define REF(ptr) (ptr)
21#else
22  #define REF(ptr) ((UInt32)((Byte *)(ptr) - (p)->Base))
23#endif
24 
25#define STATS_REF(ptr) ((CPpmd_State_Ref)REF(ptr))
26 
27#define CTX(ref) ((CPpmd8_Context *)Ppmd8_GetContext(p, ref))
28#define STATS(ctx) Ppmd8_GetStats(p, ctx)
29#define ONE_STATE(ctx) Ppmd8Context_OneState(ctx)
30#define SUFFIX(ctx) CTX((ctx)->Suffix)
31 
32typedef CPpmd8_Context * CTX_PTR;
33 
34struct CPpmd8_Node_;
35 
36typedef
37  #ifdef PPMD_32BIT
38    struct CPpmd8_Node_ *
39  #else
40    UInt32
41  #endif
42  CPpmd8_Node_Ref;
43 
44typedef struct CPpmd8_Node_
45{
46  UInt32 Stamp;
47  CPpmd8_Node_Ref Next;
48  UInt32 NU;
49} CPpmd8_Node;
50 
51#ifdef PPMD_32BIT
52  #define NODE(ptr) (ptr)
53#else
54  #define NODE(offs) ((CPpmd8_Node *)(p->Base + (offs)))
55#endif
56 
57#define EMPTY_NODE 0xFFFFFFFF
58 
59void Ppmd8_Construct(CPpmd8 *p)
60{
61  unsigned i, k, m;
62 
63  p->Base = 0;
64 
65  for (i = 0, k = 0; i < PPMD_NUM_INDEXES; i++)
66  {
67    unsigned step = (i >= 12 ? 4 : (i >> 2) + 1);
68    do { p->Units2Indx[k++] = (Byte)i; } while(--step);
69    p->Indx2Units[i] = (Byte)k;
70  }
71 
72  p->NS2BSIndx[0] = (0 << 1);
73  p->NS2BSIndx[1] = (1 << 1);
74  memset(p->NS2BSIndx + 2, (2 << 1), 9);
75  memset(p->NS2BSIndx + 11, (3 << 1), 256 - 11);
76 
77  for (i = 0; i < 5; i++)
78    p->NS2Indx[i] = (Byte)i;
79  for (m = i, k = 1; i < 260; i++)
80  {
81    p->NS2Indx[i] = (Byte)m;
82    if (--k == 0)
83      k = (++m) - 4;
84  }
85}
86 
87void Ppmd8_Free(CPpmd8 *p, ISzAlloc *alloc)
88{
89  alloc->Free(alloc, p->Base);
90  p->Size = 0;
91  p->Base = 0;
92}
93 
94Bool Ppmd8_Alloc(CPpmd8 *p, UInt32 size, ISzAlloc *alloc)
95{
96  if (p->Base == 0 || p->Size != size)
97  {
98    Ppmd8_Free(p, alloc);
99    p->AlignOffset =
100      #ifdef PPMD_32BIT
101        (4 - size) & 3;
102      #else
103        4 - (size & 3);
104      #endif
105    if ((p->Base = (Byte *)alloc->Alloc(alloc, p->AlignOffset + size)) == 0)
106      return False;
107    p->Size = size;
108  }
109  return True;
110}
111 
112static void InsertNode(CPpmd8 *p, void *node, unsigned indx)
113{
114  ((CPpmd8_Node *)node)->Stamp = EMPTY_NODE;
115  ((CPpmd8_Node *)node)->Next = (CPpmd8_Node_Ref)p->FreeList[indx];
116  ((CPpmd8_Node *)node)->NU = I2U(indx);
117  p->FreeList[indx] = REF(node);
118  p->Stamps[indx]++;
119}
120 
121static void *RemoveNode(CPpmd8 *p, unsigned indx)
122{
123  CPpmd8_Node *node = NODE((CPpmd8_Node_Ref)p->FreeList[indx]);
124  p->FreeList[indx] = node->Next;
125  p->Stamps[indx]--;
126  return node;
127}
128 
129static void SplitBlock(CPpmd8 *p, void *ptr, unsigned oldIndx, unsigned newIndx)
130{
131  unsigned i, nu = I2U(oldIndx) - I2U(newIndx);
132  ptr = (Byte *)ptr + U2B(I2U(newIndx));
133  if (I2U(i = U2I(nu)) != nu)
134  {
135    unsigned k = I2U(--i);
136    InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1);
137  }
138  InsertNode(p, ptr, i);
139}
140 
141static void GlueFreeBlocks(CPpmd8 *p)
142{
143  CPpmd8_Node_Ref head = 0;
144  CPpmd8_Node_Ref *prev = &head;
145  unsigned i;
146 
147  p->GlueCount = 1 << 13;
148  memset(p->Stamps, 0, sizeof(p->Stamps));
149   
150  /* Order-0 context is always at top UNIT, so we don't need guard NODE at the end.
151     All blocks up to p->LoUnit can be free, so we need guard NODE at LoUnit. */
152  if (p->LoUnit != p->HiUnit)
153    ((CPpmd8_Node *)p->LoUnit)->Stamp = 0;
154 
155  /* Glue free blocks */
156  for (i = 0; i < PPMD_NUM_INDEXES; i++)
157  {
158    CPpmd8_Node_Ref next = (CPpmd8_Node_Ref)p->FreeList[i];
159    p->FreeList[i] = 0;
160    while (next != 0)
161    {
162      CPpmd8_Node *node = NODE(next);
163      if (node->NU != 0)
164      {
165        CPpmd8_Node *node2;
166        *prev = next;
167        prev = &(node->Next);
168        while ((node2 = node + node->NU)->Stamp == EMPTY_NODE)
169        {
170          node->NU += node2->NU;
171          node2->NU = 0;
172        }
173      }
174      next = node->Next;
175    }
176  }
177  *prev = 0;
178   
179  /* Fill lists of free blocks */
180  while (head != 0)
181  {
182    CPpmd8_Node *node = NODE(head);
183    unsigned nu;
184    head = node->Next;
185    nu = node->NU;
186    if (nu == 0)
187      continue;
188    for (; nu > 128; nu -= 128, node += 128)
189      InsertNode(p, node, PPMD_NUM_INDEXES - 1);
190    if (I2U(i = U2I(nu)) != nu)
191    {
192      unsigned k = I2U(--i);
193      InsertNode(p, node + k, nu - k - 1);
194    }
195    InsertNode(p, node, i);
196  }
197}
198 
199static void *AllocUnitsRare(CPpmd8 *p, unsigned indx)
200{
201  unsigned i;
202  void *retVal;
203  if (p->GlueCount == 0)
204  {
205    GlueFreeBlocks(p);
206    if (p->FreeList[indx] != 0)
207      return RemoveNode(p, indx);
208  }
209  i = indx;
210  do
211  {
212    if (++i == PPMD_NUM_INDEXES)
213    {
214      UInt32 numBytes = U2B(I2U(indx));
215      p->GlueCount--;
216      return ((UInt32)(p->UnitsStart - p->Text) > numBytes) ? (p->UnitsStart -= numBytes) : (NULL);
217    }
218  }
219  while (p->FreeList[i] == 0);
220  retVal = RemoveNode(p, i);
221  SplitBlock(p, retVal, i, indx);
222  return retVal;
223}
224 
225static void *AllocUnits(CPpmd8 *p, unsigned indx)
226{
227  UInt32 numBytes;
228  if (p->FreeList[indx] != 0)
229    return RemoveNode(p, indx);
230  numBytes = U2B(I2U(indx));
231  if (numBytes <= (UInt32)(p->HiUnit - p->LoUnit))
232  {
233    void *retVal = p->LoUnit;
234    p->LoUnit += numBytes;
235    return retVal;
236  }
237  return AllocUnitsRare(p, indx);
238}
239 
240#define MyMem12Cpy(dest, src, num) \
241  { UInt32 *d = (UInt32 *)dest; const UInt32 *s = (const UInt32 *)src; UInt32 n = num; \
242    do { d[0] = s[0]; d[1] = s[1]; d[2] = s[2]; s += 3; d += 3; } while(--n); }
243 
244static void *ShrinkUnits(CPpmd8 *p, void *oldPtr, unsigned oldNU, unsigned newNU)
245{
246  unsigned i0 = U2I(oldNU);
247  unsigned i1 = U2I(newNU);
248  if (i0 == i1)
249    return oldPtr;
250  if (p->FreeList[i1] != 0)
251  {
252    void *ptr = RemoveNode(p, i1);
253    MyMem12Cpy(ptr, oldPtr, newNU);
254    InsertNode(p, oldPtr, i0);
255    return ptr;
256  }
257  SplitBlock(p, oldPtr, i0, i1);
258  return oldPtr;
259}
260 
261static void FreeUnits(CPpmd8 *p, void *ptr, unsigned nu)
262{
263  InsertNode(p, ptr, U2I(nu));
264}
265 
266static void SpecialFreeUnit(CPpmd8 *p, void *ptr)
267{
268  if ((Byte *)ptr != p->UnitsStart)
269    InsertNode(p, ptr, 0);
270  else
271  {
272    #ifdef PPMD8_FREEZE_SUPPORT
273    *(UInt32 *)ptr = EMPTY_NODE; /* it's used for (Flags == 0xFF) check in RemoveBinContexts */
274    #endif
275    p->UnitsStart += UNIT_SIZE;
276  }
277}
278 
279static void *MoveUnitsUp(CPpmd8 *p, void *oldPtr, unsigned nu)
280{
281  unsigned indx = U2I(nu);
282  void *ptr;
283  if ((Byte *)oldPtr > p->UnitsStart + 16 * 1024 || REF(oldPtr) > p->FreeList[indx])
284    return oldPtr;
285  ptr = RemoveNode(p, indx);
286  MyMem12Cpy(ptr, oldPtr, nu);
287  if ((Byte*)oldPtr != p->UnitsStart)
288    InsertNode(p, oldPtr, indx);
289  else
290    p->UnitsStart += U2B(I2U(indx));
291  return ptr;
292}
293 
294static void ExpandTextArea(CPpmd8 *p)
295{
296  UInt32 count[PPMD_NUM_INDEXES];
297  unsigned i;
298  memset(count, 0, sizeof(count));
299  if (p->LoUnit != p->HiUnit)
300    ((CPpmd8_Node *)p->LoUnit)->Stamp = 0;
301   
302  {
303    CPpmd8_Node *node = (CPpmd8_Node *)p->UnitsStart;
304    for (; node->Stamp == EMPTY_NODE; node += node->NU)
305    {
306      node->Stamp = 0;
307      count[U2I(node->NU)]++;
308    }
309    p->UnitsStart = (Byte *)node;
310  }
311   
312  for (i = 0; i < PPMD_NUM_INDEXES; i++)
313  {
314    CPpmd8_Node_Ref *next = (CPpmd8_Node_Ref *)&p->FreeList[i];
315    while (count[i] != 0)
316    {
317      CPpmd8_Node *node = NODE(*next);
318      while (node->Stamp == 0)
319      {
320        *next = node->Next;
321        node = NODE(*next);
322        p->Stamps[i]--;
323        if (--count[i] == 0)
324          break;
325      }
326      next = &node->Next;
327    }
328  }
329}
330 
331#define SUCCESSOR(p) ((CPpmd_Void_Ref)((p)->SuccessorLow | ((UInt32)(p)->SuccessorHigh << 16)))
332 
333static void SetSuccessor(CPpmd_State *p, CPpmd_Void_Ref v)
334{
335  (p)->SuccessorLow = (UInt16)((UInt32)(v) & 0xFFFF);
336  (p)->SuccessorHigh = (UInt16)(((UInt32)(v) >> 16) & 0xFFFF);
337}
338 
339#define RESET_TEXT(offs) { p->Text = p->Base + p->AlignOffset + (offs); }
340 
341static void RestartModel(CPpmd8 *p)
342{
343  unsigned i, k, m, r;
344 
345  memset(p->FreeList, 0, sizeof(p->FreeList));
346  memset(p->Stamps, 0, sizeof(p->Stamps));
347  RESET_TEXT(0);
348  p->HiUnit = p->Text + p->Size;
349  p->LoUnit = p->UnitsStart = p->HiUnit - p->Size / 8 / UNIT_SIZE * 7 * UNIT_SIZE;
350  p->GlueCount = 0;
351 
352  p->OrderFall = p->MaxOrder;
353  p->RunLength = p->InitRL = -(Int32)((p->MaxOrder < 12) ? p->MaxOrder : 12) - 1;
354  p->PrevSuccess = 0;
355 
356  p->MinContext = p->MaxContext = (CTX_PTR)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */
357  p->MinContext->Suffix = 0;
358  p->MinContext->NumStats = 255;
359  p->MinContext->Flags = 0;
360  p->MinContext->SummFreq = 256 + 1;
361  p->FoundState = (CPpmd_State *)p->LoUnit; /* AllocUnits(p, PPMD_NUM_INDEXES - 1); */
362  p->LoUnit += U2B(256 / 2);
363  p->MinContext->Stats = REF(p->FoundState);
364  for (i = 0; i < 256; i++)
365  {
366    CPpmd_State *s = &p->FoundState[i];
367    s->Symbol = (Byte)i;
368    s->Freq = 1;
369    SetSuccessor(s, 0);
370  }
371 
372  for (i = m = 0; m < 25; m++)
373  {
374    while (p->NS2Indx[i] == m)
375      i++;
376    for (k = 0; k < 8; k++)
377    {
378      UInt16 val = (UInt16)(PPMD_BIN_SCALE - kInitBinEsc[k] / (i + 1));
379      UInt16 *dest = p->BinSumm[m] + k;
380      for (r = 0; r < 64; r += 8)
381        dest[r] = val;
382    }
383  }
384 
385  for (i = m = 0; m < 24; m++)
386  {
387    while (p->NS2Indx[i + 3] == m + 3)
388      i++;
389    for (k = 0; k < 32; k++)
390    {
391      CPpmd_See *s = &p->See[m][k];
392      s->Summ = (UInt16)((2 * i + 5) << (s->Shift = PPMD_PERIOD_BITS - 4));
393      s->Count = 7;
394    }
395  }
396}
397 
398void Ppmd8_Init(CPpmd8 *p, unsigned maxOrder, unsigned restoreMethod)
399{
400  p->MaxOrder = maxOrder;
401  p->RestoreMethod = restoreMethod;
402  RestartModel(p);
403  p->DummySee.Shift = PPMD_PERIOD_BITS;
404  p->DummySee.Summ = 0; /* unused */
405  p->DummySee.Count = 64; /* unused */
406}
407 
408static void Refresh(CPpmd8 *p, CTX_PTR ctx, unsigned oldNU, unsigned scale)
409{
410  unsigned i = ctx->NumStats, escFreq, sumFreq, flags;
411  CPpmd_State *s = (CPpmd_State *)ShrinkUnits(p, STATS(ctx), oldNU, (i + 2) >> 1);
412  ctx->Stats = REF(s);
413  #ifdef PPMD8_FREEZE_SUPPORT
414  /* fixed over Shkarin's code. Fixed code is not compatible with original code for some files in FREEZE mode. */
415  scale |= (ctx->SummFreq >= ((UInt32)1 << 15));
416  #endif
417  flags = (ctx->Flags & (0x10 + 0x04 * scale)) + 0x08 * (s->Symbol >= 0x40);
418  escFreq = ctx->SummFreq - s->Freq;
419  sumFreq = (s->Freq = (Byte)((s->Freq + scale) >> scale));
420  do
421  {
422    escFreq -= (++s)->Freq;
423    sumFreq += (s->Freq = (Byte)((s->Freq + scale) >> scale));
424    flags |= 0x08 * (s->Symbol >= 0x40);
425  }
426  while (--i);
427  ctx->SummFreq = (UInt16)(sumFreq + ((escFreq + scale) >> scale));
428  ctx->Flags = (Byte)flags;
429}
430 
431static void SwapStates(CPpmd_State *t1, CPpmd_State *t2)
432{
433  CPpmd_State tmp = *t1;
434  *t1 = *t2;
435  *t2 = tmp;
436}
437 
438static CPpmd_Void_Ref CutOff(CPpmd8 *p, CTX_PTR ctx, unsigned order)
439{
440  int i;
441  unsigned tmp;
442  CPpmd_State *s;
443   
444  if (!ctx->NumStats)
445  {
446    s = ONE_STATE(ctx);
447    if ((Byte *)Ppmd8_GetPtr(p, SUCCESSOR(s)) >= p->UnitsStart)
448    {
449      if (order < p->MaxOrder)
450        SetSuccessor(s, CutOff(p, CTX(SUCCESSOR(s)), order + 1));
451      else
452        SetSuccessor(s, 0);
453      if (SUCCESSOR(s) || order <= 9) /* O_BOUND */
454        return REF(ctx);
455    }
456    SpecialFreeUnit(p, ctx);
457    return 0;
458  }
459 
460  ctx->Stats = STATS_REF(MoveUnitsUp(p, STATS(ctx), tmp = ((unsigned)ctx->NumStats + 2) >> 1));
461 
462  for (s = STATS(ctx) + (i = ctx->NumStats); s >= STATS(ctx); s--)
463    if ((Byte *)Ppmd8_GetPtr(p, SUCCESSOR(s)) < p->UnitsStart)
464    {
465      CPpmd_State *s2 = STATS(ctx) + (i--);
466      SetSuccessor(s, 0);
467      SwapStates(s, s2);
468    }
469    else if (order < p->MaxOrder)
470      SetSuccessor(s, CutOff(p, CTX(SUCCESSOR(s)), order + 1));
471    else
472      SetSuccessor(s, 0);
473     
474  if (i != ctx->NumStats && order)
475  {
476    ctx->NumStats = (Byte)i;
477    s = STATS(ctx);
478    if (i < 0)
479    {
480      FreeUnits(p, s, tmp);
481      SpecialFreeUnit(p, ctx);
482      return 0;
483    }
484    if (i == 0)
485    {
486      ctx->Flags = (ctx->Flags & 0x10) + 0x08 * (s->Symbol >= 0x40);
487      *ONE_STATE(ctx) = *s;
488      FreeUnits(p, s, tmp);
489      ONE_STATE(ctx)->Freq = (Byte)((unsigned)ONE_STATE(ctx)->Freq + 11) >> 3;
490    }
491    else
492      Refresh(p, ctx, tmp, ctx->SummFreq > 16 * i);
493  }
494  return REF(ctx);
495}
496 
497#ifdef PPMD8_FREEZE_SUPPORT
498static CPpmd_Void_Ref RemoveBinContexts(CPpmd8 *p, CTX_PTR ctx, unsigned order)
499{
500  CPpmd_State *s;
501  if (!ctx->NumStats)
502  {
503    s = ONE_STATE(ctx);
504    if ((Byte *)Ppmd8_GetPtr(p, SUCCESSOR(s)) >= p->UnitsStart && order < p->MaxOrder)
505      SetSuccessor(s, RemoveBinContexts(p, CTX(SUCCESSOR(s)), order + 1));
506    else
507      SetSuccessor(s, 0);
508    /* Suffix context can be removed already, since different (high-order)
509       Successors may refer to same context. So we check Flags == 0xFF (Stamp == EMPTY_NODE) */
510    if (!SUCCESSOR(s) && (!SUFFIX(ctx)->NumStats || SUFFIX(ctx)->Flags == 0xFF))
511    {
512      FreeUnits(p, ctx, 1);
513      return 0;
514    }
515    else
516      return REF(ctx);
517  }
518 
519  for (s = STATS(ctx) + ctx->NumStats; s >= STATS(ctx); s--)
520    if ((Byte *)Ppmd8_GetPtr(p, SUCCESSOR(s)) >= p->UnitsStart && order < p->MaxOrder)
521      SetSuccessor(s, RemoveBinContexts(p, CTX(SUCCESSOR(s)), order + 1));
522    else
523      SetSuccessor(s, 0);
524   
525  return REF(ctx);
526}
527#endif
528 
529static UInt32 GetUsedMemory(const CPpmd8 *p)
530{
531  UInt32 v = 0;
532  unsigned i;
533  for (i = 0; i < PPMD_NUM_INDEXES; i++)
534    v += p->Stamps[i] * I2U(i);
535  return p->Size - (UInt32)(p->HiUnit - p->LoUnit) - (UInt32)(p->UnitsStart - p->Text) - U2B(v);
536}
537 
538#ifdef PPMD8_FREEZE_SUPPORT
539  #define RESTORE_MODEL(c1, fSuccessor) RestoreModel(p, c1, fSuccessor)
540#else
541  #define RESTORE_MODEL(c1, fSuccessor) RestoreModel(p, c1)
542#endif
543 
544static void RestoreModel(CPpmd8 *p, CTX_PTR c1
545    #ifdef PPMD8_FREEZE_SUPPORT
546    , CTX_PTR fSuccessor
547    #endif
548    )
549{
550  CTX_PTR c;
551  CPpmd_State *s;
552  RESET_TEXT(0);
553  for (c = p->MaxContext; c != c1; c = SUFFIX(c))
554    if (--(c->NumStats) == 0)
555    {
556      s = STATS(c);
557      c->Flags = (c->Flags & 0x10) + 0x08 * (s->Symbol >= 0x40);
558      *ONE_STATE(c) = *s;
559      SpecialFreeUnit(p, s);
560      ONE_STATE(c)->Freq = (ONE_STATE(c)->Freq + 11) >> 3;
561    }
562    else
563      Refresh(p, c, (c->NumStats+3) >> 1, 0);
564 
565  for (; c != p->MinContext; c = SUFFIX(c))
566    if (!c->NumStats)
567      ONE_STATE(c)->Freq -= ONE_STATE(c)->Freq >> 1;
568    else if ((c->SummFreq += 4) > 128 + 4 * c->NumStats)
569      Refresh(p, c, (c->NumStats + 2) >> 1, 1);
570 
571  #ifdef PPMD8_FREEZE_SUPPORT
572  if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE)
573  {
574    p->MaxContext = fSuccessor;
575    p->GlueCount += !(p->Stamps[1] & 1);
576  }
577  else if (p->RestoreMethod == PPMD8_RESTORE_METHOD_FREEZE)
578  {
579    while (p->MaxContext->Suffix)
580      p->MaxContext = SUFFIX(p->MaxContext);
581    RemoveBinContexts(p, p->MaxContext, 0);
582    p->RestoreMethod++;
583    p->GlueCount = 0;
584    p->OrderFall = p->MaxOrder;
585  }
586  else
587  #endif
588  if (p->RestoreMethod == PPMD8_RESTORE_METHOD_RESTART || GetUsedMemory(p) < (p->Size >> 1))
589    RestartModel(p);
590  else
591  {
592    while (p->MaxContext->Suffix)
593      p->MaxContext = SUFFIX(p->MaxContext);
594    do
595    {
596      CutOff(p, p->MaxContext, 0);
597      ExpandTextArea(p);
598    }
599    while (GetUsedMemory(p) > 3 * (p->Size >> 2));
600    p->GlueCount = 0;
601    p->OrderFall = p->MaxOrder;
602  }
603}
604 
605static CTX_PTR CreateSuccessors(CPpmd8 *p, Bool skip, CPpmd_State *s1, CTX_PTR c)
606{
607  CPpmd_State upState;
608  Byte flags;
609  CPpmd_Byte_Ref upBranch = (CPpmd_Byte_Ref)SUCCESSOR(p->FoundState);
610  /* fixed over Shkarin's code. Maybe it could work without + 1 too. */
611  CPpmd_State *ps[PPMD8_MAX_ORDER + 1];
612  unsigned numPs = 0;
613   
614  if (!skip)
615    ps[numPs++] = p->FoundState;
616   
617  while (c->Suffix)
618  {
619    CPpmd_Void_Ref successor;
620    CPpmd_State *s;
621    c = SUFFIX(c);
622    if (s1)
623    {
624      s = s1;
625      s1 = NULL;
626    }
627    else if (c->NumStats != 0)
628    {
629      for (s = STATS(c); s->Symbol != p->FoundState->Symbol; s++);
630      if (s->Freq < MAX_FREQ - 9)
631      {
632        s->Freq++;
633        c->SummFreq++;
634      }
635    }
636    else
637    {
638      s = ONE_STATE(c);
639      s->Freq += (!SUFFIX(c)->NumStats & (s->Freq < 24));
640    }
641    successor = SUCCESSOR(s);
642    if (successor != upBranch)
643    {
644      c = CTX(successor);
645      if (numPs == 0)
646        return c;
647      break;
648    }
649    ps[numPs++] = s;
650  }
651   
652  upState.Symbol = *(const Byte *)Ppmd8_GetPtr(p, upBranch);
653  SetSuccessor(&upState, upBranch + 1);
654  flags = 0x10 * (p->FoundState->Symbol >= 0x40) + 0x08 * (upState.Symbol >= 0x40);
655 
656  if (c->NumStats == 0)
657    upState.Freq = ONE_STATE(c)->Freq;
658  else
659  {
660    UInt32 cf, s0;
661    CPpmd_State *s;
662    for (s = STATS(c); s->Symbol != upState.Symbol; s++);
663    cf = s->Freq - 1;
664    s0 = c->SummFreq - c->NumStats - cf;
665    upState.Freq = (Byte)(1 + ((2 * cf <= s0) ? (5 * cf > s0) : ((cf + 2 * s0 - 3) / s0)));
666  }
667 
668  do
669  {
670    /* Create Child */
671    CTX_PTR c1; /* = AllocContext(p); */
672    if (p->HiUnit != p->LoUnit)
673      c1 = (CTX_PTR)(p->HiUnit -= UNIT_SIZE);
674    else if (p->FreeList[0] != 0)
675      c1 = (CTX_PTR)RemoveNode(p, 0);
676    else
677    {
678      c1 = (CTX_PTR)AllocUnitsRare(p, 0);
679      if (!c1)
680        return NULL;
681    }
682    c1->NumStats = 0;
683    c1->Flags = flags;
684    *ONE_STATE(c1) = upState;
685    c1->Suffix = REF(c);
686    SetSuccessor(ps[--numPs], REF(c1));
687    c = c1;
688  }
689  while (numPs != 0);
690   
691  return c;
692}
693 
694static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c)
695{
696  CPpmd_State *s = NULL;
697  CTX_PTR c1 = c;
698  CPpmd_Void_Ref upBranch = REF(p->Text);
699   
700  #ifdef PPMD8_FREEZE_SUPPORT
701  /* The BUG in Shkarin's code was fixed: ps could overflow in CUT_OFF mode. */
702  CPpmd_State *ps[PPMD8_MAX_ORDER + 1];
703  unsigned numPs = 0;
704  ps[numPs++] = p->FoundState;
705  #endif
706 
707  SetSuccessor(p->FoundState, upBranch);
708  p->OrderFall++;
709 
710  for (;;)
711  {
712    if (s1)
713    {
714      c = SUFFIX(c);
715      s = s1;
716      s1 = NULL;
717    }
718    else
719    {
720      if (!c->Suffix)
721      {
722        #ifdef PPMD8_FREEZE_SUPPORT
723        if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE)
724        {
725          do { SetSuccessor(ps[--numPs], REF(c)); } while (numPs);
726          RESET_TEXT(1);
727          p->OrderFall = 1;
728        }
729        #endif
730        return c;
731      }
732      c = SUFFIX(c);
733      if (c->NumStats)
734      {
735        if ((s = STATS(c))->Symbol != p->FoundState->Symbol)
736          do { s++; } while (s->Symbol != p->FoundState->Symbol);
737        if (s->Freq < MAX_FREQ - 9)
738        {
739          s->Freq += 2;
740          c->SummFreq += 2;
741        }
742      }
743      else
744      {
745        s = ONE_STATE(c);
746        s->Freq += (s->Freq < 32);
747      }
748    }
749    if (SUCCESSOR(s))
750      break;
751    #ifdef PPMD8_FREEZE_SUPPORT
752    ps[numPs++] = s;
753    #endif
754    SetSuccessor(s, upBranch);
755    p->OrderFall++;
756  }
757   
758  #ifdef PPMD8_FREEZE_SUPPORT
759  if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE)
760  {
761    c = CTX(SUCCESSOR(s));
762    do { SetSuccessor(ps[--numPs], REF(c)); } while (numPs);
763    RESET_TEXT(1);
764    p->OrderFall = 1;
765    return c;
766  }
767  else
768  #endif
769  if (SUCCESSOR(s) <= upBranch)
770  {
771    CTX_PTR successor;
772    CPpmd_State *s1 = p->FoundState;
773    p->FoundState = s;
774 
775    successor = CreateSuccessors(p, False, NULL, c);
776    if (successor == NULL)
777      SetSuccessor(s, 0);
778    else
779      SetSuccessor(s, REF(successor));
780    p->FoundState = s1;
781  }
782   
783  if (p->OrderFall == 1 && c1 == p->MaxContext)
784  {
785    SetSuccessor(p->FoundState, SUCCESSOR(s));
786    p->Text--;
787  }
788  if (SUCCESSOR(s) == 0)
789    return NULL;
790  return CTX(SUCCESSOR(s));
791}
792 
793static void UpdateModel(CPpmd8 *p)
794{
795  CPpmd_Void_Ref successor, fSuccessor = SUCCESSOR(p->FoundState);
796  CTX_PTR c;
797  unsigned s0, ns, fFreq = p->FoundState->Freq;
798  Byte flag, fSymbol = p->FoundState->Symbol;
799  CPpmd_State *s = NULL;
800   
801  if (p->FoundState->Freq < MAX_FREQ / 4 && p->MinContext->Suffix != 0)
802  {
803    c = SUFFIX(p->MinContext);
804     
805    if (c->NumStats == 0)
806    {
807      s = ONE_STATE(c);
808      if (s->Freq < 32)
809        s->Freq++;
810    }
811    else
812    {
813      s = STATS(c);
814      if (s->Symbol != p->FoundState->Symbol)
815      {
816        do { s++; } while (s->Symbol != p->FoundState->Symbol);
817        if (s[0].Freq >= s[-1].Freq)
818        {
819          SwapStates(&s[0], &s[-1]);
820          s--;
821        }
822      }
823      if (s->Freq < MAX_FREQ - 9)
824      {
825        s->Freq += 2;
826        c->SummFreq += 2;
827      }
828    }
829  }
830   
831  c = p->MaxContext;
832  if (p->OrderFall == 0 && fSuccessor)
833  {
834    CTX_PTR cs = CreateSuccessors(p, True, s, p->MinContext);
835    if (cs == 0)
836    {
837      SetSuccessor(p->FoundState, 0);
838      RESTORE_MODEL(c, CTX(fSuccessor));
839    }
840    else
841    {
842      SetSuccessor(p->FoundState, REF(cs));
843      p->MaxContext = cs;
844    }
845    return;
846  }
847   
848  *p->Text++ = p->FoundState->Symbol;
849  successor = REF(p->Text);
850  if (p->Text >= p->UnitsStart)
851  {
852    RESTORE_MODEL(c, CTX(fSuccessor)); /* check it */
853    return;
854  }
855   
856  if (!fSuccessor)
857  {
858    CTX_PTR cs = ReduceOrder(p, s, p->MinContext);
859    if (cs == NULL)
860    {
861      RESTORE_MODEL(c, 0);
862      return;
863    }
864    fSuccessor = REF(cs);
865  }
866  else if ((Byte *)Ppmd8_GetPtr(p, fSuccessor) < p->UnitsStart)
867  {
868    CTX_PTR cs = CreateSuccessors(p, False, s, p->MinContext);
869    if (cs == NULL)
870    {
871      RESTORE_MODEL(c, 0);
872      return;
873    }
874    fSuccessor = REF(cs);
875  }
876   
877  if (--p->OrderFall == 0)
878  {
879    successor = fSuccessor;
880    p->Text -= (p->MaxContext != p->MinContext);
881  }
882  #ifdef PPMD8_FREEZE_SUPPORT
883  else if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE)
884  {
885    successor = fSuccessor;
886    RESET_TEXT(0);
887    p->OrderFall = 0;
888  }
889  #endif
890   
891  s0 = p->MinContext->SummFreq - (ns = p->MinContext->NumStats) - fFreq;
892  flag = 0x08 * (fSymbol >= 0x40);
893   
894  for (; c != p->MinContext; c = SUFFIX(c))
895  {
896    unsigned ns1;
897    UInt32 cf, sf;
898    if ((ns1 = c->NumStats) != 0)
899    {
900      if ((ns1 & 1) != 0)
901      {
902        /* Expand for one UNIT */
903        unsigned oldNU = (ns1 + 1) >> 1;
904        unsigned i = U2I(oldNU);
905        if (i != U2I(oldNU + 1))
906        {
907          void *ptr = AllocUnits(p, i + 1);
908          void *oldPtr;
909          if (!ptr)
910          {
911            RESTORE_MODEL(c, CTX(fSuccessor));
912            return;
913          }
914          oldPtr = STATS(c);
915          MyMem12Cpy(ptr, oldPtr, oldNU);
916          InsertNode(p, oldPtr, i);
917          c->Stats = STATS_REF(ptr);
918        }
919      }
920      c->SummFreq = (UInt16)(c->SummFreq + (3 * ns1 + 1 < ns));
921    }
922    else
923    {
924      CPpmd_State *s = (CPpmd_State*)AllocUnits(p, 0);
925      if (!s)
926      {
927        RESTORE_MODEL(c, CTX(fSuccessor));
928        return;
929      }
930      *s = *ONE_STATE(c);
931      c->Stats = REF(s);
932      if (s->Freq < MAX_FREQ / 4 - 1)
933        s->Freq <<= 1;
934      else
935        s->Freq = MAX_FREQ - 4;
936      c->SummFreq = (UInt16)(s->Freq + p->InitEsc + (ns > 2));
937    }
938    cf = 2 * fFreq * (c->SummFreq + 6);
939    sf = (UInt32)s0 + c->SummFreq;
940    if (cf < 6 * sf)
941    {
942      cf = 1 + (cf > sf) + (cf >= 4 * sf);
943      c->SummFreq += 4;
944    }
945    else
946    {
947      cf = 4 + (cf > 9 * sf) + (cf > 12 * sf) + (cf > 15 * sf);
948      c->SummFreq = (UInt16)(c->SummFreq + cf);
949    }
950    {
951      CPpmd_State *s = STATS(c) + ns1 + 1;
952      SetSuccessor(s, successor);
953      s->Symbol = fSymbol;
954      s->Freq = (Byte)cf;
955      c->Flags |= flag;
956      c->NumStats = (Byte)(ns1 + 1);
957    }
958  }
959  p->MaxContext = p->MinContext = CTX(fSuccessor);
960}
961   
962static void Rescale(CPpmd8 *p)
963{
964  unsigned i, adder, sumFreq, escFreq;
965  CPpmd_State *stats = STATS(p->MinContext);
966  CPpmd_State *s = p->FoundState;
967  {
968    CPpmd_State tmp = *s;
969    for (; s != stats; s--)
970      s[0] = s[-1];
971    *s = tmp;
972  }
973  escFreq = p->MinContext->SummFreq - s->Freq;
974  s->Freq += 4;
975  adder = (p->OrderFall != 0
976      #ifdef PPMD8_FREEZE_SUPPORT
977      || p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE
978      #endif
979      );
980  s->Freq = (Byte)((s->Freq + adder) >> 1);
981  sumFreq = s->Freq;
982   
983  i = p->MinContext->NumStats;
984  do
985  {
986    escFreq -= (++s)->Freq;
987    s->Freq = (Byte)((s->Freq + adder) >> 1);
988    sumFreq += s->Freq;
989    if (s[0].Freq > s[-1].Freq)
990    {
991      CPpmd_State *s1 = s;
992      CPpmd_State tmp = *s1;
993      do
994        s1[0] = s1[-1];
995      while (--s1 != stats && tmp.Freq > s1[-1].Freq);
996      *s1 = tmp;
997    }
998  }
999  while (--i);
1000   
1001  if (s->Freq == 0)
1002  {
1003    unsigned numStats = p->MinContext->NumStats;
1004    unsigned n0, n1;
1005    do { i++; } while ((--s)->Freq == 0);
1006    escFreq += i;
1007    p->MinContext->NumStats = (Byte)(p->MinContext->NumStats - i);
1008    if (p->MinContext->NumStats == 0)
1009    {
1010      CPpmd_State tmp = *stats;
1011      tmp.Freq = (Byte)((2 * tmp.Freq + escFreq - 1) / escFreq);
1012      if (tmp.Freq > MAX_FREQ / 3)
1013        tmp.Freq = MAX_FREQ / 3;
1014      InsertNode(p, stats, U2I((numStats + 2) >> 1));
1015      p->MinContext->Flags = (p->MinContext->Flags & 0x10) + 0x08 * (tmp.Symbol >= 0x40);
1016      *(p->FoundState = ONE_STATE(p->MinContext)) = tmp;
1017      return;
1018    }
1019    n0 = (numStats + 2) >> 1;
1020    n1 = (p->MinContext->NumStats + 2) >> 1;
1021    if (n0 != n1)
1022      p->MinContext->Stats = STATS_REF(ShrinkUnits(p, stats, n0, n1));
1023    p->MinContext->Flags &= ~0x08;
1024    p->MinContext->Flags |= 0x08 * ((s = STATS(p->MinContext))->Symbol >= 0x40);
1025    i = p->MinContext->NumStats;
1026    do { p->MinContext->Flags |= 0x08*((++s)->Symbol >= 0x40); } while (--i);
1027  }
1028  p->MinContext->SummFreq = (UInt16)(sumFreq + escFreq - (escFreq >> 1));
1029  p->MinContext->Flags |= 0x4;
1030  p->FoundState = STATS(p->MinContext);
1031}
1032 
1033CPpmd_See *Ppmd8_MakeEscFreq(CPpmd8 *p, unsigned numMasked1, UInt32 *escFreq)
1034{
1035  CPpmd_See *see;
1036  if (p->MinContext->NumStats != 0xFF)
1037  {
1038    see = p->See[p->NS2Indx[p->MinContext->NumStats + 2] - 3] +
1039        (p->MinContext->SummFreq > 11 * ((unsigned)p->MinContext->NumStats + 1)) +
1040        2 * (2 * (unsigned)p->MinContext->NumStats <
1041        ((unsigned)SUFFIX(p->MinContext)->NumStats + numMasked1)) +
1042        p->MinContext->Flags;
1043    {
1044      unsigned r = (see->Summ >> see->Shift);
1045      see->Summ = (UInt16)(see->Summ - r);
1046      *escFreq = r + (r == 0);
1047    }
1048  }
1049  else
1050  {
1051    see = &p->DummySee;
1052    *escFreq = 1;
1053  }
1054  return see;
1055}
1056 
1057static void NextContext(CPpmd8 *p)
1058{
1059  CTX_PTR c = CTX(SUCCESSOR(p->FoundState));
1060  if (p->OrderFall == 0 && (Byte *)c >= p->UnitsStart)
1061    p->MinContext = p->MaxContext = c;
1062  else
1063  {
1064    UpdateModel(p);
1065    p->MinContext = p->MaxContext;
1066  }
1067}
1068 
1069void Ppmd8_Update1(CPpmd8 *p)
1070{
1071  CPpmd_State *s = p->FoundState;
1072  s->Freq += 4;
1073  p->MinContext->SummFreq += 4;
1074  if (s[0].Freq > s[-1].Freq)
1075  {
1076    SwapStates(&s[0], &s[-1]);
1077    p->FoundState = --s;
1078    if (s->Freq > MAX_FREQ)
1079      Rescale(p);
1080  }
1081  NextContext(p);
1082}
1083 
1084void Ppmd8_Update1_0(CPpmd8 *p)
1085{
1086  p->PrevSuccess = (2 * p->FoundState->Freq >= p->MinContext->SummFreq);
1087  p->RunLength += p->PrevSuccess;
1088  p->MinContext->SummFreq += 4;
1089  if ((p->FoundState->Freq += 4) > MAX_FREQ)
1090    Rescale(p);
1091  NextContext(p);
1092}
1093 
1094void Ppmd8_UpdateBin(CPpmd8 *p)
1095{
1096  p->FoundState->Freq = (Byte)(p->FoundState->Freq + (p->FoundState->Freq < 196));
1097  p->PrevSuccess = 1;
1098  p->RunLength++;
1099  NextContext(p);
1100}
1101 
1102void Ppmd8_Update2(CPpmd8 *p)
1103{
1104  p->MinContext->SummFreq += 4;
1105  if ((p->FoundState->Freq += 4) > MAX_FREQ)
1106    Rescale(p);
1107  p->RunLength = p->InitRL;
1108  UpdateModel(p);
1109  p->MinContext = p->MaxContext;
1110}
1111 
1112/* H->I changes:
1113  NS2Indx
1114  GlewCount, and Glue method
1115  BinSum
1116  See / EscFreq
1117  CreateSuccessors updates more suffix contexts
1118  UpdateModel consts.
1119  PrevSuccess Update
1120*/
src/lib/lib7z/7zVersion.rc
r0r14440
1#define MY_VS_FFI_FILEFLAGSMASK  0x0000003FL
2#define MY_VOS_NT_WINDOWS32  0x00040004L
3#define MY_VOS_CE_WINDOWS32  0x00050004L
4 
5#define MY_VFT_APP  0x00000001L
6#define MY_VFT_DLL  0x00000002L
7 
8// #include <WinVer.h>
9 
10#ifndef MY_VERSION
11#include "7zVersion.h"
12#endif
13 
14#define MY_VER MY_VER_MAJOR,MY_VER_MINOR,MY_VER_BUILD,0
15 
16#ifdef DEBUG
17#define DBG_FL VS_FF_DEBUG
18#else
19#define DBG_FL 0
20#endif
21 
22#define MY_VERSION_INFO(fileType, descr, intName, origName)  \
23LANGUAGE 9, 1 \
241 VERSIONINFO \
25  FILEVERSION MY_VER \
26  PRODUCTVERSION MY_VER \
27  FILEFLAGSMASK MY_VS_FFI_FILEFLAGSMASK \
28  FILEFLAGS DBG_FL \
29  FILEOS MY_VOS_NT_WINDOWS32 \
30  FILETYPE fileType \
31  FILESUBTYPE 0x0L \
32BEGIN \
33    BLOCK "StringFileInfo" \
34    BEGIN  \
35        BLOCK "040904b0" \
36        BEGIN \
37            VALUE "CompanyName", "Igor Pavlov" \
38            VALUE "FileDescription", descr \
39            VALUE "FileVersion", MY_VERSION  \
40            VALUE "InternalName", intName \
41            VALUE "LegalCopyright", MY_COPYRIGHT \
42            VALUE "OriginalFilename", origName \
43            VALUE "ProductName", "7-Zip" \
44            VALUE "ProductVersion", MY_VERSION \
45        END \
46    END \
47    BLOCK "VarFileInfo" \
48    BEGIN \
49        VALUE "Translation", 0x409, 1200 \
50    END \
51END
52 
53#define MY_VERSION_INFO_APP(descr, intName) MY_VERSION_INFO(MY_VFT_APP, descr, intName, intName ".exe")
54 
55#define MY_VERSION_INFO_DLL(descr, intName) MY_VERSION_INFO(MY_VFT_DLL, descr, intName, intName ".dll")
src/lib/lib7z/7zCrc.c
r0r14440
1/* 7zCrc.c -- CRC32 init
22010-12-01 : Igor Pavlov : Public domain */
3 
4#include "7zCrc.h"
5#include "CpuArch.h"
6 
7#define kCrcPoly 0xEDB88320
8 
9#ifdef MY_CPU_X86_OR_AMD64
10  #define CRC_NUM_TABLES 8
11  UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table);
12#elif defined(MY_CPU_LE)
13  #define CRC_NUM_TABLES 4
14#else
15  #define CRC_NUM_TABLES 5
16  #define CRC_UINT32_SWAP(v) ((v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24))
17  UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table);
18#endif
19 
20#ifndef MY_CPU_BE
21  UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table);
22#endif
23 
24typedef UInt32 (MY_FAST_CALL *CRC_FUNC)(UInt32 v, const void *data, size_t size, const UInt32 *table);
25 
26static CRC_FUNC g_CrcUpdate;
27UInt32 g_CrcTable[256 * CRC_NUM_TABLES];
28 
29UInt32 MY_FAST_CALL CrcUpdate(UInt32 v, const void *data, size_t size)
30{
31  return g_CrcUpdate(v, data, size, g_CrcTable);
32}
33 
34UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size)
35{
36  return g_CrcUpdate(CRC_INIT_VAL, data, size, g_CrcTable) ^ CRC_INIT_VAL;
37}
38 
39void MY_FAST_CALL CrcGenerateTable()
40{
41  UInt32 i;
42  for (i = 0; i < 256; i++)
43  {
44    UInt32 r = i;
45    unsigned j;
46    for (j = 0; j < 8; j++)
47      r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1));
48    g_CrcTable[i] = r;
49  }
50  for (; i < 256 * CRC_NUM_TABLES; i++)
51  {
52    UInt32 r = g_CrcTable[i - 256];
53    g_CrcTable[i] = g_CrcTable[r & 0xFF] ^ (r >> 8);
54  }
55   
56  #ifdef MY_CPU_LE
57 
58  g_CrcUpdate = CrcUpdateT4;
59   
60  #if CRC_NUM_TABLES == 8
61  if (!CPU_Is_InOrder())
62    g_CrcUpdate = CrcUpdateT8;
63  #endif
64 
65  #else
66  {
67    #ifndef MY_CPU_BE
68    UInt32 k = 1;
69    if (*(const Byte *)&k == 1)
70      g_CrcUpdate = CrcUpdateT4;
71    else
72    #endif
73    {
74      for (i = 256 * CRC_NUM_TABLES - 1; i >= 256; i--)
75      {
76        UInt32 x = g_CrcTable[i - 256];
77        g_CrcTable[i] = CRC_UINT32_SWAP(x);
78      }
79      g_CrcUpdate = CrcUpdateT1_BeT4;
80    }
81  }
82  #endif
83}
src/lib/lib7z/x7zFile.c
r0r14440
1/* 7zFile.c -- File IO
22009-11-24 : Igor Pavlov : Public domain */
3 
4#include "7zFile.h"
5 
6#ifndef USE_WINDOWS_FILE
7 
8#ifndef UNDER_CE
9#include <errno.h>
10#endif
11 
12#else
13 
14/*
15   ReadFile and WriteFile functions in Windows have BUG:
16   If you Read or Write 64MB or more (probably min_failure_size = 64MB - 32KB + 1)
17   from/to Network file, it returns ERROR_NO_SYSTEM_RESOURCES
18   (Insufficient system resources exist to complete the requested service).
19   Probably in some version of Windows there are problems with other sizes:
20   for 32 MB (maybe also for 16 MB).
21   And message can be "Network connection was lost"
22*/
23 
24#define kChunkSizeMax (1 << 22)
25 
26#endif
27 
28void File_Construct(CSzFile *p)
29{
30  #ifdef USE_WINDOWS_FILE
31  p->handle = INVALID_HANDLE_VALUE;
32  #else
33  p->file = NULL;
34  #endif
35}
36 
37#if !defined(UNDER_CE) || !defined(USE_WINDOWS_FILE)
38static WRes File_Open(CSzFile *p, const char *name, int writeMode)
39{
40  #ifdef USE_WINDOWS_FILE
41  p->handle = CreateFileA(name,
42      writeMode ? GENERIC_WRITE : GENERIC_READ,
43      FILE_SHARE_READ, NULL,
44      writeMode ? CREATE_ALWAYS : OPEN_EXISTING,
45      FILE_ATTRIBUTE_NORMAL, NULL);
46  return (p->handle != INVALID_HANDLE_VALUE) ? 0 : GetLastError();
47  #else
48  p->file = fopen(name, writeMode ? "wb+" : "rb");
49  return (p->file != 0) ? 0 :
50    #ifdef UNDER_CE
51    2; /* ENOENT */
52    #else
53    errno;
54    #endif
55  #endif
56}
57 
58WRes InFile_Open(CSzFile *p, const char *name) { return File_Open(p, name, 0); }
59WRes OutFile_Open(CSzFile *p, const char *name) { return File_Open(p, name, 1); }
60#endif
61 
62#ifdef USE_WINDOWS_FILE
63static WRes File_OpenW(CSzFile *p, const WCHAR *name, int writeMode)
64{
65  p->handle = CreateFileW(name,
66      writeMode ? GENERIC_WRITE : GENERIC_READ,
67      FILE_SHARE_READ, NULL,
68      writeMode ? CREATE_ALWAYS : OPEN_EXISTING,
69      FILE_ATTRIBUTE_NORMAL, NULL);
70  return (p->handle != INVALID_HANDLE_VALUE) ? 0 : GetLastError();
71}
72WRes InFile_OpenW(CSzFile *p, const WCHAR *name) { return File_OpenW(p, name, 0); }
73WRes OutFile_OpenW(CSzFile *p, const WCHAR *name) { return File_OpenW(p, name, 1); }
74#endif
75 
76WRes File_Close(CSzFile *p)
77{
78  #ifdef USE_WINDOWS_FILE
79  if (p->handle != INVALID_HANDLE_VALUE)
80  {
81    if (!CloseHandle(p->handle))
82      return GetLastError();
83    p->handle = INVALID_HANDLE_VALUE;
84  }
85  #else
86  if (p->file != NULL)
87  {
88    int res = fclose(p->file);
89    if (res != 0)
90      return res;
91    p->file = NULL;
92  }
93  #endif
94  return 0;
95}
96 
97WRes File_Read(CSzFile *p, void *data, size_t *size)
98{
99  size_t originalSize = *size;
100  if (originalSize == 0)
101    return 0;
102 
103  #ifdef USE_WINDOWS_FILE
104 
105  *size = 0;
106  do
107  {
108    DWORD curSize = (originalSize > kChunkSizeMax) ? kChunkSizeMax : (DWORD)originalSize;
109    DWORD processed = 0;
110    BOOL res = ReadFile(p->handle, data, curSize, &processed, NULL);
111    data = (void *)((Byte *)data + processed);
112    originalSize -= processed;
113    *size += processed;
114    if (!res)
115      return GetLastError();
116    if (processed == 0)
117      break;
118  }
119  while (originalSize > 0);
120  return 0;
121 
122  #else
123   
124  *size = fread(data, 1, originalSize, p->file);
125  if (*size == originalSize)
126    return 0;
127  return ferror(p->file);
128   
129  #endif
130}
131 
132WRes File_Write(CSzFile *p, const void *data, size_t *size)
133{
134  size_t originalSize = *size;
135  if (originalSize == 0)
136    return 0;
137   
138  #ifdef USE_WINDOWS_FILE
139 
140  *size = 0;
141  do
142  {
143    DWORD curSize = (originalSize > kChunkSizeMax) ? kChunkSizeMax : (DWORD)originalSize;
144    DWORD processed = 0;
145    BOOL res = WriteFile(p->handle, data, curSize, &processed, NULL);
146    data = (void *)((Byte *)data + processed);
147    originalSize -= processed;
148    *size += processed;
149    if (!res)
150      return GetLastError();
151    if (processed == 0)
152      break;
153  }
154  while (originalSize > 0);
155  return 0;
156 
157  #else
158 
159  *size = fwrite(data, 1, originalSize, p->file);
160  if (*size == originalSize)
161    return 0;
162  return ferror(p->file);
163   
164  #endif
165}
166 
167WRes File_Seek(CSzFile *p, Int64 *pos, ESzSeek origin)
168{
169  #ifdef USE_WINDOWS_FILE
170 
171  LARGE_INTEGER value;
172  DWORD moveMethod;
173  value.LowPart = (DWORD)*pos;
174  value.HighPart = (LONG)((UInt64)*pos >> 16 >> 16); /* for case when UInt64 is 32-bit only */
175  switch (origin)
176  {
177    case SZ_SEEK_SET: moveMethod = FILE_BEGIN; break;
178    case SZ_SEEK_CUR: moveMethod = FILE_CURRENT; break;
179    case SZ_SEEK_END: moveMethod = FILE_END; break;
180    default: return ERROR_INVALID_PARAMETER;
181  }
182  value.LowPart = SetFilePointer(p->handle, value.LowPart, &value.HighPart, moveMethod);
183  if (value.LowPart == 0xFFFFFFFF)
184  {
185    WRes res = GetLastError();
186    if (res != NO_ERROR)
187      return res;
188  }
189  *pos = ((Int64)value.HighPart << 32) | value.LowPart;
190  return 0;
191 
192  #else
193   
194  int moveMethod;
195  int res;
196  switch (origin)
197  {
198    case SZ_SEEK_SET: moveMethod = SEEK_SET; break;
199    case SZ_SEEK_CUR: moveMethod = SEEK_CUR; break;
200    case SZ_SEEK_END: moveMethod = SEEK_END; break;
201    default: return 1;
202  }
203  res = fseek(p->file, (long)*pos, moveMethod);
204  *pos = ftell(p->file);
205  return res;
206   
207  #endif
208}
209 
210WRes File_GetLength(CSzFile *p, UInt64 *length)
211{
212  #ifdef USE_WINDOWS_FILE
213   
214  DWORD sizeHigh;
215  DWORD sizeLow = GetFileSize(p->handle, &sizeHigh);
216  if (sizeLow == 0xFFFFFFFF)
217  {
218    DWORD res = GetLastError();
219    if (res != NO_ERROR)
220      return res;
221  }
222  *length = (((UInt64)sizeHigh) << 32) + sizeLow;
223  return 0;
224   
225  #else
226   
227  long pos = ftell(p->file);
228  int res = fseek(p->file, 0, SEEK_END);
229  *length = ftell(p->file);
230  fseek(p->file, pos, SEEK_SET);
231  return res;
232   
233  #endif
234}
235 
236 
237/* ---------- FileSeqInStream ---------- */
238 
239static SRes FileSeqInStream_Read(void *pp, void *buf, size_t *size)
240{
241  CFileSeqInStream *p = (CFileSeqInStream *)pp;
242  return File_Read(&p->file, buf, size) == 0 ? SZ_OK : SZ_ERROR_READ;
243}
244 
245void FileSeqInStream_CreateVTable(CFileSeqInStream *p)
246{
247  p->s.Read = FileSeqInStream_Read;
248}
249 
250 
251/* ---------- FileInStream ---------- */
252 
253static SRes FileInStream_Read(void *pp, void *buf, size_t *size)
254{
255  CFileInStream *p = (CFileInStream *)pp;
256  return (File_Read(&p->file, buf, size) == 0) ? SZ_OK : SZ_ERROR_READ;
257}
258 
259static SRes FileInStream_Seek(void *pp, Int64 *pos, ESzSeek origin)
260{
261  CFileInStream *p = (CFileInStream *)pp;
262  return File_Seek(&p->file, pos, origin);
263}
264 
265void FileInStream_CreateVTable(CFileInStream *p)
266{
267  p->s.Read = FileInStream_Read;
268  p->s.Seek = FileInStream_Seek;
269}
270 
271 
272/* ---------- FileOutStream ---------- */
273 
274static size_t FileOutStream_Write(void *pp, const void *data, size_t size)
275{
276  CFileOutStream *p = (CFileOutStream *)pp;
277  File_Write(&p->file, data, &size);
278  return size;
279}
280 
281void FileOutStream_CreateVTable(CFileOutStream *p)
282{
283  p->s.Write = FileOutStream_Write;
284}
src/lib/lib7z/LzmaEnc.c
r0r14440
1/* LzmaEnc.c -- LZMA Encoder
22011-01-27 : Igor Pavlov : Public domain */
3 
4#include <string.h>
5 
6/* #define SHOW_STAT */
7/* #define SHOW_STAT2 */
8 
9#if defined(SHOW_STAT) || defined(SHOW_STAT2)
10#include <stdio.h>
11#endif
12 
13#include "LzmaEnc.h"
14 
15#include "LzFind.h"
16#ifndef _7ZIP_ST
17#include "LzFindMt.h"
18#endif
19 
20#ifdef SHOW_STAT
21static int ttt = 0;
22#endif
23 
24#define kBlockSizeMax ((1 << LZMA_NUM_BLOCK_SIZE_BITS) - 1)
25 
26#define kBlockSize (9 << 10)
27#define kUnpackBlockSize (1 << 18)
28#define kMatchArraySize (1 << 21)
29#define kMatchRecordMaxSize ((LZMA_MATCH_LEN_MAX * 2 + 3) * LZMA_MATCH_LEN_MAX)
30 
31#define kNumMaxDirectBits (31)
32 
33#define kNumTopBits 24
34#define kTopValue ((UInt32)1 << kNumTopBits)
35 
36#define kNumBitModelTotalBits 11
37#define kBitModelTotal (1 << kNumBitModelTotalBits)
38#define kNumMoveBits 5
39#define kProbInitValue (kBitModelTotal >> 1)
40 
41#define kNumMoveReducingBits 4
42#define kNumBitPriceShiftBits 4
43#define kBitPrice (1 << kNumBitPriceShiftBits)
44 
45void LzmaEncProps_Init(CLzmaEncProps *p)
46{
47  p->level = 5;
48  p->dictSize = p->mc = 0;
49  p->reduceSize = (UInt32)(Int32)-1;
50  p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1;
51  p->writeEndMark = 0;
52}
53 
54void LzmaEncProps_Normalize(CLzmaEncProps *p)
55{
56  int level = p->level;
57  if (level < 0) level = 5;
58  p->level = level;
59  if (p->dictSize == 0) p->dictSize = (level <= 5 ? (1 << (level * 2 + 14)) : (level == 6 ? (1 << 25) : (1 << 26)));
60  if (p->dictSize > p->reduceSize)
61  {
62    unsigned i;
63    for (i = 15; i <= 30; i++)
64    {
65      if (p->reduceSize <= ((UInt32)2 << i)) { p->dictSize = ((UInt32)2 << i); break; }
66      if (p->reduceSize <= ((UInt32)3 << i)) { p->dictSize = ((UInt32)3 << i); break; }
67    }
68  }
69  if (p->lc < 0) p->lc = 3;
70  if (p->lp < 0) p->lp = 0;
71  if (p->pb < 0) p->pb = 2;
72  if (p->algo < 0) p->algo = (level < 5 ? 0 : 1);
73  if (p->fb < 0) p->fb = (level < 7 ? 32 : 64);
74  if (p->btMode < 0) p->btMode = (p->algo == 0 ? 0 : 1);
75  if (p->numHashBytes < 0) p->numHashBytes = 4;
76  if (p->mc == 0)  p->mc = (16 + (p->fb >> 1)) >> (p->btMode ? 0 : 1);
77  if (p->numThreads < 0)
78    p->numThreads =
79      #ifndef _7ZIP_ST
80      ((p->btMode && p->algo) ? 2 : 1);
81      #else
82      1;
83      #endif
84}
85 
86UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2)
87{
88  CLzmaEncProps props = *props2;
89  LzmaEncProps_Normalize(&props);
90  return props.dictSize;
91}
92 
93/* #define LZMA_LOG_BSR */
94/* Define it for Intel's CPU */
95 
96 
97#ifdef LZMA_LOG_BSR
98 
99#define kDicLogSizeMaxCompress 30
100 
101#define BSR2_RET(pos, res) { unsigned long i; _BitScanReverse(&i, (pos)); res = (i + i) + ((pos >> (i - 1)) & 1); }
102 
103UInt32 GetPosSlot1(UInt32 pos)
104{
105  UInt32 res;
106  BSR2_RET(pos, res);
107  return res;
108}
109#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
110#define GetPosSlot(pos, res) { if (pos < 2) res = pos; else BSR2_RET(pos, res); }
111 
112#else
113 
114#define kNumLogBits (9 + (int)sizeof(size_t) / 2)
115#define kDicLogSizeMaxCompress ((kNumLogBits - 1) * 2 + 7)
116 
117void LzmaEnc_FastPosInit(Byte *g_FastPos)
118{
119  int c = 2, slotFast;
120  g_FastPos[0] = 0;
121  g_FastPos[1] = 1;
122   
123  for (slotFast = 2; slotFast < kNumLogBits * 2; slotFast++)
124  {
125    UInt32 k = (1 << ((slotFast >> 1) - 1));
126    UInt32 j;
127    for (j = 0; j < k; j++, c++)
128      g_FastPos[c] = (Byte)slotFast;
129  }
130}
131 
132#define BSR2_RET(pos, res) { UInt32 i = 6 + ((kNumLogBits - 1) & \
133  (0 - (((((UInt32)1 << (kNumLogBits + 6)) - 1) - pos) >> 31))); \
134  res = p->g_FastPos[pos >> i] + (i * 2); }
135/*
136#define BSR2_RET(pos, res) { res = (pos < (1 << (kNumLogBits + 6))) ? \
137  p->g_FastPos[pos >> 6] + 12 : \
138  p->g_FastPos[pos >> (6 + kNumLogBits - 1)] + (6 + (kNumLogBits - 1)) * 2; }
139*/
140 
141#define GetPosSlot1(pos) p->g_FastPos[pos]
142#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
143#define GetPosSlot(pos, res) { if (pos < kNumFullDistances) res = p->g_FastPos[pos]; else BSR2_RET(pos, res); }
144 
145#endif
146 
147 
148#define LZMA_NUM_REPS 4
149 
150typedef unsigned CState;
151 
152typedef struct
153{
154  UInt32 price;
155 
156  CState state;
157  int prev1IsChar;
158  int prev2;
159 
160  UInt32 posPrev2;
161  UInt32 backPrev2;
162 
163  UInt32 posPrev;
164  UInt32 backPrev;
165  UInt32 backs[LZMA_NUM_REPS];
166} COptimal;
167 
168#define kNumOpts (1 << 12)
169 
170#define kNumLenToPosStates 4
171#define kNumPosSlotBits 6
172#define kDicLogSizeMin 0
173#define kDicLogSizeMax 32
174#define kDistTableSizeMax (kDicLogSizeMax * 2)
175 
176 
177#define kNumAlignBits 4
178#define kAlignTableSize (1 << kNumAlignBits)
179#define kAlignMask (kAlignTableSize - 1)
180 
181#define kStartPosModelIndex 4
182#define kEndPosModelIndex 14
183#define kNumPosModels (kEndPosModelIndex - kStartPosModelIndex)
184 
185#define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
186 
187#ifdef _LZMA_PROB32
188#define CLzmaProb UInt32
189#else
190#define CLzmaProb UInt16
191#endif
192 
193#define LZMA_PB_MAX 4
194#define LZMA_LC_MAX 8
195#define LZMA_LP_MAX 4
196 
197#define LZMA_NUM_PB_STATES_MAX (1 << LZMA_PB_MAX)
198 
199 
200#define kLenNumLowBits 3
201#define kLenNumLowSymbols (1 << kLenNumLowBits)
202#define kLenNumMidBits 3
203#define kLenNumMidSymbols (1 << kLenNumMidBits)
204#define kLenNumHighBits 8
205#define kLenNumHighSymbols (1 << kLenNumHighBits)
206 
207#define kLenNumSymbolsTotal (kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols)
208 
209#define LZMA_MATCH_LEN_MIN 2
210#define LZMA_MATCH_LEN_MAX (LZMA_MATCH_LEN_MIN + kLenNumSymbolsTotal - 1)
211 
212#define kNumStates 12
213 
214typedef struct
215{
216  CLzmaProb choice;
217  CLzmaProb choice2;
218  CLzmaProb low[LZMA_NUM_PB_STATES_MAX << kLenNumLowBits];
219  CLzmaProb mid[LZMA_NUM_PB_STATES_MAX << kLenNumMidBits];
220  CLzmaProb high[kLenNumHighSymbols];
221} CLenEnc;
222 
223typedef struct
224{
225  CLenEnc p;
226  UInt32 prices[LZMA_NUM_PB_STATES_MAX][kLenNumSymbolsTotal];
227  UInt32 tableSize;
228  UInt32 counters[LZMA_NUM_PB_STATES_MAX];
229} CLenPriceEnc;
230 
231typedef struct
232{
233  UInt32 range;
234  Byte cache;
235  UInt64 low;
236  UInt64 cacheSize;
237  Byte *buf;
238  Byte *bufLim;
239  Byte *bufBase;
240  ISeqOutStream *outStream;
241  UInt64 processed;
242  SRes res;
243} CRangeEnc;
244 
245typedef struct
246{
247  CLzmaProb *litProbs;
248 
249  CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
250  CLzmaProb isRep[kNumStates];
251  CLzmaProb isRepG0[kNumStates];
252  CLzmaProb isRepG1[kNumStates];
253  CLzmaProb isRepG2[kNumStates];
254  CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
255 
256  CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
257  CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex];
258  CLzmaProb posAlignEncoder[1 << kNumAlignBits];
259   
260  CLenPriceEnc lenEnc;
261  CLenPriceEnc repLenEnc;
262 
263  UInt32 reps[LZMA_NUM_REPS];
264  UInt32 state;
265} CSaveState;
266 
267typedef struct
268{
269  IMatchFinder matchFinder;
270  void *matchFinderObj;
271 
272  #ifndef _7ZIP_ST
273  Bool mtMode;
274  CMatchFinderMt matchFinderMt;
275  #endif
276 
277  CMatchFinder matchFinderBase;
278 
279  #ifndef _7ZIP_ST
280  Byte pad[128];
281  #endif
282   
283  UInt32 optimumEndIndex;
284  UInt32 optimumCurrentIndex;
285 
286  UInt32 longestMatchLength;
287  UInt32 numPairs;
288  UInt32 numAvail;
289  COptimal opt[kNumOpts];
290   
291  #ifndef LZMA_LOG_BSR
292  Byte g_FastPos[1 << kNumLogBits];
293  #endif
294 
295  UInt32 ProbPrices[kBitModelTotal >> kNumMoveReducingBits];
296  UInt32 matches[LZMA_MATCH_LEN_MAX * 2 + 2 + 1];
297  UInt32 numFastBytes;
298  UInt32 additionalOffset;
299  UInt32 reps[LZMA_NUM_REPS];
300  UInt32 state;
301 
302  UInt32 posSlotPrices[kNumLenToPosStates][kDistTableSizeMax];
303  UInt32 distancesPrices[kNumLenToPosStates][kNumFullDistances];
304  UInt32 alignPrices[kAlignTableSize];
305  UInt32 alignPriceCount;
306 
307  UInt32 distTableSize;
308 
309  unsigned lc, lp, pb;
310  unsigned lpMask, pbMask;
311 
312  CLzmaProb *litProbs;
313 
314  CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
315  CLzmaProb isRep[kNumStates];
316  CLzmaProb isRepG0[kNumStates];
317  CLzmaProb isRepG1[kNumStates];
318  CLzmaProb isRepG2[kNumStates];
319  CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
320 
321  CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
322  CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex];
323  CLzmaProb posAlignEncoder[1 << kNumAlignBits];
324   
325  CLenPriceEnc lenEnc;
326  CLenPriceEnc repLenEnc;
327 
328  unsigned lclp;
329 
330  Bool fastMode;
331   
332  CRangeEnc rc;
333 
334  Bool writeEndMark;
335  UInt64 nowPos64;
336  UInt32 matchPriceCount;
337  Bool finished;
338  Bool multiThread;
339 
340  SRes result;
341  UInt32 dictSize;
342 
343  int needInit;
344 
345  CSaveState saveState;
346} CLzmaEnc;
347 
348void LzmaEnc_SaveState(CLzmaEncHandle pp)
349{
350  CLzmaEnc *p = (CLzmaEnc *)pp;
351  CSaveState *dest = &p->saveState;
352  int i;
353  dest->lenEnc = p->lenEnc;
354  dest->repLenEnc = p->repLenEnc;
355  dest->state = p->state;
356 
357  for (i = 0; i < kNumStates; i++)
358  {
359    memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i]));
360    memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i]));
361  }
362  for (i = 0; i < kNumLenToPosStates; i++)
363    memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i]));
364  memcpy(dest->isRep, p->isRep, sizeof(p->isRep));
365  memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0));
366  memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1));
367  memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2));
368  memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders));
369  memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder));
370  memcpy(dest->reps, p->reps, sizeof(p->reps));
371  memcpy(dest->litProbs, p->litProbs, (0x300 << p->lclp) * sizeof(CLzmaProb));
372}
373 
374void LzmaEnc_RestoreState(CLzmaEncHandle pp)
375{
376  CLzmaEnc *dest = (CLzmaEnc *)pp;
377  const CSaveState *p = &dest->saveState;
378  int i;
379  dest->lenEnc = p->lenEnc;
380  dest->repLenEnc = p->repLenEnc;
381  dest->state = p->state;
382 
383  for (i = 0; i < kNumStates; i++)
384  {
385    memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i]));
386    memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i]));
387  }
388  for (i = 0; i < kNumLenToPosStates; i++)
389    memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i]));
390  memcpy(dest->isRep, p->isRep, sizeof(p->isRep));
391  memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0));
392  memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1));
393  memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2));
394  memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders));
395  memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder));
396  memcpy(dest->reps, p->reps, sizeof(p->reps));
397  memcpy(dest->litProbs, p->litProbs, (0x300 << dest->lclp) * sizeof(CLzmaProb));
398}
399 
400SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2)
401{
402  CLzmaEnc *p = (CLzmaEnc *)pp;
403  CLzmaEncProps props = *props2;
404  LzmaEncProps_Normalize(&props);
405 
406  if (props.lc > LZMA_LC_MAX || props.lp > LZMA_LP_MAX || props.pb > LZMA_PB_MAX ||
407      props.dictSize > ((UInt32)1 << kDicLogSizeMaxCompress) || props.dictSize > ((UInt32)1 << 30))
408    return SZ_ERROR_PARAM;
409  p->dictSize = props.dictSize;
410  {
411    unsigned fb = props.fb;
412    if (fb < 5)
413      fb = 5;
414    if (fb > LZMA_MATCH_LEN_MAX)
415      fb = LZMA_MATCH_LEN_MAX;
416    p->numFastBytes = fb;
417  }
418  p->lc = props.lc;
419  p->lp = props.lp;
420  p->pb = props.pb;
421  p->fastMode = (props.algo == 0);
422  p->matchFinderBase.btMode = props.btMode;
423  {
424    UInt32 numHashBytes = 4;
425    if (props.btMode)
426    {
427      if (props.numHashBytes < 2)
428        numHashBytes = 2;
429      else if (props.numHashBytes < 4)
430        numHashBytes = props.numHashBytes;
431    }
432    p->matchFinderBase.numHashBytes = numHashBytes;
433  }
434 
435  p->matchFinderBase.cutValue = props.mc;
436 
437  p->writeEndMark = props.writeEndMark;
438 
439  #ifndef _7ZIP_ST
440  /*
441  if (newMultiThread != _multiThread)
442  {
443    ReleaseMatchFinder();
444    _multiThread = newMultiThread;
445  }
446  */
447  p->multiThread = (props.numThreads > 1);
448  #endif
449 
450  return SZ_OK;
451}
452 
453static const int kLiteralNextStates[kNumStates] = {0, 0, 0, 0, 1, 2, 3, 4,  5,  6,   4, 5};
454static const int kMatchNextStates[kNumStates]   = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10};
455static const int kRepNextStates[kNumStates]     = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11};
456static const int kShortRepNextStates[kNumStates]= {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11};
457 
458#define IsCharState(s) ((s) < 7)
459 
460#define GetLenToPosState(len) (((len) < kNumLenToPosStates + 1) ? (len) - 2 : kNumLenToPosStates - 1)
461 
462#define kInfinityPrice (1 << 30)
463 
464static void RangeEnc_Construct(CRangeEnc *p)
465{
466  p->outStream = 0;
467  p->bufBase = 0;
468}
469 
470#define RangeEnc_GetProcessed(p) ((p)->processed + ((p)->buf - (p)->bufBase) + (p)->cacheSize)
471 
472#define RC_BUF_SIZE (1 << 16)
473static int RangeEnc_Alloc(CRangeEnc *p, ISzAlloc *alloc)
474{
475  if (p->bufBase == 0)
476  {
477    p->bufBase = (Byte *)alloc->Alloc(alloc, RC_BUF_SIZE);
478    if (p->bufBase == 0)
479      return 0;
480    p->bufLim = p->bufBase + RC_BUF_SIZE;
481  }
482  return 1;
483}
484 
485static void RangeEnc_Free(CRangeEnc *p, ISzAlloc *alloc)
486{
487  alloc->Free(alloc, p->bufBase);
488  p->bufBase = 0;
489}
490 
491static void RangeEnc_Init(CRangeEnc *p)
492{
493  /* Stream.Init(); */
494  p->low = 0;
495  p->range = 0xFFFFFFFF;
496  p->cacheSize = 1;
497  p->cache = 0;
498 
499  p->buf = p->bufBase;
500 
501  p->processed = 0;
502  p->res = SZ_OK;
503}
504 
505static void RangeEnc_FlushStream(CRangeEnc *p)
506{
507  size_t num;
508  if (p->res != SZ_OK)
509    return;
510  num = p->buf - p->bufBase;
511  if (num != p->outStream->Write(p->outStream, p->bufBase, num))
512    p->res = SZ_ERROR_WRITE;
513  p->processed += num;
514  p->buf = p->bufBase;
515}
516 
517static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p)
518{
519  if ((UInt32)p->low < (UInt32)0xFF000000 || (int)(p->low >> 32) != 0)
520  {
521    Byte temp = p->cache;
522    do
523    {
524      Byte *buf = p->buf;
525      *buf++ = (Byte)(temp + (Byte)(p->low >> 32));
526      p->buf = buf;
527      if (buf == p->bufLim)
528        RangeEnc_FlushStream(p);
529      temp = 0xFF;
530    }
531    while (--p->cacheSize != 0);
532    p->cache = (Byte)((UInt32)p->low >> 24);
533  }
534  p->cacheSize++;
535  p->low = (UInt32)p->low << 8;
536}
537 
538static void RangeEnc_FlushData(CRangeEnc *p)
539{
540  int i;
541  for (i = 0; i < 5; i++)
542    RangeEnc_ShiftLow(p);
543}
544 
545static void RangeEnc_EncodeDirectBits(CRangeEnc *p, UInt32 value, int numBits)
546{
547  do
548  {
549    p->range >>= 1;
550    p->low += p->range & (0 - ((value >> --numBits) & 1));
551    if (p->range < kTopValue)
552    {
553      p->range <<= 8;
554      RangeEnc_ShiftLow(p);
555    }
556  }
557  while (numBits != 0);
558}
559 
560static void RangeEnc_EncodeBit(CRangeEnc *p, CLzmaProb *prob, UInt32 symbol)
561{
562  UInt32 ttt = *prob;
563  UInt32 newBound = (p->range >> kNumBitModelTotalBits) * ttt;
564  if (symbol == 0)
565  {
566    p->range = newBound;
567    ttt += (kBitModelTotal - ttt) >> kNumMoveBits;
568  }
569  else
570  {
571    p->low += newBound;
572    p->range -= newBound;
573    ttt -= ttt >> kNumMoveBits;
574  }
575  *prob = (CLzmaProb)ttt;
576  if (p->range < kTopValue)
577  {
578    p->range <<= 8;
579    RangeEnc_ShiftLow(p);
580  }
581}
582 
583static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol)
584{
585  symbol |= 0x100;
586  do
587  {
588    RangeEnc_EncodeBit(p, probs + (symbol >> 8), (symbol >> 7) & 1);
589    symbol <<= 1;
590  }
591  while (symbol < 0x10000);
592}
593 
594static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol, UInt32 matchByte)
595{
596  UInt32 offs = 0x100;
597  symbol |= 0x100;
598  do
599  {
600    matchByte <<= 1;
601    RangeEnc_EncodeBit(p, probs + (offs + (matchByte & offs) + (symbol >> 8)), (symbol >> 7) & 1);
602    symbol <<= 1;
603    offs &= ~(matchByte ^ symbol);
604  }
605  while (symbol < 0x10000);
606}
607 
608void LzmaEnc_InitPriceTables(UInt32 *ProbPrices)
609{
610  UInt32 i;
611  for (i = (1 << kNumMoveReducingBits) / 2; i < kBitModelTotal; i += (1 << kNumMoveReducingBits))
612  {
613    const int kCyclesBits = kNumBitPriceShiftBits;
614    UInt32 w = i;
615    UInt32 bitCount = 0;
616    int j;
617    for (j = 0; j < kCyclesBits; j++)
618    {
619      w = w * w;
620      bitCount <<= 1;
621      while (w >= ((UInt32)1 << 16))
622      {
623        w >>= 1;
624        bitCount++;
625      }
626    }
627    ProbPrices[i >> kNumMoveReducingBits] = ((kNumBitModelTotalBits << kCyclesBits) - 15 - bitCount);
628  }
629}
630 
631 
632#define GET_PRICE(prob, symbol) \
633  p->ProbPrices[((prob) ^ (((-(int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
634 
635#define GET_PRICEa(prob, symbol) \
636  ProbPrices[((prob) ^ ((-((int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
637 
638#define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits]
639#define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
640 
641#define GET_PRICE_0a(prob) ProbPrices[(prob) >> kNumMoveReducingBits]
642#define GET_PRICE_1a(prob) ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
643 
644static UInt32 LitEnc_GetPrice(const CLzmaProb *probs, UInt32 symbol, UInt32 *ProbPrices)
645{
646  UInt32 price = 0;
647  symbol |= 0x100;
648  do
649  {
650    price += GET_PRICEa(probs[symbol >> 8], (symbol >> 7) & 1);
651    symbol <<= 1;
652  }
653  while (symbol < 0x10000);
654  return price;
655}
656 
657static UInt32 LitEnc_GetPriceMatched(const CLzmaProb *probs, UInt32 symbol, UInt32 matchByte, UInt32 *ProbPrices)
658{
659  UInt32 price = 0;
660  UInt32 offs = 0x100;
661  symbol |= 0x100;
662  do
663  {
664    matchByte <<= 1;
665    price += GET_PRICEa(probs[offs + (matchByte & offs) + (symbol >> 8)], (symbol >> 7) & 1);
666    symbol <<= 1;
667    offs &= ~(matchByte ^ symbol);
668  }
669  while (symbol < 0x10000);
670  return price;
671}
672 
673 
674static void RcTree_Encode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol)
675{
676  UInt32 m = 1;
677  int i;
678  for (i = numBitLevels; i != 0;)
679  {
680    UInt32 bit;
681    i--;
682    bit = (symbol >> i) & 1;
683    RangeEnc_EncodeBit(rc, probs + m, bit);
684    m = (m << 1) | bit;
685  }
686}
687 
688static void RcTree_ReverseEncode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol)
689{
690  UInt32 m = 1;
691  int i;
692  for (i = 0; i < numBitLevels; i++)
693  {
694    UInt32 bit = symbol & 1;
695    RangeEnc_EncodeBit(rc, probs + m, bit);
696    m = (m << 1) | bit;
697    symbol >>= 1;
698  }
699}
700 
701static UInt32 RcTree_GetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, UInt32 *ProbPrices)
702{
703  UInt32 price = 0;
704  symbol |= (1 << numBitLevels);
705  while (symbol != 1)
706  {
707    price += GET_PRICEa(probs[symbol >> 1], symbol & 1);
708    symbol >>= 1;
709  }
710  return price;
711}
712 
713static UInt32 RcTree_ReverseGetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, UInt32 *ProbPrices)
714{
715  UInt32 price = 0;
716  UInt32 m = 1;
717  int i;
718  for (i = numBitLevels; i != 0; i--)
719  {
720    UInt32 bit = symbol & 1;
721    symbol >>= 1;
722    price += GET_PRICEa(probs[m], bit);
723    m = (m << 1) | bit;
724  }
725  return price;
726}
727 
728 
729static void LenEnc_Init(CLenEnc *p)
730{
731  unsigned i;
732  p->choice = p->choice2 = kProbInitValue;
733  for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumLowBits); i++)
734    p->low[i] = kProbInitValue;
735  for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumMidBits); i++)
736    p->mid[i] = kProbInitValue;
737  for (i = 0; i < kLenNumHighSymbols; i++)
738    p->high[i] = kProbInitValue;
739}
740 
741static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState)
742{
743  if (symbol < kLenNumLowSymbols)
744  {
745    RangeEnc_EncodeBit(rc, &p->choice, 0);
746    RcTree_Encode(rc, p->low + (posState << kLenNumLowBits), kLenNumLowBits, symbol);
747  }
748  else
749  {
750    RangeEnc_EncodeBit(rc, &p->choice, 1);
751    if (symbol < kLenNumLowSymbols + kLenNumMidSymbols)
752    {
753      RangeEnc_EncodeBit(rc, &p->choice2, 0);
754      RcTree_Encode(rc, p->mid + (posState << kLenNumMidBits), kLenNumMidBits, symbol - kLenNumLowSymbols);
755    }
756    else
757    {
758      RangeEnc_EncodeBit(rc, &p->choice2, 1);
759      RcTree_Encode(rc, p->high, kLenNumHighBits, symbol - kLenNumLowSymbols - kLenNumMidSymbols);
760    }
761  }
762}
763 
764static void LenEnc_SetPrices(CLenEnc *p, UInt32 posState, UInt32 numSymbols, UInt32 *prices, UInt32 *ProbPrices)
765{
766  UInt32 a0 = GET_PRICE_0a(p->choice);
767  UInt32 a1 = GET_PRICE_1a(p->choice);
768  UInt32 b0 = a1 + GET_PRICE_0a(p->choice2);
769  UInt32 b1 = a1 + GET_PRICE_1a(p->choice2);
770  UInt32 i = 0;
771  for (i = 0; i < kLenNumLowSymbols; i++)
772  {
773    if (i >= numSymbols)
774      return;
775    prices[i] = a0 + RcTree_GetPrice(p->low + (posState << kLenNumLowBits), kLenNumLowBits, i, ProbPrices);
776  }
777  for (; i < kLenNumLowSymbols + kLenNumMidSymbols; i++)
778  {
779    if (i >= numSymbols)
780      return;
781    prices[i] = b0 + RcTree_GetPrice(p->mid + (posState << kLenNumMidBits), kLenNumMidBits, i - kLenNumLowSymbols, ProbPrices);
782  }
783  for (; i < numSymbols; i++)
784    prices[i] = b1 + RcTree_GetPrice(p->high, kLenNumHighBits, i - kLenNumLowSymbols - kLenNumMidSymbols, ProbPrices);
785}
786 
787static void MY_FAST_CALL LenPriceEnc_UpdateTable(CLenPriceEnc *p, UInt32 posState, UInt32 *ProbPrices)
788{
789  LenEnc_SetPrices(&p->p, posState, p->tableSize, p->prices[posState], ProbPrices);
790  p->counters[posState] = p->tableSize;
791}
792 
793static void LenPriceEnc_UpdateTables(CLenPriceEnc *p, UInt32 numPosStates, UInt32 *ProbPrices)
794{
795  UInt32 posState;
796  for (posState = 0; posState < numPosStates; posState++)
797    LenPriceEnc_UpdateTable(p, posState, ProbPrices);
798}
799 
800static void LenEnc_Encode2(CLenPriceEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState, Bool updatePrice, UInt32 *ProbPrices)
801{
802  LenEnc_Encode(&p->p, rc, symbol, posState);
803  if (updatePrice)
804    if (--p->counters[posState] == 0)
805      LenPriceEnc_UpdateTable(p, posState, ProbPrices);
806}
807 
808 
809 
810 
811static void MovePos(CLzmaEnc *p, UInt32 num)
812{
813  #ifdef SHOW_STAT
814  ttt += num;
815  printf("\n MovePos %d", num);
816  #endif
817  if (num != 0)
818  {
819    p->additionalOffset += num;
820    p->matchFinder.Skip(p->matchFinderObj, num);
821  }
822}
823 
824static UInt32 ReadMatchDistances(CLzmaEnc *p, UInt32 *numDistancePairsRes)
825{
826  UInt32 lenRes = 0, numPairs;
827  p->numAvail = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
828  numPairs = p->matchFinder.GetMatches(p->matchFinderObj, p->matches);
829  #ifdef SHOW_STAT
830  printf("\n i = %d numPairs = %d    ", ttt, numPairs / 2);
831  ttt++;
832  {
833    UInt32 i;
834    for (i = 0; i < numPairs; i += 2)
835      printf("%2d %6d   | ", p->matches[i], p->matches[i + 1]);
836  }
837  #endif
838  if (numPairs > 0)
839  {
840    lenRes = p->matches[numPairs - 2];
841    if (lenRes == p->numFastBytes)
842    {
843      const Byte *pby = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
844      UInt32 distance = p->matches[numPairs - 1] + 1;
845      UInt32 numAvail = p->numAvail;
846      if (numAvail > LZMA_MATCH_LEN_MAX)
847        numAvail = LZMA_MATCH_LEN_MAX;
848      {
849        const Byte *pby2 = pby - distance;
850        for (; lenRes < numAvail && pby[lenRes] == pby2[lenRes]; lenRes++);
851      }
852    }
853  }
854  p->additionalOffset++;
855  *numDistancePairsRes = numPairs;
856  return lenRes;
857}
858 
859 
860#define MakeAsChar(p) (p)->backPrev = (UInt32)(-1); (p)->prev1IsChar = False;
861#define MakeAsShortRep(p) (p)->backPrev = 0; (p)->prev1IsChar = False;
862#define IsShortRep(p) ((p)->backPrev == 0)
863 
864static UInt32 GetRepLen1Price(CLzmaEnc *p, UInt32 state, UInt32 posState)
865{
866  return
867    GET_PRICE_0(p->isRepG0[state]) +
868    GET_PRICE_0(p->isRep0Long[state][posState]);
869}
870 
871static UInt32 GetPureRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 state, UInt32 posState)
872{
873  UInt32 price;
874  if (repIndex == 0)
875  {
876    price = GET_PRICE_0(p->isRepG0[state]);
877    price += GET_PRICE_1(p->isRep0Long[state][posState]);
878  }
879  else
880  {
881    price = GET_PRICE_1(p->isRepG0[state]);
882    if (repIndex == 1)
883      price += GET_PRICE_0(p->isRepG1[state]);
884    else
885    {
886      price += GET_PRICE_1(p->isRepG1[state]);
887      price += GET_PRICE(p->isRepG2[state], repIndex - 2);
888    }
889  }
890  return price;
891}
892 
893static UInt32 GetRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 len, UInt32 state, UInt32 posState)
894{
895  return p->repLenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN] +
896    GetPureRepPrice(p, repIndex, state, posState);
897}
898 
899static UInt32 Backward(CLzmaEnc *p, UInt32 *backRes, UInt32 cur)
900{
901  UInt32 posMem = p->opt[cur].posPrev;
902  UInt32 backMem = p->opt[cur].backPrev;
903  p->optimumEndIndex = cur;
904  do
905  {
906    if (p->opt[cur].prev1IsChar)
907    {
908      MakeAsChar(&p->opt[posMem])
909      p->opt[posMem].posPrev = posMem - 1;
910      if (p->opt[cur].prev2)
911      {
912        p->opt[posMem - 1].prev1IsChar = False;
913        p->opt[posMem - 1].posPrev = p->opt[cur].posPrev2;
914        p->opt[posMem - 1].backPrev = p->opt[cur].backPrev2;
915      }
916    }
917    {
918      UInt32 posPrev = posMem;
919      UInt32 backCur = backMem;
920       
921      backMem = p->opt[posPrev].backPrev;
922      posMem = p->opt[posPrev].posPrev;
923       
924      p->opt[posPrev].backPrev = backCur;
925      p->opt[posPrev].posPrev = cur;
926      cur = posPrev;
927    }
928  }
929  while (cur != 0);
930  *backRes = p->opt[0].backPrev;
931  p->optimumCurrentIndex  = p->opt[0].posPrev;
932  return p->optimumCurrentIndex;
933}
934 
935#define LIT_PROBS(pos, prevByte) (p->litProbs + ((((pos) & p->lpMask) << p->lc) + ((prevByte) >> (8 - p->lc))) * 0x300)
936 
937static UInt32 GetOptimum(CLzmaEnc *p, UInt32 position, UInt32 *backRes)
938{
939  UInt32 numAvail, mainLen, numPairs, repMaxIndex, i, posState, lenEnd, len, cur;
940  UInt32 matchPrice, repMatchPrice, normalMatchPrice;
941  UInt32 reps[LZMA_NUM_REPS], repLens[LZMA_NUM_REPS];
942  UInt32 *matches;
943  const Byte *data;
944  Byte curByte, matchByte;
945  if (p->optimumEndIndex != p->optimumCurrentIndex)
946  {
947    const COptimal *opt = &p->opt[p->optimumCurrentIndex];
948    UInt32 lenRes = opt->posPrev - p->optimumCurrentIndex;
949    *backRes = opt->backPrev;
950    p->optimumCurrentIndex = opt->posPrev;
951    return lenRes;
952  }
953  p->optimumCurrentIndex = p->optimumEndIndex = 0;
954   
955  if (p->additionalOffset == 0)
956    mainLen = ReadMatchDistances(p, &numPairs);
957  else
958  {
959    mainLen = p->longestMatchLength;
960    numPairs = p->numPairs;
961  }
962 
963  numAvail = p->numAvail;
964  if (numAvail < 2)
965  {
966    *backRes = (UInt32)(-1);
967    return 1;
968  }
969  if (numAvail > LZMA_MATCH_LEN_MAX)
970    numAvail = LZMA_MATCH_LEN_MAX;
971 
972  data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
973  repMaxIndex = 0;
974  for (i = 0; i < LZMA_NUM_REPS; i++)
975  {
976    UInt32 lenTest;
977    const Byte *data2;
978    reps[i] = p->reps[i];
979    data2 = data - (reps[i] + 1);
980    if (data[0] != data2[0] || data[1] != data2[1])
981    {
982      repLens[i] = 0;
983      continue;
984    }
985    for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++);
986    repLens[i] = lenTest;
987    if (lenTest > repLens[repMaxIndex])
988      repMaxIndex = i;
989  }
990  if (repLens[repMaxIndex] >= p->numFastBytes)
991  {
992    UInt32 lenRes;
993    *backRes = repMaxIndex;
994    lenRes = repLens[repMaxIndex];
995    MovePos(p, lenRes - 1);
996    return lenRes;
997  }
998 
999  matches = p->matches;
1000  if (mainLen >= p->numFastBytes)
1001  {
1002    *backRes = matches[numPairs - 1] + LZMA_NUM_REPS;
1003    MovePos(p, mainLen - 1);
1004    return mainLen;
1005  }
1006  curByte = *data;
1007  matchByte = *(data - (reps[0] + 1));
1008 
1009  if (mainLen < 2 && curByte != matchByte && repLens[repMaxIndex] < 2)
1010  {
1011    *backRes = (UInt32)-1;
1012    return 1;
1013  }
1014 
1015  p->opt[0].state = (CState)p->state;
1016 
1017  posState = (position & p->pbMask);
1018 
1019  {
1020    const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
1021    p->opt[1].price = GET_PRICE_0(p->isMatch[p->state][posState]) +
1022        (!IsCharState(p->state) ?
1023          LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) :
1024          LitEnc_GetPrice(probs, curByte, p->ProbPrices));
1025  }
1026 
1027  MakeAsChar(&p->opt[1]);
1028 
1029  matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]);
1030  repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]);
1031 
1032  if (matchByte == curByte)
1033  {
1034    UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, p->state, posState);
1035    if (shortRepPrice < p->opt[1].price)
1036    {
1037      p->opt[1].price = shortRepPrice;
1038      MakeAsShortRep(&p->opt[1]);
1039    }
1040  }
1041  lenEnd = ((mainLen >= repLens[repMaxIndex]) ? mainLen : repLens[repMaxIndex]);
1042 
1043  if (lenEnd < 2)
1044  {
1045    *backRes = p->opt[1].backPrev;
1046    return 1;
1047  }
1048 
1049  p->opt[1].posPrev = 0;
1050  for (i = 0; i < LZMA_NUM_REPS; i++)
1051    p->opt[0].backs[i] = reps[i];
1052 
1053  len = lenEnd;
1054  do
1055    p->opt[len--].price = kInfinityPrice;
1056  while (len >= 2);
1057 
1058  for (i = 0; i < LZMA_NUM_REPS; i++)
1059  {
1060    UInt32 repLen = repLens[i];
1061    UInt32 price;
1062    if (repLen < 2)
1063      continue;
1064    price = repMatchPrice + GetPureRepPrice(p, i, p->state, posState);
1065    do
1066    {
1067      UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][repLen - 2];
1068      COptimal *opt = &p->opt[repLen];
1069      if (curAndLenPrice < opt->price)
1070      {
1071        opt->price = curAndLenPrice;
1072        opt->posPrev = 0;
1073        opt->backPrev = i;
1074        opt->prev1IsChar = False;
1075      }
1076    }
1077    while (--repLen >= 2);
1078  }
1079 
1080  normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[p->state]);
1081 
1082  len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2);
1083  if (len <= mainLen)
1084  {
1085    UInt32 offs = 0;
1086    while (len > matches[offs])
1087      offs += 2;
1088    for (; ; len++)
1089    {
1090      COptimal *opt;
1091      UInt32 distance = matches[offs + 1];
1092 
1093      UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN];
1094      UInt32 lenToPosState = GetLenToPosState(len);
1095      if (distance < kNumFullDistances)
1096        curAndLenPrice += p->distancesPrices[lenToPosState][distance];
1097      else
1098      {
1099        UInt32 slot;
1100        GetPosSlot2(distance, slot);
1101        curAndLenPrice += p->alignPrices[distance & kAlignMask] + p->posSlotPrices[lenToPosState][slot];
1102      }
1103      opt = &p->opt[len];
1104      if (curAndLenPrice < opt->price)
1105      {
1106        opt->price = curAndLenPrice;
1107        opt->posPrev = 0;
1108        opt->backPrev = distance + LZMA_NUM_REPS;
1109        opt->prev1IsChar = False;
1110      }
1111      if (len == matches[offs])
1112      {
1113        offs += 2;
1114        if (offs == numPairs)
1115          break;
1116      }
1117    }
1118  }
1119 
1120  cur = 0;
1121 
1122    #ifdef SHOW_STAT2
1123    if (position >= 0)
1124    {
1125      unsigned i;
1126      printf("\n pos = %4X", position);
1127      for (i = cur; i <= lenEnd; i++)
1128      printf("\nprice[%4X] = %d", position - cur + i, p->opt[i].price);
1129    }
1130    #endif
1131 
1132  for (;;)
1133  {
1134    UInt32 numAvailFull, newLen, numPairs, posPrev, state, posState, startLen;
1135    UInt32 curPrice, curAnd1Price, matchPrice, repMatchPrice;
1136    Bool nextIsChar;
1137    Byte curByte, matchByte;
1138    const Byte *data;
1139    COptimal *curOpt;
1140    COptimal *nextOpt;
1141 
1142    cur++;
1143    if (cur == lenEnd)
1144      return Backward(p, backRes, cur);
1145 
1146    newLen = ReadMatchDistances(p, &numPairs);
1147    if (newLen >= p->numFastBytes)
1148    {
1149      p->numPairs = numPairs;
1150      p->longestMatchLength = newLen;
1151      return Backward(p, backRes, cur);
1152    }
1153    position++;
1154    curOpt = &p->opt[cur];
1155    posPrev = curOpt->posPrev;
1156    if (curOpt->prev1IsChar)
1157    {
1158      posPrev--;
1159      if (curOpt->prev2)
1160      {
1161        state = p->opt[curOpt->posPrev2].state;
1162        if (curOpt->backPrev2 < LZMA_NUM_REPS)
1163          state = kRepNextStates[state];
1164        else
1165          state = kMatchNextStates[state];
1166      }
1167      else
1168        state = p->opt[posPrev].state;
1169      state = kLiteralNextStates[state];
1170    }
1171    else
1172      state = p->opt[posPrev].state;
1173    if (posPrev == cur - 1)
1174    {
1175      if (IsShortRep(curOpt))
1176        state = kShortRepNextStates[state];
1177      else
1178        state = kLiteralNextStates[state];
1179    }
1180    else
1181    {
1182      UInt32 pos;
1183      const COptimal *prevOpt;
1184      if (curOpt->prev1IsChar && curOpt->prev2)
1185      {
1186        posPrev = curOpt->posPrev2;
1187        pos = curOpt->backPrev2;
1188        state = kRepNextStates[state];
1189      }
1190      else
1191      {
1192        pos = curOpt->backPrev;
1193        if (pos < LZMA_NUM_REPS)
1194          state = kRepNextStates[state];
1195        else
1196          state = kMatchNextStates[state];
1197      }
1198      prevOpt = &p->opt[posPrev];
1199      if (pos < LZMA_NUM_REPS)
1200      {
1201        UInt32 i;
1202        reps[0] = prevOpt->backs[pos];
1203        for (i = 1; i <= pos; i++)
1204          reps[i] = prevOpt->backs[i - 1];
1205        for (; i < LZMA_NUM_REPS; i++)
1206          reps[i] = prevOpt->backs[i];
1207      }
1208      else
1209      {
1210        UInt32 i;
1211        reps[0] = (pos - LZMA_NUM_REPS);
1212        for (i = 1; i < LZMA_NUM_REPS; i++)
1213          reps[i] = prevOpt->backs[i - 1];
1214      }
1215    }
1216    curOpt->state = (CState)state;
1217 
1218    curOpt->backs[0] = reps[0];
1219    curOpt->backs[1] = reps[1];
1220    curOpt->backs[2] = reps[2];
1221    curOpt->backs[3] = reps[3];
1222 
1223    curPrice = curOpt->price;
1224    nextIsChar = False;
1225    data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
1226    curByte = *data;
1227    matchByte = *(data - (reps[0] + 1));
1228 
1229    posState = (position & p->pbMask);
1230 
1231    curAnd1Price = curPrice + GET_PRICE_0(p->isMatch[state][posState]);
1232    {
1233      const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
1234      curAnd1Price +=
1235        (!IsCharState(state) ?
1236          LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) :
1237          LitEnc_GetPrice(probs, curByte, p->ProbPrices));
1238    }
1239 
1240    nextOpt = &p->opt[cur + 1];
1241 
1242    if (curAnd1Price < nextOpt->price)
1243    {
1244      nextOpt->price = curAnd1Price;
1245      nextOpt->posPrev = cur;
1246      MakeAsChar(nextOpt);
1247      nextIsChar = True;
1248    }
1249 
1250    matchPrice = curPrice + GET_PRICE_1(p->isMatch[state][posState]);
1251    repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[state]);
1252     
1253    if (matchByte == curByte && !(nextOpt->posPrev < cur && nextOpt->backPrev == 0))
1254    {
1255      UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, state, posState);
1256      if (shortRepPrice <= nextOpt->price)
1257      {
1258        nextOpt->price = shortRepPrice;
1259        nextOpt->posPrev = cur;
1260        MakeAsShortRep(nextOpt);
1261        nextIsChar = True;
1262      }
1263    }
1264    numAvailFull = p->numAvail;
1265    {
1266      UInt32 temp = kNumOpts - 1 - cur;
1267      if (temp < numAvailFull)
1268        numAvailFull = temp;
1269    }
1270 
1271    if (numAvailFull < 2)
1272      continue;
1273    numAvail = (numAvailFull <= p->numFastBytes ? numAvailFull : p->numFastBytes);
1274 
1275    if (!nextIsChar && matchByte != curByte) /* speed optimization */
1276    {
1277      /* try Literal + rep0 */
1278      UInt32 temp;
1279      UInt32 lenTest2;
1280      const Byte *data2 = data - (reps[0] + 1);
1281      UInt32 limit = p->numFastBytes + 1;
1282      if (limit > numAvailFull)
1283        limit = numAvailFull;
1284 
1285      for (temp = 1; temp < limit && data[temp] == data2[temp]; temp++);
1286      lenTest2 = temp - 1;
1287      if (lenTest2 >= 2)
1288      {
1289        UInt32 state2 = kLiteralNextStates[state];
1290        UInt32 posStateNext = (position + 1) & p->pbMask;
1291        UInt32 nextRepMatchPrice = curAnd1Price +
1292            GET_PRICE_1(p->isMatch[state2][posStateNext]) +
1293            GET_PRICE_1(p->isRep[state2]);
1294        /* for (; lenTest2 >= 2; lenTest2--) */
1295        {
1296          UInt32 curAndLenPrice;
1297          COptimal *opt;
1298          UInt32 offset = cur + 1 + lenTest2;
1299          while (lenEnd < offset)
1300            p->opt[++lenEnd].price = kInfinityPrice;
1301          curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
1302          opt = &p->opt[offset];
1303          if (curAndLenPrice < opt->price)
1304          {
1305            opt->price = curAndLenPrice;
1306            opt->posPrev = cur + 1;
1307            opt->backPrev = 0;
1308            opt->prev1IsChar = True;
1309            opt->prev2 = False;
1310          }
1311        }
1312      }
1313    }
1314     
1315    startLen = 2; /* speed optimization */
1316    {
1317    UInt32 repIndex;
1318    for (repIndex = 0; repIndex < LZMA_NUM_REPS; repIndex++)
1319    {
1320      UInt32 lenTest;
1321      UInt32 lenTestTemp;
1322      UInt32 price;
1323      const Byte *data2 = data - (reps[repIndex] + 1);
1324      if (data[0] != data2[0] || data[1] != data2[1])
1325        continue;
1326      for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++);
1327      while (lenEnd < cur + lenTest)
1328        p->opt[++lenEnd].price = kInfinityPrice;
1329      lenTestTemp = lenTest;
1330      price = repMatchPrice + GetPureRepPrice(p, repIndex, state, posState);
1331      do
1332      {
1333        UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][lenTest - 2];
1334        COptimal *opt = &p->opt[cur + lenTest];
1335        if (curAndLenPrice < opt->price)
1336        {
1337          opt->price = curAndLenPrice;
1338          opt->posPrev = cur;
1339          opt->backPrev = repIndex;
1340          opt->prev1IsChar = False;
1341        }
1342      }
1343      while (--lenTest >= 2);
1344      lenTest = lenTestTemp;
1345       
1346      if (repIndex == 0)
1347        startLen = lenTest + 1;
1348         
1349      /* if (_maxMode) */
1350        {
1351          UInt32 lenTest2 = lenTest + 1;
1352          UInt32 limit = lenTest2 + p->numFastBytes;
1353          UInt32 nextRepMatchPrice;
1354          if (limit > numAvailFull)
1355            limit = numAvailFull;
1356          for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++);
1357          lenTest2 -= lenTest + 1;
1358          if (lenTest2 >= 2)
1359          {
1360            UInt32 state2 = kRepNextStates[state];
1361            UInt32 posStateNext = (position + lenTest) & p->pbMask;
1362            UInt32 curAndLenCharPrice =
1363                price + p->repLenEnc.prices[posState][lenTest - 2] +
1364                GET_PRICE_0(p->isMatch[state2][posStateNext]) +
1365                LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]),
1366                    data[lenTest], data2[lenTest], p->ProbPrices);
1367            state2 = kLiteralNextStates[state2];
1368            posStateNext = (position + lenTest + 1) & p->pbMask;
1369            nextRepMatchPrice = curAndLenCharPrice +
1370                GET_PRICE_1(p->isMatch[state2][posStateNext]) +
1371                GET_PRICE_1(p->isRep[state2]);
1372             
1373            /* for (; lenTest2 >= 2; lenTest2--) */
1374            {
1375              UInt32 curAndLenPrice;
1376              COptimal *opt;
1377              UInt32 offset = cur + lenTest + 1 + lenTest2;
1378              while (lenEnd < offset)
1379                p->opt[++lenEnd].price = kInfinityPrice;
1380              curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
1381              opt = &p->opt[offset];
1382              if (curAndLenPrice < opt->price)
1383              {
1384                opt->price = curAndLenPrice;
1385                opt->posPrev = cur + lenTest + 1;
1386                opt->backPrev = 0;
1387                opt->prev1IsChar = True;
1388                opt->prev2 = True;
1389                opt->posPrev2 = cur;
1390                opt->backPrev2 = repIndex;
1391              }
1392            }
1393          }
1394        }
1395    }
1396    }
1397    /* for (UInt32 lenTest = 2; lenTest <= newLen; lenTest++) */
1398    if (newLen > numAvail)
1399    {
1400      newLen = numAvail;
1401      for (numPairs = 0; newLen > matches[numPairs]; numPairs += 2);
1402      matches[numPairs] = newLen;
1403      numPairs += 2;
1404    }
1405    if (newLen >= startLen)
1406    {
1407      UInt32 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[state]);
1408      UInt32 offs, curBack, posSlot;
1409      UInt32 lenTest;
1410      while (lenEnd < cur + newLen)
1411        p->opt[++lenEnd].price = kInfinityPrice;
1412 
1413      offs = 0;
1414      while (startLen > matches[offs])
1415        offs += 2;
1416      curBack = matches[offs + 1];
1417      GetPosSlot2(curBack, posSlot);
1418      for (lenTest = /*2*/ startLen; ; lenTest++)
1419      {
1420        UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][lenTest - LZMA_MATCH_LEN_MIN];
1421        UInt32 lenToPosState = GetLenToPosState(lenTest);
1422        COptimal *opt;
1423        if (curBack < kNumFullDistances)
1424          curAndLenPrice += p->distancesPrices[lenToPosState][curBack];
1425        else
1426          curAndLenPrice += p->posSlotPrices[lenToPosState][posSlot] + p->alignPrices[curBack & kAlignMask];
1427         
1428        opt = &p->opt[cur + lenTest];
1429        if (curAndLenPrice < opt->price)
1430        {
1431          opt->price = curAndLenPrice;
1432          opt->posPrev = cur;
1433          opt->backPrev = curBack + LZMA_NUM_REPS;
1434          opt->prev1IsChar = False;
1435        }
1436 
1437        if (/*_maxMode && */lenTest == matches[offs])
1438        {
1439          /* Try Match + Literal + Rep0 */
1440          const Byte *data2 = data - (curBack + 1);
1441          UInt32 lenTest2 = lenTest + 1;
1442          UInt32 limit = lenTest2 + p->numFastBytes;
1443          UInt32 nextRepMatchPrice;
1444          if (limit > numAvailFull)
1445            limit = numAvailFull;
1446          for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++);
1447          lenTest2 -= lenTest + 1;
1448          if (lenTest2 >= 2)
1449          {
1450            UInt32 state2 = kMatchNextStates[state];
1451            UInt32 posStateNext = (position + lenTest) & p->pbMask;
1452            UInt32 curAndLenCharPrice = curAndLenPrice +
1453                GET_PRICE_0(p->isMatch[state2][posStateNext]) +
1454                LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]),
1455                    data[lenTest], data2[lenTest], p->ProbPrices);
1456            state2 = kLiteralNextStates[state2];
1457            posStateNext = (posStateNext + 1) & p->pbMask;
1458            nextRepMatchPrice = curAndLenCharPrice +
1459                GET_PRICE_1(p->isMatch[state2][posStateNext]) +
1460                GET_PRICE_1(p->isRep[state2]);
1461             
1462            /* for (; lenTest2 >= 2; lenTest2--) */
1463            {
1464              UInt32 offset = cur + lenTest + 1 + lenTest2;
1465              UInt32 curAndLenPrice;
1466              COptimal *opt;
1467              while (lenEnd < offset)
1468                p->opt[++lenEnd].price = kInfinityPrice;
1469              curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
1470              opt = &p->opt[offset];
1471              if (curAndLenPrice < opt->price)
1472              {
1473                opt->price = curAndLenPrice;
1474                opt->posPrev = cur + lenTest + 1;
1475                opt->backPrev = 0;
1476                opt->prev1IsChar = True;
1477                opt->prev2 = True;
1478                opt->posPrev2 = cur;
1479                opt->backPrev2 = curBack + LZMA_NUM_REPS;
1480              }
1481            }
1482          }
1483          offs += 2;
1484          if (offs == numPairs)
1485            break;
1486          curBack = matches[offs + 1];
1487          if (curBack >= kNumFullDistances)
1488            GetPosSlot2(curBack, posSlot);
1489        }
1490      }
1491    }
1492  }
1493}
1494 
1495#define ChangePair(smallDist, bigDist) (((bigDist) >> 7) > (smallDist))
1496 
1497static UInt32 GetOptimumFast(CLzmaEnc *p, UInt32 *backRes)
1498{
1499  UInt32 numAvail, mainLen, mainDist, numPairs, repIndex, repLen, i;
1500  const Byte *data;
1501  const UInt32 *matches;
1502 
1503  if (p->additionalOffset == 0)
1504    mainLen = ReadMatchDistances(p, &numPairs);
1505  else
1506  {
1507    mainLen = p->longestMatchLength;
1508    numPairs = p->numPairs;
1509  }
1510 
1511  numAvail = p->numAvail;
1512  *backRes = (UInt32)-1;
1513  if (numAvail < 2)
1514    return 1;
1515  if (numAvail > LZMA_MATCH_LEN_MAX)
1516    numAvail = LZMA_MATCH_LEN_MAX;
1517  data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
1518 
1519  repLen = repIndex = 0;
1520  for (i = 0; i < LZMA_NUM_REPS; i++)
1521  {
1522    UInt32 len;
1523    const Byte *data2 = data - (p->reps[i] + 1);
1524    if (data[0] != data2[0] || data[1] != data2[1])
1525      continue;
1526    for (len = 2; len < numAvail && data[len] == data2[len]; len++);
1527    if (len >= p->numFastBytes)
1528    {
1529      *backRes = i;
1530      MovePos(p, len - 1);
1531      return len;
1532    }
1533    if (len > repLen)
1534    {
1535      repIndex = i;
1536      repLen = len;
1537    }
1538  }
1539 
1540  matches = p->matches;
1541  if (mainLen >= p->numFastBytes)
1542  {
1543    *backRes = matches[numPairs - 1] + LZMA_NUM_REPS;
1544    MovePos(p, mainLen - 1);
1545    return mainLen;
1546  }
1547 
1548  mainDist = 0; /* for GCC */
1549  if (mainLen >= 2)
1550  {
1551    mainDist = matches[numPairs - 1];
1552    while (numPairs > 2 && mainLen == matches[numPairs - 4] + 1)
1553    {
1554      if (!ChangePair(matches[numPairs - 3], mainDist))
1555        break;
1556      numPairs -= 2;
1557      mainLen = matches[numPairs - 2];
1558      mainDist = matches[numPairs - 1];
1559    }
1560    if (mainLen == 2 && mainDist >= 0x80)
1561      mainLen = 1;
1562  }
1563 
1564  if (repLen >= 2 && (
1565        (repLen + 1 >= mainLen) ||
1566        (repLen + 2 >= mainLen && mainDist >= (1 << 9)) ||
1567        (repLen + 3 >= mainLen && mainDist >= (1 << 15))))
1568  {
1569    *backRes = repIndex;
1570    MovePos(p, repLen - 1);
1571    return repLen;
1572  }
1573   
1574  if (mainLen < 2 || numAvail <= 2)
1575    return 1;
1576 
1577  p->longestMatchLength = ReadMatchDistances(p, &p->numPairs);
1578  if (p->longestMatchLength >= 2)
1579  {
1580    UInt32 newDistance = matches[p->numPairs - 1];
1581    if ((p->longestMatchLength >= mainLen && newDistance < mainDist) ||
1582        (p->longestMatchLength == mainLen + 1 && !ChangePair(mainDist, newDistance)) ||
1583        (p->longestMatchLength > mainLen + 1) ||
1584        (p->longestMatchLength + 1 >= mainLen && mainLen >= 3 && ChangePair(newDistance, mainDist)))
1585      return 1;
1586  }
1587   
1588  data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
1589  for (i = 0; i < LZMA_NUM_REPS; i++)
1590  {
1591    UInt32 len, limit;
1592    const Byte *data2 = data - (p->reps[i] + 1);
1593    if (data[0] != data2[0] || data[1] != data2[1])
1594      continue;
1595    limit = mainLen - 1;
1596    for (len = 2; len < limit && data[len] == data2[len]; len++);
1597    if (len >= limit)
1598      return 1;
1599  }
1600  *backRes = mainDist + LZMA_NUM_REPS;
1601  MovePos(p, mainLen - 2);
1602  return mainLen;
1603}
1604 
1605static void WriteEndMarker(CLzmaEnc *p, UInt32 posState)
1606{
1607  UInt32 len;
1608  RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1);
1609  RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0);
1610  p->state = kMatchNextStates[p->state];
1611  len = LZMA_MATCH_LEN_MIN;
1612  LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
1613  RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, (1 << kNumPosSlotBits) - 1);
1614  RangeEnc_EncodeDirectBits(&p->rc, (((UInt32)1 << 30) - 1) >> kNumAlignBits, 30 - kNumAlignBits);
1615  RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, kAlignMask);
1616}
1617 
1618static SRes CheckErrors(CLzmaEnc *p)
1619{
1620  if (p->result != SZ_OK)
1621    return p->result;
1622  if (p->rc.res != SZ_OK)
1623    p->result = SZ_ERROR_WRITE;
1624  if (p->matchFinderBase.result != SZ_OK)
1625    p->result = SZ_ERROR_READ;
1626  if (p->result != SZ_OK)
1627    p->finished = True;
1628  return p->result;
1629}
1630 
1631static SRes Flush(CLzmaEnc *p, UInt32 nowPos)
1632{
1633  /* ReleaseMFStream(); */
1634  p->finished = True;
1635  if (p->writeEndMark)
1636    WriteEndMarker(p, nowPos & p->pbMask);
1637  RangeEnc_FlushData(&p->rc);
1638  RangeEnc_FlushStream(&p->rc);
1639  return CheckErrors(p);
1640}
1641 
1642static void FillAlignPrices(CLzmaEnc *p)
1643{
1644  UInt32 i;
1645  for (i = 0; i < kAlignTableSize; i++)
1646    p->alignPrices[i] = RcTree_ReverseGetPrice(p->posAlignEncoder, kNumAlignBits, i, p->ProbPrices);
1647  p->alignPriceCount = 0;
1648}
1649 
1650static void FillDistancesPrices(CLzmaEnc *p)
1651{
1652  UInt32 tempPrices[kNumFullDistances];
1653  UInt32 i, lenToPosState;
1654  for (i = kStartPosModelIndex; i < kNumFullDistances; i++)
1655  {
1656    UInt32 posSlot = GetPosSlot1(i);
1657    UInt32 footerBits = ((posSlot >> 1) - 1);
1658    UInt32 base = ((2 | (posSlot & 1)) << footerBits);
1659    tempPrices[i] = RcTree_ReverseGetPrice(p->posEncoders + base - posSlot - 1, footerBits, i - base, p->ProbPrices);
1660  }
1661 
1662  for (lenToPosState = 0; lenToPosState < kNumLenToPosStates; lenToPosState++)
1663  {
1664    UInt32 posSlot;
1665    const CLzmaProb *encoder = p->posSlotEncoder[lenToPosState];
1666    UInt32 *posSlotPrices = p->posSlotPrices[lenToPosState];
1667    for (posSlot = 0; posSlot < p->distTableSize; posSlot++)
1668      posSlotPrices[posSlot] = RcTree_GetPrice(encoder, kNumPosSlotBits, posSlot, p->ProbPrices);
1669    for (posSlot = kEndPosModelIndex; posSlot < p->distTableSize; posSlot++)
1670      posSlotPrices[posSlot] += ((((posSlot >> 1) - 1) - kNumAlignBits) << kNumBitPriceShiftBits);
1671 
1672    {
1673      UInt32 *distancesPrices = p->distancesPrices[lenToPosState];
1674      UInt32 i;
1675      for (i = 0; i < kStartPosModelIndex; i++)
1676        distancesPrices[i] = posSlotPrices[i];
1677      for (; i < kNumFullDistances; i++)
1678        distancesPrices[i] = posSlotPrices[GetPosSlot1(i)] + tempPrices[i];
1679    }
1680  }
1681  p->matchPriceCount = 0;
1682}
1683 
1684void LzmaEnc_Construct(CLzmaEnc *p)
1685{
1686  RangeEnc_Construct(&p->rc);
1687  MatchFinder_Construct(&p->matchFinderBase);
1688  #ifndef _7ZIP_ST
1689  MatchFinderMt_Construct(&p->matchFinderMt);
1690  p->matchFinderMt.MatchFinder = &p->matchFinderBase;
1691  #endif
1692 
1693  {
1694    CLzmaEncProps props;
1695    LzmaEncProps_Init(&props);
1696    LzmaEnc_SetProps(p, &props);
1697  }
1698 
1699  #ifndef LZMA_LOG_BSR
1700  LzmaEnc_FastPosInit(p->g_FastPos);
1701  #endif
1702 
1703  LzmaEnc_InitPriceTables(p->ProbPrices);
1704  p->litProbs = 0;
1705  p->saveState.litProbs = 0;
1706}
1707 
1708CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc)
1709{
1710  void *p;
1711  p = alloc->Alloc(alloc, sizeof(CLzmaEnc));
1712  if (p != 0)
1713    LzmaEnc_Construct((CLzmaEnc *)p);
1714  return p;
1715}
1716 
1717void LzmaEnc_FreeLits(CLzmaEnc *p, ISzAlloc *alloc)
1718{
1719  alloc->Free(alloc, p->litProbs);
1720  alloc->Free(alloc, p->saveState.litProbs);
1721  p->litProbs = 0;
1722  p->saveState.litProbs = 0;
1723}
1724 
1725void LzmaEnc_Destruct(CLzmaEnc *p, ISzAlloc *alloc, ISzAlloc *allocBig)
1726{
1727  #ifndef _7ZIP_ST
1728  MatchFinderMt_Destruct(&p->matchFinderMt, allocBig);
1729  #endif
1730  MatchFinder_Free(&p->matchFinderBase, allocBig);
1731  LzmaEnc_FreeLits(p, alloc);
1732  RangeEnc_Free(&p->rc, alloc);
1733}
1734 
1735void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig)
1736{
1737  LzmaEnc_Destruct((CLzmaEnc *)p, alloc, allocBig);
1738  alloc->Free(alloc, p);
1739}
1740 
1741static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, Bool useLimits, UInt32 maxPackSize, UInt32 maxUnpackSize)
1742{
1743  UInt32 nowPos32, startPos32;
1744  if (p->needInit)
1745  {
1746    p->matchFinder.Init(p->matchFinderObj);
1747    p->needInit = 0;
1748  }
1749 
1750  if (p->finished)
1751    return p->result;
1752  RINOK(CheckErrors(p));
1753 
1754  nowPos32 = (UInt32)p->nowPos64;
1755  startPos32 = nowPos32;
1756 
1757  if (p->nowPos64 == 0)
1758  {
1759    UInt32 numPairs;
1760    Byte curByte;
1761    if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
1762      return Flush(p, nowPos32);
1763    ReadMatchDistances(p, &numPairs);
1764    RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][0], 0);
1765    p->state = kLiteralNextStates[p->state];
1766    curByte = p->matchFinder.GetIndexByte(p->matchFinderObj, 0 - p->additionalOffset);
1767    LitEnc_Encode(&p->rc, p->litProbs, curByte);
1768    p->additionalOffset--;
1769    nowPos32++;
1770  }
1771 
1772  if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) != 0)
1773  for (;;)
1774  {
1775    UInt32 pos, len, posState;
1776 
1777    if (p->fastMode)
1778      len = GetOptimumFast(p, &pos);
1779    else
1780      len = GetOptimum(p, nowPos32, &pos);
1781 
1782    #ifdef SHOW_STAT2
1783    printf("\n pos = %4X,   len = %d   pos = %d", nowPos32, len, pos);
1784    #endif
1785 
1786    posState = nowPos32 & p->pbMask;
1787    if (len == 1 && pos == (UInt32)-1)
1788    {
1789      Byte curByte;
1790      CLzmaProb *probs;
1791      const Byte *data;
1792 
1793      RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 0);
1794      data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
1795      curByte = *data;
1796      probs = LIT_PROBS(nowPos32, *(data - 1));
1797      if (IsCharState(p->state))
1798        LitEnc_Encode(&p->rc, probs, curByte);
1799      else
1800        LitEnc_EncodeMatched(&p->rc, probs, curByte, *(data - p->reps[0] - 1));
1801      p->state = kLiteralNextStates[p->state];
1802    }
1803    else
1804    {
1805      RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1);
1806      if (pos < LZMA_NUM_REPS)
1807      {
1808        RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 1);
1809        if (pos == 0)
1810        {
1811          RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 0);
1812          RangeEnc_EncodeBit(&p->rc, &p->isRep0Long[p->state][posState], ((len == 1) ? 0 : 1));
1813        }
1814        else
1815        {
1816          UInt32 distance = p->reps[pos];
1817          RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 1);
1818          if (pos == 1)
1819            RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 0);
1820          else
1821          {
1822            RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 1);
1823            RangeEnc_EncodeBit(&p->rc, &p->isRepG2[p->state], pos - 2);
1824            if (pos == 3)
1825              p->reps[3] = p->reps[2];
1826            p->reps[2] = p->reps[1];
1827          }
1828          p->reps[1] = p->reps[0];
1829          p->reps[0] = distance;
1830        }
1831        if (len == 1)
1832          p->state = kShortRepNextStates[p->state];
1833        else
1834        {
1835          LenEnc_Encode2(&p->repLenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
1836          p->state = kRepNextStates[p->state];
1837        }
1838      }
1839      else
1840      {
1841        UInt32 posSlot;
1842        RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0);
1843        p->state = kMatchNextStates[p->state];
1844        LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
1845        pos -= LZMA_NUM_REPS;
1846        GetPosSlot(pos, posSlot);
1847        RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, posSlot);
1848         
1849        if (posSlot >= kStartPosModelIndex)
1850        {
1851          UInt32 footerBits = ((posSlot >> 1) - 1);
1852          UInt32 base = ((2 | (posSlot & 1)) << footerBits);
1853          UInt32 posReduced = pos - base;
1854 
1855          if (posSlot < kEndPosModelIndex)
1856            RcTree_ReverseEncode(&p->rc, p->posEncoders + base - posSlot - 1, footerBits, posReduced);
1857          else
1858          {
1859            RangeEnc_EncodeDirectBits(&p->rc, posReduced >> kNumAlignBits, footerBits - kNumAlignBits);
1860            RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, posReduced & kAlignMask);
1861            p->alignPriceCount++;
1862          }
1863        }
1864        p->reps[3] = p->reps[2];
1865        p->reps[2] = p->reps[1];
1866        p->reps[1] = p->reps[0];
1867        p->reps[0] = pos;
1868        p->matchPriceCount++;
1869      }
1870    }
1871    p->additionalOffset -= len;
1872    nowPos32 += len;
1873    if (p->additionalOffset == 0)
1874    {
1875      UInt32 processed;
1876      if (!p->fastMode)
1877      {
1878        if (p->matchPriceCount >= (1 << 7))
1879          FillDistancesPrices(p);
1880        if (p->alignPriceCount >= kAlignTableSize)
1881          FillAlignPrices(p);
1882      }
1883      if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
1884        break;
1885      processed = nowPos32 - startPos32;
1886      if (useLimits)
1887      {
1888        if (processed + kNumOpts + 300 >= maxUnpackSize ||
1889            RangeEnc_GetProcessed(&p->rc) + kNumOpts * 2 >= maxPackSize)
1890          break;
1891      }
1892      else if (processed >= (1 << 15))
1893      {
1894        p->nowPos64 += nowPos32 - startPos32;
1895        return CheckErrors(p);
1896      }
1897    }
1898  }
1899  p->nowPos64 += nowPos32 - startPos32;
1900  return Flush(p, nowPos32);
1901}
1902 
1903#define kBigHashDicLimit ((UInt32)1 << 24)
1904 
1905static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
1906{
1907  UInt32 beforeSize = kNumOpts;
1908  Bool btMode;
1909  if (!RangeEnc_Alloc(&p->rc, alloc))
1910    return SZ_ERROR_MEM;
1911  btMode = (p->matchFinderBase.btMode != 0);
1912  #ifndef _7ZIP_ST
1913  p->mtMode = (p->multiThread && !p->fastMode && btMode);
1914  #endif
1915 
1916  {
1917    unsigned lclp = p->lc + p->lp;
1918    if (p->litProbs == 0 || p->saveState.litProbs == 0 || p->lclp != lclp)
1919    {
1920      LzmaEnc_FreeLits(p, alloc);
1921      p->litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb));
1922      p->saveState.litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb));
1923      if (p->litProbs == 0 || p->saveState.litProbs == 0)
1924      {
1925        LzmaEnc_FreeLits(p, alloc);
1926        return SZ_ERROR_MEM;
1927      }
1928      p->lclp = lclp;
1929    }
1930  }
1931 
1932  p->matchFinderBase.bigHash = (p->dictSize > kBigHashDicLimit);
1933 
1934  if (beforeSize + p->dictSize < keepWindowSize)
1935    beforeSize = keepWindowSize - p->dictSize;
1936 
1937  #ifndef _7ZIP_ST
1938  if (p->mtMode)
1939  {
1940    RINOK(MatchFinderMt_Create(&p->matchFinderMt, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig));
1941    p->matchFinderObj = &p->matchFinderMt;
1942    MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder);
1943  }
1944  else
1945  #endif
1946  {
1947    if (!MatchFinder_Create(&p->matchFinderBase, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig))
1948      return SZ_ERROR_MEM;
1949    p->matchFinderObj = &p->matchFinderBase;
1950    MatchFinder_CreateVTable(&p->matchFinderBase, &p->matchFinder);
1951  }
1952  return SZ_OK;
1953}
1954 
1955void LzmaEnc_Init(CLzmaEnc *p)
1956{
1957  UInt32 i;
1958  p->state = 0;
1959  for (i = 0 ; i < LZMA_NUM_REPS; i++)
1960    p->reps[i] = 0;
1961 
1962  RangeEnc_Init(&p->rc);
1963 
1964 
1965  for (i = 0; i < kNumStates; i++)
1966  {
1967    UInt32 j;
1968    for (j = 0; j < LZMA_NUM_PB_STATES_MAX; j++)
1969    {
1970      p->isMatch[i][j] = kProbInitValue;
1971      p->isRep0Long[i][j] = kProbInitValue;
1972    }
1973    p->isRep[i] = kProbInitValue;
1974    p->isRepG0[i] = kProbInitValue;
1975    p->isRepG1[i] = kProbInitValue;
1976    p->isRepG2[i] = kProbInitValue;
1977  }
1978 
1979  {
1980    UInt32 num = 0x300 << (p->lp + p->lc);
1981    for (i = 0; i < num; i++)
1982      p->litProbs[i] = kProbInitValue;
1983  }
1984 
1985  {
1986    for (i = 0; i < kNumLenToPosStates; i++)
1987    {
1988      CLzmaProb *probs = p->posSlotEncoder[i];
1989      UInt32 j;
1990      for (j = 0; j < (1 << kNumPosSlotBits); j++)
1991        probs[j] = kProbInitValue;
1992    }
1993  }
1994  {
1995    for (i = 0; i < kNumFullDistances - kEndPosModelIndex; i++)
1996      p->posEncoders[i] = kProbInitValue;
1997  }
1998 
1999  LenEnc_Init(&p->lenEnc.p);
2000  LenEnc_Init(&p->repLenEnc.p);
2001 
2002  for (i = 0; i < (1 << kNumAlignBits); i++)
2003    p->posAlignEncoder[i] = kProbInitValue;
2004 
2005  p->optimumEndIndex = 0;
2006  p->optimumCurrentIndex = 0;
2007  p->additionalOffset = 0;
2008 
2009  p->pbMask = (1 << p->pb) - 1;
2010  p->lpMask = (1 << p->lp) - 1;
2011}
2012 
2013void LzmaEnc_InitPrices(CLzmaEnc *p)
2014{
2015  if (!p->fastMode)
2016  {
2017    FillDistancesPrices(p);
2018    FillAlignPrices(p);
2019  }
2020 
2021  p->lenEnc.tableSize =
2022  p->repLenEnc.tableSize =
2023      p->numFastBytes + 1 - LZMA_MATCH_LEN_MIN;
2024  LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, p->ProbPrices);
2025  LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, p->ProbPrices);
2026}
2027 
2028static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
2029{
2030  UInt32 i;
2031  for (i = 0; i < (UInt32)kDicLogSizeMaxCompress; i++)
2032    if (p->dictSize <= ((UInt32)1 << i))
2033      break;
2034  p->distTableSize = i * 2;
2035 
2036  p->finished = False;
2037  p->result = SZ_OK;
2038  RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig));
2039  LzmaEnc_Init(p);
2040  LzmaEnc_InitPrices(p);
2041  p->nowPos64 = 0;
2042  return SZ_OK;
2043}
2044 
2045static SRes LzmaEnc_Prepare(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream,
2046    ISzAlloc *alloc, ISzAlloc *allocBig)
2047{
2048  CLzmaEnc *p = (CLzmaEnc *)pp;
2049  p->matchFinderBase.stream = inStream;
2050  p->needInit = 1;
2051  p->rc.outStream = outStream;
2052  return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig);
2053}
2054 
2055SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp,
2056    ISeqInStream *inStream, UInt32 keepWindowSize,
2057    ISzAlloc *alloc, ISzAlloc *allocBig)
2058{
2059  CLzmaEnc *p = (CLzmaEnc *)pp;
2060  p->matchFinderBase.stream = inStream;
2061  p->needInit = 1;
2062  return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
2063}
2064 
2065static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen)
2066{
2067  p->matchFinderBase.directInput = 1;
2068  p->matchFinderBase.bufferBase = (Byte *)src;
2069  p->matchFinderBase.directInputRem = srcLen;
2070}
2071 
2072SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen,
2073    UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
2074{
2075  CLzmaEnc *p = (CLzmaEnc *)pp;
2076  LzmaEnc_SetInputBuf(p, src, srcLen);
2077  p->needInit = 1;
2078 
2079  return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
2080}
2081 
2082void LzmaEnc_Finish(CLzmaEncHandle pp)
2083{
2084  #ifndef _7ZIP_ST
2085  CLzmaEnc *p = (CLzmaEnc *)pp;
2086  if (p->mtMode)
2087    MatchFinderMt_ReleaseStream(&p->matchFinderMt);
2088  #else
2089  pp = pp;
2090  #endif
2091}
2092 
2093typedef struct
2094{
2095  ISeqOutStream funcTable;
2096  Byte *data;
2097  SizeT rem;
2098  Bool overflow;
2099} CSeqOutStreamBuf;
2100 
2101static size_t MyWrite(void *pp, const void *data, size_t size)
2102{
2103  CSeqOutStreamBuf *p = (CSeqOutStreamBuf *)pp;
2104  if (p->rem < size)
2105  {
2106    size = p->rem;
2107    p->overflow = True;
2108  }
2109  memcpy(p->data, data, size);
2110  p->rem -= size;
2111  p->data += size;
2112  return size;
2113}
2114 
2115 
2116UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp)
2117{
2118  const CLzmaEnc *p = (CLzmaEnc *)pp;
2119  return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
2120}
2121 
2122const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp)
2123{
2124  const CLzmaEnc *p = (CLzmaEnc *)pp;
2125  return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
2126}
2127 
2128SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, Bool reInit,
2129    Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize)
2130{
2131  CLzmaEnc *p = (CLzmaEnc *)pp;
2132  UInt64 nowPos64;
2133  SRes res;
2134  CSeqOutStreamBuf outStream;
2135 
2136  outStream.funcTable.Write = MyWrite;
2137  outStream.data = dest;
2138  outStream.rem = *destLen;
2139  outStream.overflow = False;
2140 
2141  p->writeEndMark = False;
2142  p->finished = False;
2143  p->result = SZ_OK;
2144 
2145  if (reInit)
2146    LzmaEnc_Init(p);
2147  LzmaEnc_InitPrices(p);
2148  nowPos64 = p->nowPos64;
2149  RangeEnc_Init(&p->rc);
2150  p->rc.outStream = &outStream.funcTable;
2151 
2152  res = LzmaEnc_CodeOneBlock(p, True, desiredPackSize, *unpackSize);
2153   
2154  *unpackSize = (UInt32)(p->nowPos64 - nowPos64);
2155  *destLen -= outStream.rem;
2156  if (outStream.overflow)
2157    return SZ_ERROR_OUTPUT_EOF;
2158 
2159  return res;
2160}
2161 
2162static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress)
2163{
2164  SRes res = SZ_OK;
2165 
2166  #ifndef _7ZIP_ST
2167  Byte allocaDummy[0x300];
2168  int i = 0;
2169  for (i = 0; i < 16; i++)
2170    allocaDummy[i] = (Byte)i;
2171  #endif
2172 
2173  for (;;)
2174  {
2175    res = LzmaEnc_CodeOneBlock(p, False, 0, 0);
2176    if (res != SZ_OK || p->finished != 0)
2177      break;
2178    if (progress != 0)
2179    {
2180      res = progress->Progress(progress, p->nowPos64, RangeEnc_GetProcessed(&p->rc));
2181      if (res != SZ_OK)
2182      {
2183        res = SZ_ERROR_PROGRESS;
2184        break;
2185      }
2186    }
2187  }
2188  LzmaEnc_Finish(p);
2189  return res;
2190}
2191 
2192SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress,
2193    ISzAlloc *alloc, ISzAlloc *allocBig)
2194{
2195  RINOK(LzmaEnc_Prepare(pp, outStream, inStream, alloc, allocBig));
2196  return LzmaEnc_Encode2((CLzmaEnc *)pp, progress);
2197}
2198 
2199SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size)
2200{
2201  CLzmaEnc *p = (CLzmaEnc *)pp;
2202  int i;
2203  UInt32 dictSize = p->dictSize;
2204  if (*size < LZMA_PROPS_SIZE)
2205    return SZ_ERROR_PARAM;
2206  *size = LZMA_PROPS_SIZE;
2207  props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc);
2208 
2209  for (i = 11; i <= 30; i++)
2210  {
2211    if (dictSize <= ((UInt32)2 << i))
2212    {
2213      dictSize = (2 << i);
2214      break;
2215    }
2216    if (dictSize <= ((UInt32)3 << i))
2217    {
2218      dictSize = (3 << i);
2219      break;
2220    }
2221  }
2222 
2223  for (i = 0; i < 4; i++)
2224    props[1 + i] = (Byte)(dictSize >> (8 * i));
2225  return SZ_OK;
2226}
2227 
2228SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
2229    int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig)
2230{
2231  SRes res;
2232  CLzmaEnc *p = (CLzmaEnc *)pp;
2233 
2234  CSeqOutStreamBuf outStream;
2235 
2236  LzmaEnc_SetInputBuf(p, src, srcLen);
2237 
2238  outStream.funcTable.Write = MyWrite;
2239  outStream.data = dest;
2240  outStream.rem = *destLen;
2241  outStream.overflow = False;
2242 
2243  p->writeEndMark = writeEndMark;
2244 
2245  p->rc.outStream = &outStream.funcTable;
2246  res = LzmaEnc_MemPrepare(pp, src, srcLen, 0, alloc, allocBig);
2247  if (res == SZ_OK)
2248    res = LzmaEnc_Encode2(p, progress);
2249 
2250  *destLen -= outStream.rem;
2251  if (outStream.overflow)
2252    return SZ_ERROR_OUTPUT_EOF;
2253  return res;
2254}
2255 
2256SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
2257    const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
2258    ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig)
2259{
2260  CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc);
2261  SRes res;
2262  if (p == 0)
2263    return SZ_ERROR_MEM;
2264 
2265  res = LzmaEnc_SetProps(p, props);
2266  if (res == SZ_OK)
2267  {
2268    res = LzmaEnc_WriteProperties(p, propsEncoded, propsSize);
2269    if (res == SZ_OK)
2270      res = LzmaEnc_MemEncode(p, dest, destLen, src, srcLen,
2271          writeEndMark, progress, alloc, allocBig);
2272  }
2273 
2274  LzmaEnc_Destroy(p, alloc, allocBig);
2275  return res;
2276}
src/lib/lib7z/Delta.c
r0r14440
1/* Delta.c -- Delta converter
22009-05-26 : Igor Pavlov : Public domain */
3 
4#include "Delta.h"
5 
6void Delta_Init(Byte *state)
7{
8  unsigned i;
9  for (i = 0; i < DELTA_STATE_SIZE; i++)
10    state[i] = 0;
11}
12 
13static void MyMemCpy(Byte *dest, const Byte *src, unsigned size)
14{
15  unsigned i;
16  for (i = 0; i < size; i++)
17    dest[i] = src[i];
18}
19 
20void Delta_Encode(Byte *state, unsigned delta, Byte *data, SizeT size)
21{
22  Byte buf[DELTA_STATE_SIZE];
23  unsigned j = 0;
24  MyMemCpy(buf, state, delta);
25  {
26    SizeT i;
27    for (i = 0; i < size;)
28    {
29      for (j = 0; j < delta && i < size; i++, j++)
30      {
31        Byte b = data[i];
32        data[i] = (Byte)(b - buf[j]);
33        buf[j] = b;
34      }
35    }
36  }
37  if (j == delta)
38    j = 0;
39  MyMemCpy(state, buf + j, delta - j);
40  MyMemCpy(state + delta - j, buf, j);
41}
42 
43void Delta_Decode(Byte *state, unsigned delta, Byte *data, SizeT size)
44{
45  Byte buf[DELTA_STATE_SIZE];
46  unsigned j = 0;
47  MyMemCpy(buf, state, delta);
48  {
49    SizeT i;
50    for (i = 0; i < size;)
51    {
52      for (j = 0; j < delta && i < size; i++, j++)
53      {
54        buf[j] = data[i] = (Byte)(buf[j] + data[i]);
55      }
56    }
57  }
58  if (j == delta)
59    j = 0;
60  MyMemCpy(state, buf + j, delta - j);
61  MyMemCpy(state + delta - j, buf, j);
62}
src/lib/lib7z/LzFind.h
r0r14440
1/* LzFind.h -- Match finder for LZ algorithms
22009-04-22 : Igor Pavlov : Public domain */
3 
4#ifndef __LZ_FIND_H
5#define __LZ_FIND_H
6 
7#include "Types.h"
8 
9#ifdef __cplusplus
10extern "C" {
11#endif
12 
13typedef UInt32 CLzRef;
14 
15typedef struct _CMatchFinder
16{
17  Byte *buffer;
18  UInt32 pos;
19  UInt32 posLimit;
20  UInt32 streamPos;
21  UInt32 lenLimit;
22 
23  UInt32 cyclicBufferPos;
24  UInt32 cyclicBufferSize; /* it must be = (historySize + 1) */
25 
26  UInt32 matchMaxLen;
27  CLzRef *hash;
28  CLzRef *son;
29  UInt32 hashMask;
30  UInt32 cutValue;
31 
32  Byte *bufferBase;
33  ISeqInStream *stream;
34  int streamEndWasReached;
35 
36  UInt32 blockSize;
37  UInt32 keepSizeBefore;
38  UInt32 keepSizeAfter;
39 
40  UInt32 numHashBytes;
41  int directInput;
42  size_t directInputRem;
43  int btMode;
44  int bigHash;
45  UInt32 historySize;
46  UInt32 fixedHashSize;
47  UInt32 hashSizeSum;
48  UInt32 numSons;
49  SRes result;
50  UInt32 crc[256];
51} CMatchFinder;
52 
53#define Inline_MatchFinder_GetPointerToCurrentPos(p) ((p)->buffer)
54#define Inline_MatchFinder_GetIndexByte(p, index) ((p)->buffer[(Int32)(index)])
55 
56#define Inline_MatchFinder_GetNumAvailableBytes(p) ((p)->streamPos - (p)->pos)
57 
58int MatchFinder_NeedMove(CMatchFinder *p);
59Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p);
60void MatchFinder_MoveBlock(CMatchFinder *p);
61void MatchFinder_ReadIfRequired(CMatchFinder *p);
62 
63void MatchFinder_Construct(CMatchFinder *p);
64 
65/* Conditions:
66     historySize <= 3 GB
67     keepAddBufferBefore + matchMaxLen + keepAddBufferAfter < 511MB
68*/
69int MatchFinder_Create(CMatchFinder *p, UInt32 historySize,
70    UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter,
71    ISzAlloc *alloc);
72void MatchFinder_Free(CMatchFinder *p, ISzAlloc *alloc);
73void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems);
74void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue);
75 
76UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *buffer, CLzRef *son,
77    UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 _cutValue,
78    UInt32 *distances, UInt32 maxLen);
79 
80/*
81Conditions:
82  Mf_GetNumAvailableBytes_Func must be called before each Mf_GetMatchLen_Func.
83  Mf_GetPointerToCurrentPos_Func's result must be used only before any other function
84*/
85 
86typedef void (*Mf_Init_Func)(void *object);
87typedef Byte (*Mf_GetIndexByte_Func)(void *object, Int32 index);
88typedef UInt32 (*Mf_GetNumAvailableBytes_Func)(void *object);
89typedef const Byte * (*Mf_GetPointerToCurrentPos_Func)(void *object);
90typedef UInt32 (*Mf_GetMatches_Func)(void *object, UInt32 *distances);
91typedef void (*Mf_Skip_Func)(void *object, UInt32);
92 
93typedef struct _IMatchFinder
94{
95  Mf_Init_Func Init;
96  Mf_GetIndexByte_Func GetIndexByte;
97  Mf_GetNumAvailableBytes_Func GetNumAvailableBytes;
98  Mf_GetPointerToCurrentPos_Func GetPointerToCurrentPos;
99  Mf_GetMatches_Func GetMatches;
100  Mf_Skip_Func Skip;
101} IMatchFinder;
102 
103void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable);
104 
105void MatchFinder_Init(CMatchFinder *p);
106UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances);
107UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances);
108void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num);
109void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num);
110 
111#ifdef __cplusplus
112}
113#endif
114 
115#endif
src/lib/lib7z/AesOpt.c
r0r14440
1/* AesOpt.c -- Intel's AES
22009-11-23 : Igor Pavlov : Public domain */
3 
4#include "CpuArch.h"
5 
6#ifdef MY_CPU_X86_OR_AMD64
7#if _MSC_VER >= 1500
8#define USE_INTEL_AES
9#endif
10#endif
11 
12#ifdef USE_INTEL_AES
13 
14#include <wmmintrin.h>
15 
16void MY_FAST_CALL AesCbc_Encode_Intel(__m128i *p, __m128i *data, size_t numBlocks)
17{
18  __m128i m = *p;
19  for (; numBlocks != 0; numBlocks--, data++)
20  {
21    UInt32 numRounds2 = *(const UInt32 *)(p + 1) - 1;
22    const __m128i *w = p + 3;
23    m = _mm_xor_si128(m, *data);
24    m = _mm_xor_si128(m, p[2]);
25    do
26    {
27      m = _mm_aesenc_si128(m, w[0]);
28      m = _mm_aesenc_si128(m, w[1]);
29      w += 2;
30    }
31    while (--numRounds2 != 0);
32    m = _mm_aesenc_si128(m, w[0]);
33    m = _mm_aesenclast_si128(m, w[1]);
34    *data = m;
35  }
36  *p = m;
37}
38 
39#define NUM_WAYS 3
40 
41#define AES_OP_W(op, n) { \
42    const __m128i t = w[n]; \
43    m0 = op(m0, t); \
44    m1 = op(m1, t); \
45    m2 = op(m2, t); \
46    }
47 
48#define AES_DEC(n) AES_OP_W(_mm_aesdec_si128, n)
49#define AES_DEC_LAST(n) AES_OP_W(_mm_aesdeclast_si128, n)
50#define AES_ENC(n) AES_OP_W(_mm_aesenc_si128, n)
51#define AES_ENC_LAST(n) AES_OP_W(_mm_aesenclast_si128, n)
52 
53void MY_FAST_CALL AesCbc_Decode_Intel(__m128i *p, __m128i *data, size_t numBlocks)
54{
55  __m128i iv = *p;
56  for (; numBlocks >= NUM_WAYS; numBlocks -= NUM_WAYS, data += NUM_WAYS)
57  {
58    UInt32 numRounds2 = *(const UInt32 *)(p + 1);
59    const __m128i *w = p + numRounds2 * 2;
60    __m128i m0, m1, m2;
61    {
62      const __m128i t = w[2];
63      m0 = _mm_xor_si128(t, data[0]);
64      m1 = _mm_xor_si128(t, data[1]);
65      m2 = _mm_xor_si128(t, data[2]);
66    }
67    numRounds2--;
68    do
69    {
70      AES_DEC(1)
71      AES_DEC(0)
72      w -= 2;
73    }
74    while (--numRounds2 != 0);
75    AES_DEC(1)
76    AES_DEC_LAST(0)
77 
78    {
79      __m128i t;
80      t = _mm_xor_si128(m0, iv); iv = data[0]; data[0] = t;
81      t = _mm_xor_si128(m1, iv); iv = data[1]; data[1] = t;
82      t = _mm_xor_si128(m2, iv); iv = data[2]; data[2] = t;
83    }
84  }
85  for (; numBlocks != 0; numBlocks--, data++)
86  {
87    UInt32 numRounds2 = *(const UInt32 *)(p + 1);
88    const __m128i *w = p + numRounds2 * 2;
89    __m128i m = _mm_xor_si128(w[2], *data);
90    numRounds2--;
91    do
92    {
93      m = _mm_aesdec_si128(m, w[1]);
94      m = _mm_aesdec_si128(m, w[0]);
95      w -= 2;
96    }
97    while (--numRounds2 != 0);
98    m = _mm_aesdec_si128(m, w[1]);
99    m = _mm_aesdeclast_si128(m, w[0]);
100 
101    m = _mm_xor_si128(m, iv);
102    iv = *data;
103    *data = m;
104  }
105  *p = iv;
106}
107 
108void MY_FAST_CALL AesCtr_Code_Intel(__m128i *p, __m128i *data, size_t numBlocks)
109{
110  __m128i ctr = *p;
111  __m128i one;
112  one.m128i_u64[0] = 1;
113  one.m128i_u64[1] = 0;
114  for (; numBlocks >= NUM_WAYS; numBlocks -= NUM_WAYS, data += NUM_WAYS)
115  {
116    UInt32 numRounds2 = *(const UInt32 *)(p + 1) - 1;
117    const __m128i *w = p;
118    __m128i m0, m1, m2;
119    {
120      const __m128i t = w[2];
121      ctr = _mm_add_epi64(ctr, one); m0 = _mm_xor_si128(ctr, t);
122      ctr = _mm_add_epi64(ctr, one); m1 = _mm_xor_si128(ctr, t);
123      ctr = _mm_add_epi64(ctr, one); m2 = _mm_xor_si128(ctr, t);
124    }
125    w += 3;
126    do
127    {
128      AES_ENC(0)
129      AES_ENC(1)
130      w += 2;
131    }
132    while (--numRounds2 != 0);
133    AES_ENC(0)
134    AES_ENC_LAST(1)
135    data[0] = _mm_xor_si128(data[0], m0);
136    data[1] = _mm_xor_si128(data[1], m1);
137    data[2] = _mm_xor_si128(data[2], m2);
138  }
139  for (; numBlocks != 0; numBlocks--, data++)
140  {
141    UInt32 numRounds2 = *(const UInt32 *)(p + 1) - 1;
142    const __m128i *w = p;
143    __m128i m;
144    ctr = _mm_add_epi64(ctr, one);
145    m = _mm_xor_si128(ctr, p[2]);
146    w += 3;
147    do
148    {
149      m = _mm_aesenc_si128(m, w[0]);
150      m = _mm_aesenc_si128(m, w[1]);
151      w += 2;
152    }
153    while (--numRounds2 != 0);
154    m = _mm_aesenc_si128(m, w[0]);
155    m = _mm_aesenclast_si128(m, w[1]);
156    *data = _mm_xor_si128(*data, m);
157  }
158  *p = ctr;
159}
160 
161#else
162 
163void MY_FAST_CALL AesCbc_Encode(UInt32 *ivAes, Byte *data, size_t numBlocks);
164void MY_FAST_CALL AesCbc_Decode(UInt32 *ivAes, Byte *data, size_t numBlocks);
165void MY_FAST_CALL AesCtr_Code(UInt32 *ivAes, Byte *data, size_t numBlocks);
166 
167void MY_FAST_CALL AesCbc_Encode_Intel(UInt32 *p, Byte *data, size_t numBlocks)
168{
169  AesCbc_Encode(p, data, numBlocks);
170}
171 
172void MY_FAST_CALL AesCbc_Decode_Intel(UInt32 *p, Byte *data, size_t numBlocks)
173{
174  AesCbc_Decode(p, data, numBlocks);
175}
176 
177void MY_FAST_CALL AesCtr_Code_Intel(UInt32 *p, Byte *data, size_t numBlocks)
178{
179  AesCtr_Code(p, data, numBlocks);
180}
181 
182#endif
src/lib/lib7z/Sort.h
r0r14440
1/* Sort.h -- Sort functions
22009-02-07 : Igor Pavlov : Public domain */
3 
4#ifndef __7Z_SORT_H
5#define __7Z_SORT_H
6 
7#include "Types.h"
8 
9#ifdef __cplusplus
10extern "C" {
11#endif
12 
13void HeapSort(UInt32 *p, UInt32 size);
14/* void HeapSortRef(UInt32 *p, UInt32 *vals, UInt32 size); */
15 
16#ifdef __cplusplus
17}
18#endif
19 
20#endif
src/lib/lib7z/Ppmd8.h
r0r14440
1/* Ppmd8.h -- PPMdI codec
22011-01-27 : Igor Pavlov : Public domain
3This code is based on:
4  PPMd var.I (2002): Dmitry Shkarin : Public domain
5  Carryless rangecoder (1999): Dmitry Subbotin : Public domain */
6 
7#ifndef __PPMD8_H
8#define __PPMD8_H
9 
10#include "Ppmd.h"
11 
12EXTERN_C_BEGIN
13 
14#define PPMD8_MIN_ORDER 2
15#define PPMD8_MAX_ORDER 16
16 
17struct CPpmd8_Context_;
18 
19typedef
20  #ifdef PPMD_32BIT
21    struct CPpmd8_Context_ *
22  #else
23    UInt32
24  #endif
25  CPpmd8_Context_Ref;
26 
27#pragma pack(push, 1)
28 
29typedef struct CPpmd8_Context_
30{
31  Byte NumStats;
32  Byte Flags;
33  UInt16 SummFreq;
34  CPpmd_State_Ref Stats;
35  CPpmd8_Context_Ref Suffix;
36} CPpmd8_Context;
37 
38#pragma pack(pop)
39 
40#define Ppmd8Context_OneState(p) ((CPpmd_State *)&(p)->SummFreq)
41 
42/* The BUG in Shkarin's code for FREEZE mode was fixed, but that fixed
43   code is not compatible with original code for some files compressed
44   in FREEZE mode. So we disable FREEZE mode support. */
45 
46enum
47{
48  PPMD8_RESTORE_METHOD_RESTART,
49  PPMD8_RESTORE_METHOD_CUT_OFF
50  #ifdef PPMD8_FREEZE_SUPPORT
51  , PPMD8_RESTORE_METHOD_FREEZE
52  #endif
53};
54 
55typedef struct
56{
57  CPpmd8_Context *MinContext, *MaxContext;
58  CPpmd_State *FoundState;
59  unsigned OrderFall, InitEsc, PrevSuccess, MaxOrder;
60  Int32 RunLength, InitRL; /* must be 32-bit at least */
61 
62  UInt32 Size;
63  UInt32 GlueCount;
64  Byte *Base, *LoUnit, *HiUnit, *Text, *UnitsStart;
65  UInt32 AlignOffset;
66  unsigned RestoreMethod;
67 
68  /* Range Coder */
69  UInt32 Range;
70  UInt32 Code;
71  UInt32 Low;
72  union
73  {
74    IByteIn *In;
75    IByteOut *Out;
76  } Stream;
77 
78  Byte Indx2Units[PPMD_NUM_INDEXES];
79  Byte Units2Indx[128];
80  CPpmd_Void_Ref FreeList[PPMD_NUM_INDEXES];
81  UInt32 Stamps[PPMD_NUM_INDEXES];
82 
83  Byte NS2BSIndx[256], NS2Indx[260];
84  CPpmd_See DummySee, See[24][32];
85  UInt16 BinSumm[25][64];
86} CPpmd8;
87 
88void Ppmd8_Construct(CPpmd8 *p);
89Bool Ppmd8_Alloc(CPpmd8 *p, UInt32 size, ISzAlloc *alloc);
90void Ppmd8_Free(CPpmd8 *p, ISzAlloc *alloc);
91void Ppmd8_Init(CPpmd8 *p, unsigned maxOrder, unsigned restoreMethod);
92#define Ppmd8_WasAllocated(p) ((p)->Base != NULL)
93 
94 
95/* ---------- Internal Functions ---------- */
96 
97extern const Byte PPMD8_kExpEscape[16];
98 
99#ifdef PPMD_32BIT
100  #define Ppmd8_GetPtr(p, ptr) (ptr)
101  #define Ppmd8_GetContext(p, ptr) (ptr)
102  #define Ppmd8_GetStats(p, ctx) ((ctx)->Stats)
103#else
104  #define Ppmd8_GetPtr(p, offs) ((void *)((p)->Base + (offs)))
105  #define Ppmd8_GetContext(p, offs) ((CPpmd8_Context *)Ppmd8_GetPtr((p), (offs)))
106  #define Ppmd8_GetStats(p, ctx) ((CPpmd_State *)Ppmd8_GetPtr((p), ((ctx)->Stats)))
107#endif
108 
109void Ppmd8_Update1(CPpmd8 *p);
110void Ppmd8_Update1_0(CPpmd8 *p);
111void Ppmd8_Update2(CPpmd8 *p);
112void Ppmd8_UpdateBin(CPpmd8 *p);
113 
114#define Ppmd8_GetBinSumm(p) \
115    &p->BinSumm[p->NS2Indx[Ppmd8Context_OneState(p->MinContext)->Freq - 1]][ \
116    p->NS2BSIndx[Ppmd8_GetContext(p, p->MinContext->Suffix)->NumStats] + \
117    p->PrevSuccess + p->MinContext->Flags + ((p->RunLength >> 26) & 0x20)]
118 
119CPpmd_See *Ppmd8_MakeEscFreq(CPpmd8 *p, unsigned numMasked, UInt32 *scale);
120 
121 
122/* ---------- Decode ---------- */
123 
124Bool Ppmd8_RangeDec_Init(CPpmd8 *p);
125#define Ppmd8_RangeDec_IsFinishedOK(p) ((p)->Code == 0)
126int Ppmd8_DecodeSymbol(CPpmd8 *p); /* returns: -1 as EndMarker, -2 as DataError */
127 
128 
129/* ---------- Encode ---------- */
130 
131#define Ppmd8_RangeEnc_Init(p) { (p)->Low = 0; (p)->Range = 0xFFFFFFFF; }
132void Ppmd8_RangeEnc_FlushData(CPpmd8 *p);
133void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol); /* symbol = -1 means EndMarker */
134 
135EXTERN_C_END
136 
137#endif
src/lib/lib7z/7zCrc.h
r0r14440
1/* 7zCrc.h -- CRC32 calculation
22009-11-21 : Igor Pavlov : Public domain */
3 
4#ifndef __7Z_CRC_H
5#define __7Z_CRC_H
6 
7#include "Types.h"
8 
9EXTERN_C_BEGIN
10 
11extern UInt32 g_CrcTable[];
12 
13/* Call CrcGenerateTable one time before other CRC functions */
14void MY_FAST_CALL CrcGenerateTable(void);
15 
16#define CRC_INIT_VAL 0xFFFFFFFF
17#define CRC_GET_DIGEST(crc) ((crc) ^ CRC_INIT_VAL)
18#define CRC_UPDATE_BYTE(crc, b) (g_CrcTable[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
19 
20UInt32 MY_FAST_CALL CrcUpdate(UInt32 crc, const void *data, size_t size);
21UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size);
22 
23EXTERN_C_END
24 
25#endif
src/lib/lib7z/x7zFile.h
r0r14440
1/* 7zFile.h -- File IO
22009-11-24 : Igor Pavlov : Public domain */
3 
4#ifndef __7Z_FILE_H
5#define __7Z_FILE_H
6 
7#ifdef _WIN32_7Z
8#define USE_WINDOWS_FILE
9#endif
10 
11#ifdef USE_WINDOWS_FILE
12#include <windows.h>
13#else
14#include <stdio.h>
15#endif
16 
17#include "Types.h"
18 
19EXTERN_C_BEGIN
20 
21/* ---------- File ---------- */
22 
23typedef struct
24{
25  #ifdef USE_WINDOWS_FILE
26  HANDLE handle;
27  #else
28  FILE *file;
29  #endif
30} CSzFile;
31 
32void File_Construct(CSzFile *p);
33#if !defined(UNDER_CE) || !defined(USE_WINDOWS_FILE)
34WRes InFile_Open(CSzFile *p, const char *name);
35WRes OutFile_Open(CSzFile *p, const char *name);
36#endif
37#ifdef USE_WINDOWS_FILE
38WRes InFile_OpenW(CSzFile *p, const WCHAR *name);
39WRes OutFile_OpenW(CSzFile *p, const WCHAR *name);
40#endif
41WRes File_Close(CSzFile *p);
42 
43/* reads max(*size, remain file's size) bytes */
44WRes File_Read(CSzFile *p, void *data, size_t *size);
45 
46/* writes *size bytes */
47WRes File_Write(CSzFile *p, const void *data, size_t *size);
48 
49WRes File_Seek(CSzFile *p, Int64 *pos, ESzSeek origin);
50WRes File_GetLength(CSzFile *p, UInt64 *length);
51 
52 
53/* ---------- FileInStream ---------- */
54 
55typedef struct
56{
57  ISeqInStream s;
58  CSzFile file;
59} CFileSeqInStream;
60 
61void FileSeqInStream_CreateVTable(CFileSeqInStream *p);
62 
63 
64typedef struct
65{
66  ISeekInStream s;
67  CSzFile file;
68} CFileInStream;
69 
70void FileInStream_CreateVTable(CFileInStream *p);
71 
72 
73typedef struct
74{
75  ISeqOutStream s;
76  CSzFile file;
77} CFileOutStream;
78 
79void FileOutStream_CreateVTable(CFileOutStream *p);
80 
81EXTERN_C_END
82 
83#endif
src/lib/lib7z/Delta.h
r0r14440
1/* Delta.h -- Delta converter
22009-04-15 : Igor Pavlov : Public domain */
3 
4#ifndef __DELTA_H
5#define __DELTA_H
6 
7#include "Types.h"
8 
9#ifdef __cplusplus
10extern "C" {
11#endif
12 
13#define DELTA_STATE_SIZE 256
14 
15void Delta_Init(Byte *state);
16void Delta_Encode(Byte *state, unsigned delta, Byte *data, SizeT size);
17void Delta_Decode(Byte *state, unsigned delta, Byte *data, SizeT size);
18 
19#ifdef __cplusplus
20}
21#endif
22 
23#endif
src/lib/lib7z/LzmaEnc.h
r0r14440
1/*  LzmaEnc.h -- LZMA Encoder
22011-01-27 : Igor Pavlov : Public domain */
3 
4#ifndef __LZMA_ENC_H
5#define __LZMA_ENC_H
6 
7#include "Types.h"
8 
9EXTERN_C_BEGIN
10 
11#define LZMA_PROPS_SIZE 5
12 
13typedef struct _CLzmaEncProps
14{
15  int level;       /*  0 <= level <= 9 */
16  UInt32 dictSize; /* (1 << 12) <= dictSize <= (1 << 27) for 32-bit version
17                      (1 << 12) <= dictSize <= (1 << 30) for 64-bit version
18                       default = (1 << 24) */
19  UInt32 reduceSize; /* estimated size of data that will be compressed. default = 0xFFFFFFFF.
20                        Encoder uses this value to reduce dictionary size */
21  int lc;          /* 0 <= lc <= 8, default = 3 */
22  int lp;          /* 0 <= lp <= 4, default = 0 */
23  int pb;          /* 0 <= pb <= 4, default = 2 */
24  int algo;        /* 0 - fast, 1 - normal, default = 1 */
25  int fb;          /* 5 <= fb <= 273, default = 32 */
26  int btMode;      /* 0 - hashChain Mode, 1 - binTree mode - normal, default = 1 */
27  int numHashBytes; /* 2, 3 or 4, default = 4 */
28  UInt32 mc;        /* 1 <= mc <= (1 << 30), default = 32 */
29  unsigned writeEndMark;  /* 0 - do not write EOPM, 1 - write EOPM, default = 0 */
30  int numThreads;  /* 1 or 2, default = 2 */
31} CLzmaEncProps;
32 
33void LzmaEncProps_Init(CLzmaEncProps *p);
34void LzmaEncProps_Normalize(CLzmaEncProps *p);
35UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2);
36 
37 
38/* ---------- CLzmaEncHandle Interface ---------- */
39 
40/* LzmaEnc_* functions can return the following exit codes:
41Returns:
42  SZ_OK           - OK
43  SZ_ERROR_MEM    - Memory allocation error
44  SZ_ERROR_PARAM  - Incorrect paramater in props
45  SZ_ERROR_WRITE  - Write callback error.
46  SZ_ERROR_PROGRESS - some break from progress callback
47  SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version)
48*/
49 
50typedef void * CLzmaEncHandle;
51 
52CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc);
53void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig);
54SRes LzmaEnc_SetProps(CLzmaEncHandle p, const CLzmaEncProps *props);
55SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *properties, SizeT *size);
56SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream,
57    ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
58SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
59    int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
60 
61/* ---------- One Call Interface ---------- */
62 
63/* LzmaEncode
64Return code:
65  SZ_OK               - OK
66  SZ_ERROR_MEM        - Memory allocation error
67  SZ_ERROR_PARAM      - Incorrect paramater
68  SZ_ERROR_OUTPUT_EOF - output buffer overflow
69  SZ_ERROR_THREAD     - errors in multithreading functions (only for Mt version)
70*/
71 
72SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
73    const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
74    ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
75 
76EXTERN_C_END
77 
78#endif
src/lib/lib7z/Xz.c
r0r14440
1/* Xz.c - Xz
22009-04-15 : Igor Pavlov : Public domain */
3 
4#include "7zCrc.h"
5#include "CpuArch.h"
6#include "Xz.h"
7#include "XzCrc64.h"
8 
9Byte XZ_SIG[XZ_SIG_SIZE] = { 0xFD, '7', 'z', 'X', 'Z', 0 };
10Byte XZ_FOOTER_SIG[XZ_FOOTER_SIG_SIZE] = { 'Y', 'Z' };
11 
12unsigned Xz_WriteVarInt(Byte *buf, UInt64 v)
13{
14  unsigned i = 0;
15  do
16  {
17    buf[i++] = (Byte)((v & 0x7F) | 0x80);
18    v >>= 7;
19  }
20  while (v != 0);
21  buf[i - 1] &= 0x7F;
22  return i;
23}
24 
25void Xz_Construct(CXzStream *p)
26{
27  p->numBlocks = p->numBlocksAllocated = 0;
28  p->blocks = 0;
29  p->flags = 0;
30}
31 
32void Xz_Free(CXzStream *p, ISzAlloc *alloc)
33{
34  alloc->Free(alloc, p->blocks);
35  p->numBlocks = p->numBlocksAllocated = 0;
36  p->blocks = 0;
37}
38 
39unsigned XzFlags_GetCheckSize(CXzStreamFlags f)
40{
41  int t = XzFlags_GetCheckType(f);
42  return (t == 0) ? 0 : (4 << ((t - 1) / 3));
43}
44 
45void XzCheck_Init(CXzCheck *p, int mode)
46{
47  p->mode = mode;
48  switch (mode)
49  {
50    case XZ_CHECK_CRC32: p->crc = CRC_INIT_VAL; break;
51    case XZ_CHECK_CRC64: p->crc64 = CRC64_INIT_VAL; break;
52    case XZ_CHECK_SHA256: Sha256_Init(&p->sha); break;
53  }
54}
55 
56void XzCheck_Update(CXzCheck *p, const void *data, size_t size)
57{
58  switch (p->mode)
59  {
60    case XZ_CHECK_CRC32: p->crc = CrcUpdate(p->crc, data, size); break;
61    case XZ_CHECK_CRC64: p->crc64 = Crc64Update(p->crc64, data, size); break;
62    case XZ_CHECK_SHA256: Sha256_Update(&p->sha, (const Byte *)data, size); break;
63  }
64}
65 
66int XzCheck_Final(CXzCheck *p, Byte *digest)
67{
68  switch (p->mode)
69  {
70    case XZ_CHECK_CRC32:
71      SetUi32(digest, CRC_GET_DIGEST(p->crc));
72      break;
73    case XZ_CHECK_CRC64:
74    {
75      int i;
76      UInt64 v = CRC64_GET_DIGEST(p->crc64);
77      for (i = 0; i < 8; i++, v >>= 8)
78        digest[i] = (Byte)(v & 0xFF);
79      break;
80    }
81    case XZ_CHECK_SHA256:
82      Sha256_Final(&p->sha, digest);
83      break;
84    default:
85      return 0;
86  }
87  return 1;
88}
src/lib/lib7z/Lzma2Dec.c
r0r14440
1/* Lzma2Dec.c -- LZMA2 Decoder
22010-12-15 : Igor Pavlov : Public domain */
3 
4/* #define SHOW_DEBUG_INFO */
5 
6#ifdef SHOW_DEBUG_INFO
7#include <stdio.h>
8#endif
9 
10#include <string.h>
11 
12#include "Lzma2Dec.h"
13 
14/*
1500000000  -  EOS
1600000001 U U  -  Uncompressed Reset Dic
1700000010 U U  -  Uncompressed No Reset
18100uuuuu U U P P  -  LZMA no reset
19101uuuuu U U P P  -  LZMA reset state
20110uuuuu U U P P S  -  LZMA reset state + new prop
21111uuuuu U U P P S  -  LZMA reset state + new prop + reset dic
22 
23  u, U - Unpack Size
24  P - Pack Size
25  S - Props
26*/
27 
28#define LZMA2_CONTROL_LZMA (1 << 7)
29#define LZMA2_CONTROL_COPY_NO_RESET 2
30#define LZMA2_CONTROL_COPY_RESET_DIC 1
31#define LZMA2_CONTROL_EOF 0
32 
33#define LZMA2_IS_UNCOMPRESSED_STATE(p) (((p)->control & LZMA2_CONTROL_LZMA) == 0)
34 
35#define LZMA2_GET_LZMA_MODE(p) (((p)->control >> 5) & 3)
36#define LZMA2_IS_THERE_PROP(mode) ((mode) >= 2)
37 
38#define LZMA2_LCLP_MAX 4
39#define LZMA2_DIC_SIZE_FROM_PROP(p) (((UInt32)2 | ((p) & 1)) << ((p) / 2 + 11))
40 
41#ifdef SHOW_DEBUG_INFO
42#define PRF(x) x
43#else
44#define PRF(x)
45#endif
46 
47typedef enum
48{
49  LZMA2_STATE_CONTROL,
50  LZMA2_STATE_UNPACK0,
51  LZMA2_STATE_UNPACK1,
52  LZMA2_STATE_PACK0,
53  LZMA2_STATE_PACK1,
54  LZMA2_STATE_PROP,
55  LZMA2_STATE_DATA,
56  LZMA2_STATE_DATA_CONT,
57  LZMA2_STATE_FINISHED,
58  LZMA2_STATE_ERROR
59} ELzma2State;
60 
61static SRes Lzma2Dec_GetOldProps(Byte prop, Byte *props)
62{
63  UInt32 dicSize;
64  if (prop > 40)
65    return SZ_ERROR_UNSUPPORTED;
66  dicSize = (prop == 40) ? 0xFFFFFFFF : LZMA2_DIC_SIZE_FROM_PROP(prop);
67  props[0] = (Byte)LZMA2_LCLP_MAX;
68  props[1] = (Byte)(dicSize);
69  props[2] = (Byte)(dicSize >> 8);
70  props[3] = (Byte)(dicSize >> 16);
71  props[4] = (Byte)(dicSize >> 24);
72  return SZ_OK;
73}
74 
75SRes Lzma2Dec_AllocateProbs(CLzma2Dec *p, Byte prop, ISzAlloc *alloc)
76{
77  Byte props[LZMA_PROPS_SIZE];
78  RINOK(Lzma2Dec_GetOldProps(prop, props));
79  return LzmaDec_AllocateProbs(&p->decoder, props, LZMA_PROPS_SIZE, alloc);
80}
81 
82SRes Lzma2Dec_Allocate(CLzma2Dec *p, Byte prop, ISzAlloc *alloc)
83{
84  Byte props[LZMA_PROPS_SIZE];
85  RINOK(Lzma2Dec_GetOldProps(prop, props));
86  return LzmaDec_Allocate(&p->decoder, props, LZMA_PROPS_SIZE, alloc);
87}
88 
89void Lzma2Dec_Init(CLzma2Dec *p)
90{
91  p->state = LZMA2_STATE_CONTROL;
92  p->needInitDic = True;
93  p->needInitState = True;
94  p->needInitProp = True;
95  LzmaDec_Init(&p->decoder);
96}
97 
98static ELzma2State Lzma2Dec_UpdateState(CLzma2Dec *p, Byte b)
99{
100  switch(p->state)
101  {
102    case LZMA2_STATE_CONTROL:
103      p->control = b;
104      PRF(printf("\n %4X ", p->decoder.dicPos));
105      PRF(printf(" %2X", b));
106      if (p->control == 0)
107        return LZMA2_STATE_FINISHED;
108      if (LZMA2_IS_UNCOMPRESSED_STATE(p))
109      {
110        if ((p->control & 0x7F) > 2)
111          return LZMA2_STATE_ERROR;
112        p->unpackSize = 0;
113      }
114      else
115        p->unpackSize = (UInt32)(p->control & 0x1F) << 16;
116      return LZMA2_STATE_UNPACK0;
117     
118    case LZMA2_STATE_UNPACK0:
119      p->unpackSize |= (UInt32)b << 8;
120      return LZMA2_STATE_UNPACK1;
121     
122    case LZMA2_STATE_UNPACK1:
123      p->unpackSize |= (UInt32)b;
124      p->unpackSize++;
125      PRF(printf(" %8d", p->unpackSize));
126      return (LZMA2_IS_UNCOMPRESSED_STATE(p)) ? LZMA2_STATE_DATA : LZMA2_STATE_PACK0;
127     
128    case LZMA2_STATE_PACK0:
129      p->packSize = (UInt32)b << 8;
130      return LZMA2_STATE_PACK1;
131 
132    case LZMA2_STATE_PACK1:
133      p->packSize |= (UInt32)b;
134      p->packSize++;
135      PRF(printf(" %8d", p->packSize));
136      return LZMA2_IS_THERE_PROP(LZMA2_GET_LZMA_MODE(p)) ? LZMA2_STATE_PROP:
137        (p->needInitProp ? LZMA2_STATE_ERROR : LZMA2_STATE_DATA);
138 
139    case LZMA2_STATE_PROP:
140    {
141      int lc, lp;
142      if (b >= (9 * 5 * 5))
143        return LZMA2_STATE_ERROR;
144      lc = b % 9;
145      b /= 9;
146      p->decoder.prop.pb = b / 5;
147      lp = b % 5;
148      if (lc + lp > LZMA2_LCLP_MAX)
149        return LZMA2_STATE_ERROR;
150      p->decoder.prop.lc = lc;
151      p->decoder.prop.lp = lp;
152      p->needInitProp = False;
153      return LZMA2_STATE_DATA;
154    }
155  }
156  return LZMA2_STATE_ERROR;
157}
158 
159static void LzmaDec_UpdateWithUncompressed(CLzmaDec *p, const Byte *src, SizeT size)
160{
161  memcpy(p->dic + p->dicPos, src, size);
162  p->dicPos += size;
163  if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= size)
164    p->checkDicSize = p->prop.dicSize;
165  p->processedPos += (UInt32)size;
166}
167 
168void LzmaDec_InitDicAndState(CLzmaDec *p, Bool initDic, Bool initState);
169 
170SRes Lzma2Dec_DecodeToDic(CLzma2Dec *p, SizeT dicLimit,
171    const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status)
172{
173  SizeT inSize = *srcLen;
174  *srcLen = 0;
175  *status = LZMA_STATUS_NOT_SPECIFIED;
176 
177  while (p->state != LZMA2_STATE_FINISHED)
178  {
179    SizeT dicPos = p->decoder.dicPos;
180    if (p->state == LZMA2_STATE_ERROR)
181      return SZ_ERROR_DATA;
182    if (dicPos == dicLimit && finishMode == LZMA_FINISH_ANY)
183    {
184      *status = LZMA_STATUS_NOT_FINISHED;
185      return SZ_OK;
186    }
187    if (p->state != LZMA2_STATE_DATA && p->state != LZMA2_STATE_DATA_CONT)
188    {
189      if (*srcLen == inSize)
190      {
191        *status = LZMA_STATUS_NEEDS_MORE_INPUT;
192        return SZ_OK;
193      }
194      (*srcLen)++;
195      p->state = Lzma2Dec_UpdateState(p, *src++);
196      continue;
197    }
198    {
199      SizeT destSizeCur = dicLimit - dicPos;
200      SizeT srcSizeCur = inSize - *srcLen;
201      ELzmaFinishMode curFinishMode = LZMA_FINISH_ANY;
202       
203      if (p->unpackSize <= destSizeCur)
204      {
205        destSizeCur = (SizeT)p->unpackSize;
206        curFinishMode = LZMA_FINISH_END;
207      }
208 
209      if (LZMA2_IS_UNCOMPRESSED_STATE(p))
210      {
211        if (*srcLen == inSize)
212        {
213          *status = LZMA_STATUS_NEEDS_MORE_INPUT;
214          return SZ_OK;
215        }
216 
217        if (p->state == LZMA2_STATE_DATA)
218        {
219          Bool initDic = (p->control == LZMA2_CONTROL_COPY_RESET_DIC);
220          if (initDic)
221            p->needInitProp = p->needInitState = True;
222          else if (p->needInitDic)
223            return SZ_ERROR_DATA;
224          p->needInitDic = False;
225          LzmaDec_InitDicAndState(&p->decoder, initDic, False);
226        }
227 
228        if (srcSizeCur > destSizeCur)
229          srcSizeCur = destSizeCur;
230 
231        if (srcSizeCur == 0)
232          return SZ_ERROR_DATA;
233 
234        LzmaDec_UpdateWithUncompressed(&p->decoder, src, srcSizeCur);
235 
236        src += srcSizeCur;
237        *srcLen += srcSizeCur;
238        p->unpackSize -= (UInt32)srcSizeCur;
239        p->state = (p->unpackSize == 0) ? LZMA2_STATE_CONTROL : LZMA2_STATE_DATA_CONT;
240      }
241      else
242      {
243        SizeT outSizeProcessed;
244        SRes res;
245 
246        if (p->state == LZMA2_STATE_DATA)
247        {
248          int mode = LZMA2_GET_LZMA_MODE(p);
249          Bool initDic = (mode == 3);
250          Bool initState = (mode > 0);
251          if ((!initDic && p->needInitDic) || (!initState && p->needInitState))
252            return SZ_ERROR_DATA;
253           
254          LzmaDec_InitDicAndState(&p->decoder, initDic, initState);
255          p->needInitDic = False;
256          p->needInitState = False;
257          p->state = LZMA2_STATE_DATA_CONT;
258        }
259        if (srcSizeCur > p->packSize)
260          srcSizeCur = (SizeT)p->packSize;
261           
262        res = LzmaDec_DecodeToDic(&p->decoder, dicPos + destSizeCur, src, &srcSizeCur, curFinishMode, status);
263         
264        src += srcSizeCur;
265        *srcLen += srcSizeCur;
266        p->packSize -= (UInt32)srcSizeCur;
267 
268        outSizeProcessed = p->decoder.dicPos - dicPos;
269        p->unpackSize -= (UInt32)outSizeProcessed;
270 
271        RINOK(res);
272        if (*status == LZMA_STATUS_NEEDS_MORE_INPUT)
273          return res;
274 
275        if (srcSizeCur == 0 && outSizeProcessed == 0)
276        {
277          if (*status != LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK ||
278              p->unpackSize != 0 || p->packSize != 0)
279            return SZ_ERROR_DATA;
280          p->state = LZMA2_STATE_CONTROL;
281        }
282        if (*status == LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK)
283          *status = LZMA_STATUS_NOT_FINISHED;
284      }
285    }
286  }
287  *status = LZMA_STATUS_FINISHED_WITH_MARK;
288  return SZ_OK;
289}
290 
291SRes Lzma2Dec_DecodeToBuf(CLzma2Dec *p, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status)
292{
293  SizeT outSize = *destLen, inSize = *srcLen;
294  *srcLen = *destLen = 0;
295  for (;;)
296  {
297    SizeT srcSizeCur = inSize, outSizeCur, dicPos;
298    ELzmaFinishMode curFinishMode;
299    SRes res;
300    if (p->decoder.dicPos == p->decoder.dicBufSize)
301      p->decoder.dicPos = 0;
302    dicPos = p->decoder.dicPos;
303    if (outSize > p->decoder.dicBufSize - dicPos)
304    {
305      outSizeCur = p->decoder.dicBufSize;
306      curFinishMode = LZMA_FINISH_ANY;
307    }
308    else
309    {
310      outSizeCur = dicPos + outSize;
311      curFinishMode = finishMode;
312    }
313 
314    res = Lzma2Dec_DecodeToDic(p, outSizeCur, src, &srcSizeCur, curFinishMode, status);
315    src += srcSizeCur;
316    inSize -= srcSizeCur;
317    *srcLen += srcSizeCur;
318    outSizeCur = p->decoder.dicPos - dicPos;
319    memcpy(dest, p->decoder.dic + dicPos, outSizeCur);
320    dest += outSizeCur;
321    outSize -= outSizeCur;
322    *destLen += outSizeCur;
323    if (res != 0)
324      return res;
325    if (outSizeCur == 0 || outSize == 0)
326      return SZ_OK;
327  }
328}
329 
330SRes Lzma2Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
331    Byte prop, ELzmaFinishMode finishMode, ELzmaStatus *status, ISzAlloc *alloc)
332{
333  CLzma2Dec p;
334  SRes res;
335  SizeT outSize = *destLen, inSize = *srcLen;
336  *destLen = *srcLen = 0;
337  *status = LZMA_STATUS_NOT_SPECIFIED;
338  Lzma2Dec_Construct(&p);
339  RINOK(Lzma2Dec_AllocateProbs(&p, prop, alloc));
340  p.decoder.dic = dest;
341  p.decoder.dicBufSize = outSize;
342  Lzma2Dec_Init(&p);
343  *srcLen = inSize;
344  res = Lzma2Dec_DecodeToDic(&p, outSize, src, srcLen, finishMode, status);
345  *destLen = p.decoder.dicPos;
346  if (res == SZ_OK && *status == LZMA_STATUS_NEEDS_MORE_INPUT)
347    res = SZ_ERROR_INPUT_EOF;
348  Lzma2Dec_FreeProbs(&p, alloc);
349  return res;
350}
src/lib/lib7z/XzCrc64.c
r0r14440
1/* XzCrc64.c -- CRC64 calculation
22010-04-16 : Igor Pavlov : Public domain */
3 
4#include "XzCrc64.h"
5 
6#define kCrc64Poly UINT64_CONST(0xC96C5795D7870F42)
7UInt64 g_Crc64Table[256];
8 
9void MY_FAST_CALL Crc64GenerateTable(void)
10{
11  UInt32 i;
12  for (i = 0; i < 256; i++)
13  {
14    UInt64 r = i;
15    int j;
16    for (j = 0; j < 8; j++)
17      r = (r >> 1) ^ ((UInt64)kCrc64Poly & ~((r & 1) - 1));
18    g_Crc64Table[i] = r;
19  }
20}
21 
22UInt64 MY_FAST_CALL Crc64Update(UInt64 v, const void *data, size_t size)
23{
24  const Byte *p = (const Byte *)data;
25  for (; size > 0 ; size--, p++)
26    v = CRC64_UPDATE_BYTE(v, *p);
27  return v;
28}
29 
30UInt64 MY_FAST_CALL Crc64Calc(const void *data, size_t size)
31{
32  return CRC64_GET_DIGEST(Crc64Update(CRC64_INIT_VAL, data, size));
33}
src/lib/lib7z/Ppmd8Dec.c
r0r14440
1/* Ppmd8Dec.c -- PPMdI Decoder
22010-04-16 : Igor Pavlov : Public domain
3This code is based on:
4  PPMd var.I (2002): Dmitry Shkarin : Public domain
5  Carryless rangecoder (1999): Dmitry Subbotin : Public domain */
6 
7#include "Ppmd8.h"
8 
9#define kTop (1 << 24)
10#define kBot (1 << 15)
11 
12Bool Ppmd8_RangeDec_Init(CPpmd8 *p)
13{
14  unsigned i;
15  p->Low = 0;
16  p->Range = 0xFFFFFFFF;
17  p->Code = 0;
18  for (i = 0; i < 4; i++)
19    p->Code = (p->Code << 8) | p->Stream.In->Read(p->Stream.In);
20  return (p->Code < 0xFFFFFFFF);
21}
22 
23static UInt32 RangeDec_GetThreshold(CPpmd8 *p, UInt32 total)
24{
25  return p->Code / (p->Range /= total);
26}
27 
28static void RangeDec_Decode(CPpmd8 *p, UInt32 start, UInt32 size)
29{
30  start *= p->Range;
31  p->Low += start;
32  p->Code -= start;
33  p->Range *= size;
34 
35  while ((p->Low ^ (p->Low + p->Range)) < kTop ||
36      (p->Range < kBot && ((p->Range = (0 - p->Low) & (kBot - 1)), 1)))
37  {
38    p->Code = (p->Code << 8) | p->Stream.In->Read(p->Stream.In);
39    p->Range <<= 8;
40    p->Low <<= 8;
41  }
42}
43 
44#define MASK(sym) ((signed char *)charMask)[sym]
45 
46int Ppmd8_DecodeSymbol(CPpmd8 *p)
47{
48  size_t charMask[256 / sizeof(size_t)];
49  if (p->MinContext->NumStats != 0)
50  {
51    CPpmd_State *s = Ppmd8_GetStats(p, p->MinContext);
52    unsigned i;
53    UInt32 count, hiCnt;
54    if ((count = RangeDec_GetThreshold(p, p->MinContext->SummFreq)) < (hiCnt = s->Freq))
55    {
56      Byte symbol;
57      RangeDec_Decode(p, 0, s->Freq);
58      p->FoundState = s;
59      symbol = s->Symbol;
60      Ppmd8_Update1_0(p);
61      return symbol;
62    }
63    p->PrevSuccess = 0;
64    i = p->MinContext->NumStats;
65    do
66    {
67      if ((hiCnt += (++s)->Freq) > count)
68      {
69        Byte symbol;
70        RangeDec_Decode(p, hiCnt - s->Freq, s->Freq);
71        p->FoundState = s;
72        symbol = s->Symbol;
73        Ppmd8_Update1(p);
74        return symbol;
75      }
76    }
77    while (--i);
78    if (count >= p->MinContext->SummFreq)
79      return -2;
80    RangeDec_Decode(p, hiCnt, p->MinContext->SummFreq - hiCnt);
81    PPMD_SetAllBitsIn256Bytes(charMask);
82    MASK(s->Symbol) = 0;
83    i = p->MinContext->NumStats;
84    do { MASK((--s)->Symbol) = 0; } while (--i);
85  }
86  else
87  {
88    UInt16 *prob = Ppmd8_GetBinSumm(p);
89    if (((p->Code / (p->Range >>= 14)) < *prob))
90    {
91      Byte symbol;
92      RangeDec_Decode(p, 0, *prob);
93      *prob = (UInt16)PPMD_UPDATE_PROB_0(*prob);
94      symbol = (p->FoundState = Ppmd8Context_OneState(p->MinContext))->Symbol;
95      Ppmd8_UpdateBin(p);
96      return symbol;
97    }
98    RangeDec_Decode(p, *prob, (1 << 14) - *prob);
99    *prob = (UInt16)PPMD_UPDATE_PROB_1(*prob);
100    p->InitEsc = PPMD8_kExpEscape[*prob >> 10];
101    PPMD_SetAllBitsIn256Bytes(charMask);
102    MASK(Ppmd8Context_OneState(p->MinContext)->Symbol) = 0;
103    p->PrevSuccess = 0;
104  }
105  for (;;)
106  {
107    CPpmd_State *ps[256], *s;
108    UInt32 freqSum, count, hiCnt;
109    CPpmd_See *see;
110    unsigned i, num, numMasked = p->MinContext->NumStats;
111    do
112    {
113      p->OrderFall++;
114      if (!p->MinContext->Suffix)
115        return -1;
116      p->MinContext = Ppmd8_GetContext(p, p->MinContext->Suffix);
117    }
118    while (p->MinContext->NumStats == numMasked);
119    hiCnt = 0;
120    s = Ppmd8_GetStats(p, p->MinContext);
121    i = 0;
122    num = p->MinContext->NumStats - numMasked;
123    do
124    {
125      int k = (int)(MASK(s->Symbol));
126      hiCnt += (s->Freq & k);
127      ps[i] = s++;
128      i -= k;
129    }
130    while (i != num);
131     
132    see = Ppmd8_MakeEscFreq(p, numMasked, &freqSum);
133    freqSum += hiCnt;
134    count = RangeDec_GetThreshold(p, freqSum);
135     
136    if (count < hiCnt)
137    {
138      Byte symbol;
139      CPpmd_State **pps = ps;
140      for (hiCnt = 0; (hiCnt += (*pps)->Freq) <= count; pps++);
141      s = *pps;
142      RangeDec_Decode(p, hiCnt - s->Freq, s->Freq);
143      Ppmd_See_Update(see);
144      p->FoundState = s;
145      symbol = s->Symbol;
146      Ppmd8_Update2(p);
147      return symbol;
148    }
149    if (count >= freqSum)
150      return -2;
151    RangeDec_Decode(p, hiCnt, freqSum - hiCnt);
152    see->Summ = (UInt16)(see->Summ + freqSum);
153    do { MASK(ps[--i]->Symbol) = 0; } while (i != 0);
154  }
155}
src/lib/lib7z/7z.h
r0r14440
1/* 7z.h -- 7z interface
22010-03-11 : Igor Pavlov : Public domain */
3 
4#ifndef __7Z_H
5#define __7Z_H
6 
7#include "7zBuf.h"
8 
9EXTERN_C_BEGIN
10 
11#define k7zStartHeaderSize 0x20
12#define k7zSignatureSize 6
13extern Byte k7zSignature[k7zSignatureSize];
14#define k7zMajorVersion 0
15 
16enum EIdEnum
17{
18  k7zIdEnd,
19  k7zIdHeader,
20  k7zIdArchiveProperties,
21  k7zIdAdditionalStreamsInfo,
22  k7zIdMainStreamsInfo,
23  k7zIdFilesInfo,
24  k7zIdPackInfo,
25  k7zIdUnpackInfo,
26  k7zIdSubStreamsInfo,
27  k7zIdSize,
28  k7zIdCRC,
29  k7zIdFolder,
30  k7zIdCodersUnpackSize,
31  k7zIdNumUnpackStream,
32  k7zIdEmptyStream,
33  k7zIdEmptyFile,
34  k7zIdAnti,
35  k7zIdName,
36  k7zIdCTime,
37  k7zIdATime,
38  k7zIdMTime,
39  k7zIdWinAttributes,
40  k7zIdComment,
41  k7zIdEncodedHeader,
42  k7zIdStartPos,
43  k7zIdDummy
44};
45 
46typedef struct
47{
48  UInt32 NumInStreams;
49  UInt32 NumOutStreams;
50  UInt64 MethodID;
51  CBuf Props;
52} CSzCoderInfo;
53 
54void SzCoderInfo_Init(CSzCoderInfo *p);
55void SzCoderInfo_Free(CSzCoderInfo *p, ISzAlloc *alloc);
56 
57typedef struct
58{
59  UInt32 InIndex;
60  UInt32 OutIndex;
61} CSzBindPair;
62 
63typedef struct
64{
65  CSzCoderInfo *Coders;
66  CSzBindPair *BindPairs;
67  UInt32 *PackStreams;
68  UInt64 *UnpackSizes;
69  UInt32 NumCoders;
70  UInt32 NumBindPairs;
71  UInt32 NumPackStreams;
72  int UnpackCRCDefined;
73  UInt32 UnpackCRC;
74 
75  UInt32 NumUnpackStreams;
76} CSzFolder;
77 
78void SzFolder_Init(CSzFolder *p);
79UInt64 SzFolder_GetUnpackSize(CSzFolder *p);
80int SzFolder_FindBindPairForInStream(CSzFolder *p, UInt32 inStreamIndex);
81UInt32 SzFolder_GetNumOutStreams(CSzFolder *p);
82UInt64 SzFolder_GetUnpackSize(CSzFolder *p);
83 
84SRes SzFolder_Decode(const CSzFolder *folder, const UInt64 *packSizes,
85    ILookInStream *stream, UInt64 startPos,
86    Byte *outBuffer, size_t outSize, ISzAlloc *allocMain);
87 
88typedef struct
89{
90  UInt32 Low;
91  UInt32 High;
92} CNtfsFileTime;
93 
94typedef struct
95{
96  CNtfsFileTime MTime;
97  UInt64 Size;
98  UInt32 Crc;
99  UInt32 Attrib;
100  Byte HasStream;
101  Byte IsDir;
102  Byte IsAnti;
103  Byte CrcDefined;
104  Byte MTimeDefined;
105  Byte AttribDefined;
106} CSzFileItem;
107 
108void SzFile_Init(CSzFileItem *p);
109 
110typedef struct
111{
112  UInt64 *PackSizes;
113  Byte *PackCRCsDefined;
114  UInt32 *PackCRCs;
115  CSzFolder *Folders;
116  CSzFileItem *Files;
117  UInt32 NumPackStreams;
118  UInt32 NumFolders;
119  UInt32 NumFiles;
120} CSzAr;
121 
122void SzAr_Init(CSzAr *p);
123void SzAr_Free(CSzAr *p, ISzAlloc *alloc);
124 
125 
126/*
127  SzExtract extracts file from archive
128 
129  *outBuffer must be 0 before first call for each new archive.
130 
131  Extracting cache:
132    If you need to decompress more than one file, you can send
133    these values from previous call:
134      *blockIndex,
135      *outBuffer,
136      *outBufferSize
137    You can consider "*outBuffer" as cache of solid block. If your archive is solid,
138    it will increase decompression speed.
139   
140    If you use external function, you can declare these 3 cache variables
141    (blockIndex, outBuffer, outBufferSize) as static in that external function.
142     
143    Free *outBuffer and set *outBuffer to 0, if you want to flush cache.
144*/
145 
146typedef struct
147{
148  CSzAr db;
149   
150  UInt64 startPosAfterHeader;
151  UInt64 dataPos;
152 
153  UInt32 *FolderStartPackStreamIndex;
154  UInt64 *PackStreamStartPositions;
155  UInt32 *FolderStartFileIndex;
156  UInt32 *FileIndexToFolderIndexMap;
157 
158  size_t *FileNameOffsets; /* in 2-byte steps */
159  CBuf FileNames;  /* UTF-16-LE */
160} CSzArEx;
161 
162void SzArEx_Init(CSzArEx *p);
163void SzArEx_Free(CSzArEx *p, ISzAlloc *alloc);
164UInt64 SzArEx_GetFolderStreamPos(const CSzArEx *p, UInt32 folderIndex, UInt32 indexInFolder);
165int SzArEx_GetFolderFullPackSize(const CSzArEx *p, UInt32 folderIndex, UInt64 *resSize);
166 
167/*
168if dest == NULL, the return value specifies the required size of the buffer,
169  in 16-bit characters, including the null-terminating character.
170if dest != NULL, the return value specifies the number of 16-bit characters that
171  are written to the dest, including the null-terminating character. */
172 
173size_t SzArEx_GetFileNameUtf16(const CSzArEx *p, size_t fileIndex, UInt16 *dest);
174 
175SRes SzArEx_Extract(
176    const CSzArEx *db,
177    ILookInStream *inStream,
178    UInt32 fileIndex,         /* index of file */
179    UInt32 *blockIndex,       /* index of solid block */
180    Byte **outBuffer,         /* pointer to pointer to output buffer (allocated with allocMain) */
181    size_t *outBufferSize,    /* buffer size for output buffer */
182    size_t *offset,           /* offset of stream for required file in *outBuffer */
183    size_t *outSizeProcessed, /* size of file in *outBuffer */
184    ISzAlloc *allocMain,
185    ISzAlloc *allocTemp);
186 
187 
188/*
189SzArEx_Open Errors:
190SZ_ERROR_NO_ARCHIVE
191SZ_ERROR_ARCHIVE
192SZ_ERROR_UNSUPPORTED
193SZ_ERROR_MEM
194SZ_ERROR_CRC
195SZ_ERROR_INPUT_EOF
196SZ_ERROR_FAIL
197*/
198 
199SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream, ISzAlloc *allocMain, ISzAlloc *allocTemp);
200 
201EXTERN_C_END
202 
203#endif
src/lib/lib7z/Xz.h
r0r14440
1/* Xz.h - Xz interface
22011-01-09 : Igor Pavlov : Public domain */
3 
4#ifndef __XZ_H
5#define __XZ_H
6 
7#include "Sha256.h"
8 
9EXTERN_C_BEGIN
10 
11#define XZ_ID_Subblock 1
12#define XZ_ID_Delta 3
13#define XZ_ID_X86 4
14#define XZ_ID_PPC 5
15#define XZ_ID_IA64 6
16#define XZ_ID_ARM 7
17#define XZ_ID_ARMT 8
18#define XZ_ID_SPARC 9
19#define XZ_ID_LZMA2 0x21
20 
21unsigned Xz_ReadVarInt(const Byte *p, size_t maxSize, UInt64 *value);
22unsigned Xz_WriteVarInt(Byte *buf, UInt64 v);
23 
24/* ---------- xz block ---------- */
25 
26#define XZ_BLOCK_HEADER_SIZE_MAX 1024
27 
28#define XZ_NUM_FILTERS_MAX 4
29#define XZ_BF_NUM_FILTERS_MASK 3
30#define XZ_BF_PACK_SIZE (1 << 6)
31#define XZ_BF_UNPACK_SIZE (1 << 7)
32 
33#define XZ_FILTER_PROPS_SIZE_MAX 20
34 
35typedef struct
36{
37  UInt64 id;
38  UInt32 propsSize;
39  Byte props[XZ_FILTER_PROPS_SIZE_MAX];
40} CXzFilter;
41 
42typedef struct
43{
44  UInt64 packSize;
45  UInt64 unpackSize;
46  Byte flags;
47  CXzFilter filters[XZ_NUM_FILTERS_MAX];
48} CXzBlock;
49 
50#define XzBlock_GetNumFilters(p) (((p)->flags & XZ_BF_NUM_FILTERS_MASK) + 1)
51#define XzBlock_HasPackSize(p)   (((p)->flags & XZ_BF_PACK_SIZE) != 0)
52#define XzBlock_HasUnpackSize(p) (((p)->flags & XZ_BF_UNPACK_SIZE) != 0)
53 
54SRes XzBlock_Parse(CXzBlock *p, const Byte *header);
55SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, Bool *isIndex, UInt32 *headerSizeRes);
56 
57/* ---------- xz stream ---------- */
58 
59#define XZ_SIG_SIZE 6
60#define XZ_FOOTER_SIG_SIZE 2
61 
62extern Byte XZ_SIG[XZ_SIG_SIZE];
63extern Byte XZ_FOOTER_SIG[XZ_FOOTER_SIG_SIZE];
64 
65#define XZ_STREAM_FLAGS_SIZE 2
66#define XZ_STREAM_CRC_SIZE 4
67 
68#define XZ_STREAM_HEADER_SIZE (XZ_SIG_SIZE + XZ_STREAM_FLAGS_SIZE + XZ_STREAM_CRC_SIZE)
69#define XZ_STREAM_FOOTER_SIZE (XZ_FOOTER_SIG_SIZE + XZ_STREAM_FLAGS_SIZE + XZ_STREAM_CRC_SIZE + 4)
70 
71#define XZ_CHECK_MASK 0xF
72#define XZ_CHECK_NO 0
73#define XZ_CHECK_CRC32 1
74#define XZ_CHECK_CRC64 4
75#define XZ_CHECK_SHA256 10
76 
77typedef struct
78{
79  int mode;
80  UInt32 crc;
81  UInt64 crc64;
82  CSha256 sha;
83} CXzCheck;
84 
85void XzCheck_Init(CXzCheck *p, int mode);
86void XzCheck_Update(CXzCheck *p, const void *data, size_t size);
87int XzCheck_Final(CXzCheck *p, Byte *digest);
88 
89typedef UInt16 CXzStreamFlags;
90 
91#define XzFlags_IsSupported(f) ((f) <= XZ_CHECK_MASK)
92#define XzFlags_GetCheckType(f) ((f) & XZ_CHECK_MASK)
93#define XzFlags_HasDataCrc32(f) (Xz_GetCheckType(f) == XZ_CHECK_CRC32)
94unsigned XzFlags_GetCheckSize(CXzStreamFlags f);
95 
96SRes Xz_ParseHeader(CXzStreamFlags *p, const Byte *buf);
97SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream);
98 
99typedef struct
100{
101  UInt64 unpackSize;
102  UInt64 totalSize;
103} CXzBlockSizes;
104 
105typedef struct
106{
107  CXzStreamFlags flags;
108  size_t numBlocks;
109  size_t numBlocksAllocated;
110  CXzBlockSizes *blocks;
111  UInt64 startOffset;
112} CXzStream;
113 
114void Xz_Construct(CXzStream *p);
115void Xz_Free(CXzStream *p, ISzAlloc *alloc);
116 
117#define XZ_SIZE_OVERFLOW ((UInt64)(Int64)-1)
118 
119UInt64 Xz_GetUnpackSize(const CXzStream *p);
120UInt64 Xz_GetPackSize(const CXzStream *p);
121 
122typedef struct
123{
124  size_t num;
125  size_t numAllocated;
126  CXzStream *streams;
127} CXzs;
128 
129void Xzs_Construct(CXzs *p);
130void Xzs_Free(CXzs *p, ISzAlloc *alloc);
131SRes Xzs_ReadBackward(CXzs *p, ILookInStream *inStream, Int64 *startOffset, ICompressProgress *progress, ISzAlloc *alloc);
132 
133UInt64 Xzs_GetNumBlocks(const CXzs *p);
134UInt64 Xzs_GetUnpackSize(const CXzs *p);
135 
136typedef enum
137{
138  CODER_STATUS_NOT_SPECIFIED,               /* use main error code instead */
139  CODER_STATUS_FINISHED_WITH_MARK,          /* stream was finished with end mark. */
140  CODER_STATUS_NOT_FINISHED,                /* stream was not finished */
141  CODER_STATUS_NEEDS_MORE_INPUT             /* you must provide more input bytes */
142} ECoderStatus;
143 
144typedef enum
145{
146  CODER_FINISH_ANY,   /* finish at any point */
147  CODER_FINISH_END    /* block must be finished at the end */
148} ECoderFinishMode;
149 
150typedef struct _IStateCoder
151{
152  void *p;
153  void (*Free)(void *p, ISzAlloc *alloc);
154  SRes (*SetProps)(void *p, const Byte *props, size_t propSize, ISzAlloc *alloc);
155  void (*Init)(void *p);
156  SRes (*Code)(void *p, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
157      int srcWasFinished, ECoderFinishMode finishMode, int *wasFinished);
158} IStateCoder;
159 
160#define MIXCODER_NUM_FILTERS_MAX 4
161 
162typedef struct
163{
164  ISzAlloc *alloc;
165  Byte *buf;
166  int numCoders;
167  int finished[MIXCODER_NUM_FILTERS_MAX - 1];
168  size_t pos[MIXCODER_NUM_FILTERS_MAX - 1];
169  size_t size[MIXCODER_NUM_FILTERS_MAX - 1];
170  UInt64 ids[MIXCODER_NUM_FILTERS_MAX];
171  IStateCoder coders[MIXCODER_NUM_FILTERS_MAX];
172} CMixCoder;
173 
174void MixCoder_Construct(CMixCoder *p, ISzAlloc *alloc);
175void MixCoder_Free(CMixCoder *p);
176void MixCoder_Init(CMixCoder *p);
177SRes MixCoder_SetFromMethod(CMixCoder *p, int coderIndex, UInt64 methodId);
178SRes MixCoder_Code(CMixCoder *p, Byte *dest, SizeT *destLen,
179    const Byte *src, SizeT *srcLen, int srcWasFinished,
180    ECoderFinishMode finishMode, ECoderStatus *status);
181 
182typedef enum
183{
184  XZ_STATE_STREAM_HEADER,
185  XZ_STATE_STREAM_INDEX,
186  XZ_STATE_STREAM_INDEX_CRC,
187  XZ_STATE_STREAM_FOOTER,
188  XZ_STATE_STREAM_PADDING,
189  XZ_STATE_BLOCK_HEADER,
190  XZ_STATE_BLOCK,
191  XZ_STATE_BLOCK_FOOTER
192} EXzState;
193 
194typedef struct
195{
196  EXzState state;
197  UInt32 pos;
198  unsigned alignPos;
199  unsigned indexPreSize;
200 
201  CXzStreamFlags streamFlags;
202   
203  UInt32 blockHeaderSize;
204  UInt64 packSize;
205  UInt64 unpackSize;
206 
207  UInt64 numBlocks;
208  UInt64 indexSize;
209  UInt64 indexPos;
210  UInt64 padSize;
211 
212  UInt64 numStreams;
213 
214  UInt32 crc;
215  CMixCoder decoder;
216  CXzBlock block;
217  CXzCheck check;
218  CSha256 sha;
219  Byte shaDigest[SHA256_DIGEST_SIZE];
220  Byte buf[XZ_BLOCK_HEADER_SIZE_MAX];
221} CXzUnpacker;
222 
223void XzUnpacker_Construct(CXzUnpacker *p, ISzAlloc *alloc);
224void XzUnpacker_Init(CXzUnpacker *p);
225void XzUnpacker_Free(CXzUnpacker *p);
226 
227/*
228finishMode:
229  It has meaning only if the decoding reaches output limit (*destLen).
230  LZMA_FINISH_ANY - use smallest number of input bytes
231  LZMA_FINISH_END - read EndOfStream marker after decoding
232 
233Returns:
234  SZ_OK
235    status:
236      CODER_STATUS_NOT_FINISHED,
237      CODER_STATUS_NEEDS_MORE_INPUT - maybe there are more xz streams,
238                                      call XzUnpacker_IsStreamWasFinished to check that current stream was finished
239  SZ_ERROR_DATA - Data error
240  SZ_ERROR_MEM  - Memory allocation error
241  SZ_ERROR_UNSUPPORTED - Unsupported properties
242  SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src).
243*/
244 
245 
246SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen,
247    const Byte *src, SizeT *srcLen, /* int srcWasFinished, */ int finishMode,
248    ECoderStatus *status);
249 
250Bool XzUnpacker_IsStreamWasFinished(CXzUnpacker *p);
251 
252EXTERN_C_END
253 
254#endif
src/lib/lib7z/Lzma2Dec.h
r0r14440
1/* Lzma2Dec.h -- LZMA2 Decoder
22009-05-03 : Igor Pavlov : Public domain */
3 
4#ifndef __LZMA2_DEC_H
5#define __LZMA2_DEC_H
6 
7#include "LzmaDec.h"
8 
9#ifdef __cplusplus
10extern "C" {
11#endif
12 
13/* ---------- State Interface ---------- */
14 
15typedef struct
16{
17  CLzmaDec decoder;
18  UInt32 packSize;
19  UInt32 unpackSize;
20  int state;
21  Byte control;
22  Bool needInitDic;
23  Bool needInitState;
24  Bool needInitProp;
25} CLzma2Dec;
26 
27#define Lzma2Dec_Construct(p) LzmaDec_Construct(&(p)->decoder)
28#define Lzma2Dec_FreeProbs(p, alloc) LzmaDec_FreeProbs(&(p)->decoder, alloc);
29#define Lzma2Dec_Free(p, alloc) LzmaDec_Free(&(p)->decoder, alloc);
30 
31SRes Lzma2Dec_AllocateProbs(CLzma2Dec *p, Byte prop, ISzAlloc *alloc);
32SRes Lzma2Dec_Allocate(CLzma2Dec *p, Byte prop, ISzAlloc *alloc);
33void Lzma2Dec_Init(CLzma2Dec *p);
34 
35 
36/*
37finishMode:
38  It has meaning only if the decoding reaches output limit (*destLen or dicLimit).
39  LZMA_FINISH_ANY - use smallest number of input bytes
40  LZMA_FINISH_END - read EndOfStream marker after decoding
41 
42Returns:
43  SZ_OK
44    status:
45      LZMA_STATUS_FINISHED_WITH_MARK
46      LZMA_STATUS_NOT_FINISHED
47      LZMA_STATUS_NEEDS_MORE_INPUT
48  SZ_ERROR_DATA - Data error
49*/
50 
51SRes Lzma2Dec_DecodeToDic(CLzma2Dec *p, SizeT dicLimit,
52    const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
53 
54SRes Lzma2Dec_DecodeToBuf(CLzma2Dec *p, Byte *dest, SizeT *destLen,
55    const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
56 
57 
58/* ---------- One Call Interface ---------- */
59 
60/*
61finishMode:
62  It has meaning only if the decoding reaches output limit (*destLen).
63  LZMA_FINISH_ANY - use smallest number of input bytes
64  LZMA_FINISH_END - read EndOfStream marker after decoding
65 
66Returns:
67  SZ_OK
68    status:
69      LZMA_STATUS_FINISHED_WITH_MARK
70      LZMA_STATUS_NOT_FINISHED
71  SZ_ERROR_DATA - Data error
72  SZ_ERROR_MEM  - Memory allocation error
73  SZ_ERROR_UNSUPPORTED - Unsupported properties
74  SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src).
75*/
76 
77SRes Lzma2Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
78    Byte prop, ELzmaFinishMode finishMode, ELzmaStatus *status, ISzAlloc *alloc);
79 
80#ifdef __cplusplus
81}
82#endif
83 
84#endif
src/lib/lib7z/XzCrc64.h
r0r14440
1/* XzCrc64.h -- CRC64 calculation
22010-04-16 : Igor Pavlov : Public domain */
3 
4#ifndef __XZ_CRC64_H
5#define __XZ_CRC64_H
6 
7#include <stddef.h>
8 
9#include "Types.h"
10 
11EXTERN_C_BEGIN
12 
13extern UInt64 g_Crc64Table[];
14 
15void MY_FAST_CALL Crc64GenerateTable(void);
16 
17#define CRC64_INIT_VAL UINT64_CONST(0xFFFFFFFFFFFFFFFF)
18#define CRC64_GET_DIGEST(crc) ((crc) ^ CRC64_INIT_VAL)
19#define CRC64_UPDATE_BYTE(crc, b) (g_Crc64Table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
20 
21UInt64 MY_FAST_CALL Crc64Update(UInt64 crc, const void *data, size_t size);
22UInt64 MY_FAST_CALL Crc64Calc(const void *data, size_t size);
23 
24EXTERN_C_END
25 
26#endif
src/lib/lib7z/Sha256.c
r0r14440
1/* Crypto/Sha256.c -- SHA-256 Hash
22010-06-11 : Igor Pavlov : Public domain
3This code is based on public domain code from Wei Dai's Crypto++ library. */
4 
5#include "RotateDefs.h"
6#include "Sha256.h"
7 
8/* define it for speed optimization */
9/* #define _SHA256_UNROLL */
10/* #define _SHA256_UNROLL2 */
11 
12void Sha256_Init(CSha256 *p)
13{
14  p->state[0] = 0x6a09e667;
15  p->state[1] = 0xbb67ae85;
16  p->state[2] = 0x3c6ef372;
17  p->state[3] = 0xa54ff53a;
18  p->state[4] = 0x510e527f;
19  p->state[5] = 0x9b05688c;
20  p->state[6] = 0x1f83d9ab;
21  p->state[7] = 0x5be0cd19;
22  p->count = 0;
23}
24 
25#define S0(x) (rotrFixed(x, 2) ^ rotrFixed(x,13) ^ rotrFixed(x, 22))
26#define S1(x) (rotrFixed(x, 6) ^ rotrFixed(x,11) ^ rotrFixed(x, 25))
27#define s0(x) (rotrFixed(x, 7) ^ rotrFixed(x,18) ^ (x >> 3))
28#define s1(x) (rotrFixed(x,17) ^ rotrFixed(x,19) ^ (x >> 10))
29 
30#define blk0(i) (W[i] = data[i])
31#define blk2(i) (W[i&15] += s1(W[(i-2)&15]) + W[(i-7)&15] + s0(W[(i-15)&15]))
32 
33#define Ch(x,y,z) (z^(x&(y^z)))
34#define Maj(x,y,z) ((x&y)|(z&(x|y)))
35 
36#define a(i) T[(0-(i))&7]
37#define b(i) T[(1-(i))&7]
38#define c(i) T[(2-(i))&7]
39#define d(i) T[(3-(i))&7]
40#define e(i) T[(4-(i))&7]
41#define f(i) T[(5-(i))&7]
42#define g(i) T[(6-(i))&7]
43#define h(i) T[(7-(i))&7]
44 
45 
46#ifdef _SHA256_UNROLL2
47 
48#define R(a,b,c,d,e,f,g,h, i) h += S1(e) + Ch(e,f,g) + K[i+j] + (j?blk2(i):blk0(i));\
49  d += h; h += S0(a) + Maj(a, b, c)
50 
51#define RX_8(i) \
52  R(a,b,c,d,e,f,g,h, i); \
53  R(h,a,b,c,d,e,f,g, i+1); \
54  R(g,h,a,b,c,d,e,f, i+2); \
55  R(f,g,h,a,b,c,d,e, i+3); \
56  R(e,f,g,h,a,b,c,d, i+4); \
57  R(d,e,f,g,h,a,b,c, i+5); \
58  R(c,d,e,f,g,h,a,b, i+6); \
59  R(b,c,d,e,f,g,h,a, i+7)
60 
61#else
62 
63#define R(i) h(i) += S1(e(i)) + Ch(e(i),f(i),g(i)) + K[i+j] + (j?blk2(i):blk0(i));\
64  d(i) += h(i); h(i) += S0(a(i)) + Maj(a(i), b(i), c(i))
65 
66#ifdef _SHA256_UNROLL
67 
68#define RX_8(i) R(i+0); R(i+1); R(i+2); R(i+3); R(i+4); R(i+5); R(i+6); R(i+7);
69 
70#endif
71 
72#endif
73 
74static const UInt32 K[64] = {
75  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
76  0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
77  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
78  0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
79  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
80  0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
81  0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
82  0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
83  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
84  0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
85  0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
86  0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
87  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
88  0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
89  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
90  0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
91};
92 
93static void Sha256_Transform(UInt32 *state, const UInt32 *data)
94{
95  UInt32 W[16];
96  unsigned j;
97  #ifdef _SHA256_UNROLL2
98  UInt32 a,b,c,d,e,f,g,h;
99  a = state[0];
100  b = state[1];
101  c = state[2];
102  d = state[3];
103  e = state[4];
104  f = state[5];
105  g = state[6];
106  h = state[7];
107  #else
108  UInt32 T[8];
109  for (j = 0; j < 8; j++)
110    T[j] = state[j];
111  #endif
112 
113  for (j = 0; j < 64; j += 16)
114  {
115    #if defined(_SHA256_UNROLL) || defined(_SHA256_UNROLL2)
116    RX_8(0); RX_8(8);
117    #else
118    unsigned i;
119    for (i = 0; i < 16; i++) { R(i); }
120    #endif
121  }
122 
123  #ifdef _SHA256_UNROLL2
124  state[0] += a;
125  state[1] += b;
126  state[2] += c;
127  state[3] += d;
128  state[4] += e;
129  state[5] += f;
130  state[6] += g;
131  state[7] += h;
132  #else
133  for (j = 0; j < 8; j++)
134    state[j] += T[j];
135  #endif
136   
137  /* Wipe variables */
138  /* memset(W, 0, sizeof(W)); */
139  /* memset(T, 0, sizeof(T)); */
140}
141 
142#undef S0
143#undef S1
144#undef s0
145#undef s1
146 
147static void Sha256_WriteByteBlock(CSha256 *p)
148{
149  UInt32 data32[16];
150  unsigned i;
151  for (i = 0; i < 16; i++)
152    data32[i] =
153      ((UInt32)(p->buffer[i * 4    ]) << 24) +
154      ((UInt32)(p->buffer[i * 4 + 1]) << 16) +
155      ((UInt32)(p->buffer[i * 4 + 2]) <<  8) +
156      ((UInt32)(p->buffer[i * 4 + 3]));
157  Sha256_Transform(p->state, data32);
158}
159 
160void Sha256_Update(CSha256 *p, const Byte *data, size_t size)
161{
162  UInt32 curBufferPos = (UInt32)p->count & 0x3F;
163  while (size > 0)
164  {
165    p->buffer[curBufferPos++] = *data++;
166    p->count++;
167    size--;
168    if (curBufferPos == 64)
169    {
170      curBufferPos = 0;
171      Sha256_WriteByteBlock(p);
172    }
173  }
174}
175 
176void Sha256_Final(CSha256 *p, Byte *digest)
177{
178  UInt64 lenInBits = (p->count << 3);
179  UInt32 curBufferPos = (UInt32)p->count & 0x3F;
180  unsigned i;
181  p->buffer[curBufferPos++] = 0x80;
182  while (curBufferPos != (64 - 8))
183  {
184    curBufferPos &= 0x3F;
185    if (curBufferPos == 0)
186      Sha256_WriteByteBlock(p);
187    p->buffer[curBufferPos++] = 0;
188  }
189  for (i = 0; i < 8; i++)
190  {
191    p->buffer[curBufferPos++] = (Byte)(lenInBits >> 56);
192    lenInBits <<= 8;
193  }
194  Sha256_WriteByteBlock(p);
195 
196  for (i = 0; i < 8; i++)
197  {
198    *digest++ = (Byte)(p->state[i] >> 24);
199    *digest++ = (Byte)(p->state[i] >> 16);
200    *digest++ = (Byte)(p->state[i] >> 8);
201    *digest++ = (Byte)(p->state[i]);
202  }
203  Sha256_Init(p);
204}
src/lib/lib7z/Types.h
r0r14440
1/* Types.h -- Basic types
22010-10-09 : Igor Pavlov : Public domain */
3 
4#ifndef __7Z_TYPES_H
5#define __7Z_TYPES_H
6 
7#include <stddef.h>
8 
9#ifdef _WIN32_7Z
10#include <windows.h>
11#endif
12 
13#ifndef EXTERN_C_BEGIN
14#ifdef __cplusplus
15#define EXTERN_C_BEGIN extern "C" {
16#define EXTERN_C_END }
17#else
18#define EXTERN_C_BEGIN
19#define EXTERN_C_END
20#endif
21#endif
22 
23EXTERN_C_BEGIN
24 
25#define SZ_OK 0
26 
27#define SZ_ERROR_DATA 1
28#define SZ_ERROR_MEM 2
29#define SZ_ERROR_CRC 3
30#define SZ_ERROR_UNSUPPORTED 4
31#define SZ_ERROR_PARAM 5
32#define SZ_ERROR_INPUT_EOF 6
33#define SZ_ERROR_OUTPUT_EOF 7
34#define SZ_ERROR_READ 8
35#define SZ_ERROR_WRITE 9
36#define SZ_ERROR_PROGRESS 10
37#define SZ_ERROR_FAIL 11
38#define SZ_ERROR_THREAD 12
39 
40#define SZ_ERROR_ARCHIVE 16
41#define SZ_ERROR_NO_ARCHIVE 17
42 
43typedef int SRes;
44 
45#ifdef _WIN32_7Z
46typedef DWORD WRes;
47#else
48typedef int WRes;
49#endif
50 
51#ifndef RINOK
52#define RINOK(x) { int __result__ = (x); if (__result__ != 0) return __result__; }
53#endif
54 
55typedef unsigned char Byte;
56typedef short Int16;
57typedef unsigned short UInt16;
58 
59#ifdef _LZMA_UINT32_IS_ULONG
60typedef long Int32;
61typedef unsigned long UInt32;
62#else
63typedef int Int32;
64typedef unsigned int UInt32;
65#endif
66 
67#ifdef _SZ_NO_INT_64
68 
69/* define _SZ_NO_INT_64, if your compiler doesn't support 64-bit integers.
70   NOTES: Some code will work incorrectly in that case! */
71 
72typedef long Int64;
73typedef unsigned long UInt64;
74 
75#else
76 
77#if defined(_MSC_VER) || defined(__BORLANDC__)
78typedef __int64 Int64;
79typedef unsigned __int64 UInt64;
80#define UINT64_CONST(n) n
81#else
82typedef long long int Int64;
83typedef unsigned long long int UInt64;
84#define UINT64_CONST(n) n ## ULL
85#endif
86 
87#endif
88 
89#ifdef _LZMA_NO_SYSTEM_SIZE_T
90typedef UInt32 SizeT;
91#else
92typedef size_t SizeT;
93#endif
94 
95typedef int Bool;
96#define True 1
97#define False 0
98 
99 
100#ifdef _WIN32_7Z
101#define MY_STD_CALL __stdcall
102#else
103#define MY_STD_CALL
104#endif
105 
106#ifdef _MSC_VER
107 
108#if _MSC_VER >= 1300
109#define MY_NO_INLINE __declspec(noinline)
110#else
111#define MY_NO_INLINE
112#endif
113 
114#define MY_CDECL __cdecl
115#define MY_FAST_CALL __fastcall
116 
117#else
118 
119#define MY_CDECL
120#define MY_FAST_CALL
121 
122#endif
123 
124 
125/* The following interfaces use first parameter as pointer to structure */
126 
127typedef struct
128{
129  Byte (*Read)(void *p); /* reads one byte, returns 0 in case of EOF or error */
130} IByteIn;
131 
132typedef struct
133{
134  void (*Write)(void *p, Byte b);
135} IByteOut;
136 
137typedef struct
138{
139  SRes (*Read)(void *p, void *buf, size_t *size);
140    /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream.
141       (output(*size) < input(*size)) is allowed */
142} ISeqInStream;
143 
144/* it can return SZ_ERROR_INPUT_EOF */
145SRes SeqInStream_Read(ISeqInStream *stream, void *buf, size_t size);
146SRes SeqInStream_Read2(ISeqInStream *stream, void *buf, size_t size, SRes errorType);
147SRes SeqInStream_ReadByte(ISeqInStream *stream, Byte *buf);
148 
149typedef struct
150{
151  size_t (*Write)(void *p, const void *buf, size_t size);
152    /* Returns: result - the number of actually written bytes.
153       (result < size) means error */
154} ISeqOutStream;
155 
156typedef enum
157{
158  SZ_SEEK_SET = 0,
159  SZ_SEEK_CUR = 1,
160  SZ_SEEK_END = 2
161} ESzSeek;
162 
163typedef struct
164{
165  SRes (*Read)(void *p, void *buf, size_t *size);  /* same as ISeqInStream::Read */
166  SRes (*Seek)(void *p, Int64 *pos, ESzSeek origin);
167} ISeekInStream;
168 
169typedef struct
170{
171  SRes (*Look)(void *p, const void **buf, size_t *size);
172    /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream.
173       (output(*size) > input(*size)) is not allowed
174       (output(*size) < input(*size)) is allowed */
175  SRes (*Skip)(void *p, size_t offset);
176    /* offset must be <= output(*size) of Look */
177 
178  SRes (*Read)(void *p, void *buf, size_t *size);
179    /* reads directly (without buffer). It's same as ISeqInStream::Read */
180  SRes (*Seek)(void *p, Int64 *pos, ESzSeek origin);
181} ILookInStream;
182 
183SRes LookInStream_LookRead(ILookInStream *stream, void *buf, size_t *size);
184SRes LookInStream_SeekTo(ILookInStream *stream, UInt64 offset);
185 
186/* reads via ILookInStream::Read */
187SRes LookInStream_Read2(ILookInStream *stream, void *buf, size_t size, SRes errorType);
188SRes LookInStream_Read(ILookInStream *stream, void *buf, size_t size);
189 
190#define LookToRead_BUF_SIZE (1 << 14)
191 
192typedef struct
193{
194  ILookInStream s;
195  ISeekInStream *realStream;
196  size_t pos;
197  size_t size;
198  Byte buf[LookToRead_BUF_SIZE];
199} CLookToRead;
200 
201void LookToRead_CreateVTable(CLookToRead *p, int lookahead);
202void LookToRead_Init(CLookToRead *p);
203 
204typedef struct
205{
206  ISeqInStream s;
207  ILookInStream *realStream;
208} CSecToLook;
209 
210void SecToLook_CreateVTable(CSecToLook *p);
211 
212typedef struct
213{
214  ISeqInStream s;
215  ILookInStream *realStream;
216} CSecToRead;
217 
218void SecToRead_CreateVTable(CSecToRead *p);
219 
220typedef struct
221{
222  SRes (*Progress)(void *p, UInt64 inSize, UInt64 outSize);
223    /* Returns: result. (result != SZ_OK) means break.
224       Value (UInt64)(Int64)-1 for size means unknown value. */
225} ICompressProgress;
226 
227typedef struct
228{
229  void *(*Alloc)(void *p, size_t size);
230  void (*Free)(void *p, void *address); /* address can be 0 */
231} ISzAlloc;
232 
233#define IAlloc_Alloc(p, size) (p)->Alloc((p), size)
234#define IAlloc_Free(p, a) (p)->Free((p), a)
235 
236#ifdef _WIN32_7Z
237 
238#define CHAR_PATH_SEPARATOR '\\'
239#define WCHAR_PATH_SEPARATOR L'\\'
240#define STRING_PATH_SEPARATOR "\\"
241#define WSTRING_PATH_SEPARATOR L"\\"
242 
243#else
244 
245#define CHAR_PATH_SEPARATOR '/'
246#define WCHAR_PATH_SEPARATOR L'/'
247#define STRING_PATH_SEPARATOR "/"
248#define WSTRING_PATH_SEPARATOR L"/"
249 
250#endif
251 
252EXTERN_C_END
253 
254#endif
src/lib/lib7z/7zCrcOpt.c
r0r14440
1/* 7zCrcOpt.c -- CRC32 calculation
22010-12-01 : Igor Pavlov : Public domain */
3 
4#include "CpuArch.h"
5 
6#define CRC_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
7 
8#ifndef MY_CPU_BE
9 
10UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table)
11{
12  const Byte *p = (const Byte *)data;
13  for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++)
14    v = CRC_UPDATE_BYTE_2(v, *p);
15  for (; size >= 4; size -= 4, p += 4)
16  {
17    v ^= *(const UInt32 *)p;
18    v =
19      table[0x300 + (v & 0xFF)] ^
20      table[0x200 + ((v >> 8) & 0xFF)] ^
21      table[0x100 + ((v >> 16) & 0xFF)] ^
22      table[0x000 + ((v >> 24))];
23  }
24  for (; size > 0; size--, p++)
25    v = CRC_UPDATE_BYTE_2(v, *p);
26  return v;
27}
28 
29UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table)
30{
31  return CrcUpdateT4(v, data, size, table);
32}
33 
34#endif
35 
36 
37#ifndef MY_CPU_LE
38 
39#define CRC_UINT32_SWAP(v) ((v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24))
40 
41UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table)
42{
43  const Byte *p = (const Byte *)data;
44  for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++)
45    v = CRC_UPDATE_BYTE_2(v, *p);
46  v = CRC_UINT32_SWAP(v);
47  table += 0x100;
48  for (; size >= 4; size -= 4, p += 4)
49  {
50    v ^= *(const UInt32 *)p;
51    v =
52      table[0x000 + (v & 0xFF)] ^
53      table[0x100 + ((v >> 8) & 0xFF)] ^
54      table[0x200 + ((v >> 16) & 0xFF)] ^
55      table[0x300 + ((v >> 24))];
56  }
57  table -= 0x100;
58  v = CRC_UINT32_SWAP(v);
59  for (; size > 0; size--, p++)
60    v = CRC_UPDATE_BYTE_2(v, *p);
61  return v;
62}
63 
64#endif
src/lib/lib7z/7zDec.c
r0r14440
1/* 7zDec.c -- Decoding from 7z folder
22010-11-02 : Igor Pavlov : Public domain */
3 
4#include <string.h>
5 
6/* #define _7ZIP_PPMD_SUPPPORT */
7 
8#include "7z.h"
9 
10#include "Bcj2.h"
11#include "Bra.h"
12#include "CpuArch.h"
13#include "LzmaDec.h"
14#include "Lzma2Dec.h"
15#ifdef _7ZIP_PPMD_SUPPPORT
16#include "Ppmd7.h"
17#endif
18 
19#define k_Copy 0
20#define k_LZMA2 0x21
21#define k_LZMA  0x30101
22#define k_BCJ   0x03030103
23#define k_PPC   0x03030205
24#define k_ARM   0x03030501
25#define k_ARMT  0x03030701
26#define k_SPARC 0x03030805
27#define k_BCJ2  0x0303011B
28 
29#ifdef _7ZIP_PPMD_SUPPPORT
30 
31#define k_PPMD 0x30401
32 
33typedef struct
34{
35  IByteIn p;
36  const Byte *cur;
37  const Byte *end;
38  const Byte *begin;
39  UInt64 processed;
40  Bool extra;
41  SRes res;
42  ILookInStream *inStream;
43} CByteInToLook;
44 
45static Byte ReadByte(void *pp)
46{
47  CByteInToLook *p = (CByteInToLook *)pp;
48  if (p->cur != p->end)
49    return *p->cur++;
50  if (p->res == SZ_OK)
51  {
52    size_t size = p->cur - p->begin;
53    p->processed += size;
54    p->res = p->inStream->Skip(p->inStream, size);
55    size = (1 << 25);
56    p->res = p->inStream->Look(p->inStream, (const void **)&p->begin, &size);
57    p->cur = p->begin;
58    p->end = p->begin + size;
59    if (size != 0)
60      return *p->cur++;;
61  }
62  p->extra = True;
63  return 0;
64}
65 
66static SRes SzDecodePpmd(CSzCoderInfo *coder, UInt64 inSize, ILookInStream *inStream,
67    Byte *outBuffer, SizeT outSize, ISzAlloc *allocMain)
68{
69  CPpmd7 ppmd;
70  CByteInToLook s;
71  SRes res = SZ_OK;
72 
73  s.p.Read = ReadByte;
74  s.inStream = inStream;
75  s.begin = s.end = s.cur = NULL;
76  s.extra = False;
77  s.res = SZ_OK;
78  s.processed = 0;
79 
80  if (coder->Props.size != 5)
81    return SZ_ERROR_UNSUPPORTED;
82 
83  {
84    unsigned order = coder->Props.data[0];
85    UInt32 memSize = GetUi32(coder->Props.data + 1);
86    if (order < PPMD7_MIN_ORDER ||
87        order > PPMD7_MAX_ORDER ||
88        memSize < PPMD7_MIN_MEM_SIZE ||
89        memSize > PPMD7_MAX_MEM_SIZE)
90      return SZ_ERROR_UNSUPPORTED;
91    Ppmd7_Construct(&ppmd);
92    if (!Ppmd7_Alloc(&ppmd, memSize, allocMain))
93      return SZ_ERROR_MEM;
94    Ppmd7_Init(&ppmd, order);
95  }
96  {
97    CPpmd7z_RangeDec rc;
98    Ppmd7z_RangeDec_CreateVTable(&rc);
99    rc.Stream = &s.p;
100    if (!Ppmd7z_RangeDec_Init(&rc))
101      res = SZ_ERROR_DATA;
102    else if (s.extra)
103      res = (s.res != SZ_OK ? s.res : SZ_ERROR_DATA);
104    else
105    {
106      SizeT i;
107      for (i = 0; i < outSize; i++)
108      {
109        int sym = Ppmd7_DecodeSymbol(&ppmd, &rc.p);
110        if (s.extra || sym < 0)
111          break;
112        outBuffer[i] = (Byte)sym;
113      }
114      if (i != outSize)
115        res = (s.res != SZ_OK ? s.res : SZ_ERROR_DATA);
116      else if (s.processed + (s.cur - s.begin) != inSize || !Ppmd7z_RangeDec_IsFinishedOK(&rc))
117        res = SZ_ERROR_DATA;
118    }
119  }
120  Ppmd7_Free(&ppmd, allocMain);
121  return res;
122}
123 
124#endif
125 
126 
127static SRes SzDecodeLzma(CSzCoderInfo *coder, UInt64 inSize, ILookInStream *inStream,
128    Byte *outBuffer, SizeT outSize, ISzAlloc *allocMain)
129{
130  CLzmaDec state;
131  SRes res = SZ_OK;
132 
133  LzmaDec_Construct(&state);
134  RINOK(LzmaDec_AllocateProbs(&state, coder->Props.data, (unsigned)coder->Props.size, allocMain));
135  state.dic = outBuffer;
136  state.dicBufSize = outSize;
137  LzmaDec_Init(&state);
138 
139  for (;;)
140  {
141    Byte *inBuf = NULL;
142    size_t lookahead = (1 << 18);
143    if (lookahead > inSize)
144      lookahead = (size_t)inSize;
145    res = inStream->Look((void *)inStream, (const void **)&inBuf, &lookahead);
146    if (res != SZ_OK)
147      break;
148 
149    {
150      SizeT inProcessed = (SizeT)lookahead, dicPos = state.dicPos;
151      ELzmaStatus status;
152      res = LzmaDec_DecodeToDic(&state, outSize, inBuf, &inProcessed, LZMA_FINISH_END, &status);
153      lookahead -= inProcessed;
154      inSize -= inProcessed;
155      if (res != SZ_OK)
156        break;
157      if (state.dicPos == state.dicBufSize || (inProcessed == 0 && dicPos == state.dicPos))
158      {
159        if (state.dicBufSize != outSize || lookahead != 0 ||
160            (status != LZMA_STATUS_FINISHED_WITH_MARK &&
161             status != LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK))
162          res = SZ_ERROR_DATA;
163        break;
164      }
165      res = inStream->Skip((void *)inStream, inProcessed);
166      if (res != SZ_OK)
167        break;
168    }
169  }
170 
171  LzmaDec_FreeProbs(&state, allocMain);
172  return res;
173}
174 
175static SRes SzDecodeLzma2(CSzCoderInfo *coder, UInt64 inSize, ILookInStream *inStream,
176    Byte *outBuffer, SizeT outSize, ISzAlloc *allocMain)
177{
178  CLzma2Dec state;
179  SRes res = SZ_OK;
180 
181  Lzma2Dec_Construct(&state);
182  if (coder->Props.size != 1)
183    return SZ_ERROR_DATA;
184  RINOK(Lzma2Dec_AllocateProbs(&state, coder->Props.data[0], allocMain));
185  state.decoder.dic = outBuffer;
186  state.decoder.dicBufSize = outSize;
187  Lzma2Dec_Init(&state);
188 
189  for (;;)
190  {
191    Byte *inBuf = NULL;
192    size_t lookahead = (1 << 18);
193    if (lookahead > inSize)
194      lookahead = (size_t)inSize;
195    res = inStream->Look((void *)inStream, (const void **)&inBuf, &lookahead);
196    if (res != SZ_OK)
197      break;
198 
199    {
200      SizeT inProcessed = (SizeT)lookahead, dicPos = state.decoder.dicPos;
201      ELzmaStatus status;
202      res = Lzma2Dec_DecodeToDic(&state, outSize, inBuf, &inProcessed, LZMA_FINISH_END, &status);
203      lookahead -= inProcessed;
204      inSize -= inProcessed;
205      if (res != SZ_OK)
206        break;
207      if (state.decoder.dicPos == state.decoder.dicBufSize || (inProcessed == 0 && dicPos == state.decoder.dicPos))
208      {
209        if (state.decoder.dicBufSize != outSize || lookahead != 0 ||
210            (status != LZMA_STATUS_FINISHED_WITH_MARK))
211          res = SZ_ERROR_DATA;
212        break;
213      }
214      res = inStream->Skip((void *)inStream, inProcessed);
215      if (res != SZ_OK)
216        break;
217    }
218  }
219 
220  Lzma2Dec_FreeProbs(&state, allocMain);
221  return res;
222}
223 
224static SRes SzDecodeCopy(UInt64 inSize, ILookInStream *inStream, Byte *outBuffer)
225{
226  while (inSize > 0)
227  {
228    void *inBuf;
229    size_t curSize = (1 << 18);
230    if (curSize > inSize)
231      curSize = (size_t)inSize;
232    RINOK(inStream->Look((void *)inStream, (const void **)&inBuf, &curSize));
233    if (curSize == 0)
234      return SZ_ERROR_INPUT_EOF;
235    memcpy(outBuffer, inBuf, curSize);
236    outBuffer += curSize;
237    inSize -= curSize;
238    RINOK(inStream->Skip((void *)inStream, curSize));
239  }
240  return SZ_OK;
241}
242 
243static Bool IS_MAIN_METHOD(UInt32 m)
244{
245  switch(m)
246  {
247    case k_Copy:
248    case k_LZMA:
249    case k_LZMA2:
250    #ifdef _7ZIP_PPMD_SUPPPORT
251    case k_PPMD:
252    #endif
253      return True;
254  }
255  return False;
256}
257 
258static Bool IS_SUPPORTED_CODER(const CSzCoderInfo *c)
259{
260  return
261      c->NumInStreams == 1 &&
262      c->NumOutStreams == 1 &&
263      c->MethodID <= (UInt32)0xFFFFFFFF &&
264      IS_MAIN_METHOD((UInt32)c->MethodID);
265}
266 
267#define IS_BCJ2(c) ((c)->MethodID == k_BCJ2 && (c)->NumInStreams == 4 && (c)->NumOutStreams == 1)
268 
269static SRes CheckSupportedFolder(const CSzFolder *f)
270{
271  if (f->NumCoders < 1 || f->NumCoders > 4)
272    return SZ_ERROR_UNSUPPORTED;
273  if (!IS_SUPPORTED_CODER(&f->Coders[0]))
274    return SZ_ERROR_UNSUPPORTED;
275  if (f->NumCoders == 1)
276  {
277    if (f->NumPackStreams != 1 || f->PackStreams[0] != 0 || f->NumBindPairs != 0)
278      return SZ_ERROR_UNSUPPORTED;
279    return SZ_OK;
280  }
281  if (f->NumCoders == 2)
282  {
283    CSzCoderInfo *c = &f->Coders[1];
284    if (c->MethodID > (UInt32)0xFFFFFFFF ||
285        c->NumInStreams != 1 ||
286        c->NumOutStreams != 1 ||
287        f->NumPackStreams != 1 ||
288        f->PackStreams[0] != 0 ||
289        f->NumBindPairs != 1 ||
290        f->BindPairs[0].InIndex != 1 ||
291        f->BindPairs[0].OutIndex != 0)
292      return SZ_ERROR_UNSUPPORTED;
293    switch ((UInt32)c->MethodID)
294    {
295      case k_BCJ:
296      case k_ARM:
297        break;
298      default:
299        return SZ_ERROR_UNSUPPORTED;
300    }
301    return SZ_OK;
302  }
303  if (f->NumCoders == 4)
304  {
305    if (!IS_SUPPORTED_CODER(&f->Coders[1]) ||
306        !IS_SUPPORTED_CODER(&f->Coders[2]) ||
307        !IS_BCJ2(&f->Coders[3]))
308      return SZ_ERROR_UNSUPPORTED;
309    if (f->NumPackStreams != 4 ||
310        f->PackStreams[0] != 2 ||
311        f->PackStreams[1] != 6 ||
312        f->PackStreams[2] != 1 ||
313        f->PackStreams[3] != 0 ||
314        f->NumBindPairs != 3 ||
315        f->BindPairs[0].InIndex != 5 || f->BindPairs[0].OutIndex != 0 ||
316        f->BindPairs[1].InIndex != 4 || f->BindPairs[1].OutIndex != 1 ||
317        f->BindPairs[2].InIndex != 3 || f->BindPairs[2].OutIndex != 2)
318      return SZ_ERROR_UNSUPPORTED;
319    return SZ_OK;
320  }
321  return SZ_ERROR_UNSUPPORTED;
322}
323 
324static UInt64 GetSum(const UInt64 *values, UInt32 index)
325{
326  UInt64 sum = 0;
327  UInt32 i;
328  for (i = 0; i < index; i++)
329    sum += values[i];
330  return sum;
331}
332 
333#define CASE_BRA_CONV(isa) case k_ ## isa: isa ## _Convert(outBuffer, outSize, 0, 0); break;
334 
335static SRes SzFolder_Decode2(const CSzFolder *folder, const UInt64 *packSizes,
336    ILookInStream *inStream, UInt64 startPos,
337    Byte *outBuffer, SizeT outSize, ISzAlloc *allocMain,
338    Byte *tempBuf[])
339{
340  UInt32 ci;
341  SizeT tempSizes[3] = { 0, 0, 0};
342  SizeT tempSize3 = 0;
343  Byte *tempBuf3 = 0;
344 
345  RINOK(CheckSupportedFolder(folder));
346 
347  for (ci = 0; ci < folder->NumCoders; ci++)
348  {
349    CSzCoderInfo *coder = &folder->Coders[ci];
350 
351    if (IS_MAIN_METHOD((UInt32)coder->MethodID))
352    {
353      UInt32 si = 0;
354      UInt64 offset;
355      UInt64 inSize;
356      Byte *outBufCur = outBuffer;
357      SizeT outSizeCur = outSize;
358      if (folder->NumCoders == 4)
359      {
360        UInt32 indices[] = { 3, 2, 0 };
361        UInt64 unpackSize = folder->UnpackSizes[ci];
362        si = indices[ci];
363        if (ci < 2)
364        {
365          Byte *temp;
366          outSizeCur = (SizeT)unpackSize;
367          if (outSizeCur != unpackSize)
368            return SZ_ERROR_MEM;
369          temp = (Byte *)IAlloc_Alloc(allocMain, outSizeCur);
370          if (temp == 0 && outSizeCur != 0)
371            return SZ_ERROR_MEM;
372          outBufCur = tempBuf[1 - ci] = temp;
373          tempSizes[1 - ci] = outSizeCur;
374        }
375        else if (ci == 2)
376        {
377          if (unpackSize > outSize) /* check it */
378            return SZ_ERROR_PARAM;
379          tempBuf3 = outBufCur = outBuffer + (outSize - (size_t)unpackSize);
380          tempSize3 = outSizeCur = (SizeT)unpackSize;
381        }
382        else
383          return SZ_ERROR_UNSUPPORTED;
384      }
385      offset = GetSum(packSizes, si);
386      inSize = packSizes[si];
387      RINOK(LookInStream_SeekTo(inStream, startPos + offset));
388 
389      if (coder->MethodID == k_Copy)
390      {
391        if (inSize != outSizeCur) /* check it */
392          return SZ_ERROR_DATA;
393        RINOK(SzDecodeCopy(inSize, inStream, outBufCur));
394      }
395      else if (coder->MethodID == k_LZMA)
396      {
397        RINOK(SzDecodeLzma(coder, inSize, inStream, outBufCur, outSizeCur, allocMain));
398      }
399      else if (coder->MethodID == k_LZMA2)
400      {
401        RINOK(SzDecodeLzma2(coder, inSize, inStream, outBufCur, outSizeCur, allocMain));
402      }
403      else
404      {
405        #ifdef _7ZIP_PPMD_SUPPPORT
406        RINOK(SzDecodePpmd(coder, inSize, inStream, outBufCur, outSizeCur, allocMain));
407        #else
408        return SZ_ERROR_UNSUPPORTED;
409        #endif
410      }
411    }
412    else if (coder->MethodID == k_BCJ2)
413    {
414      UInt64 offset = GetSum(packSizes, 1);
415      UInt64 s3Size = packSizes[1];
416      SRes res;
417      if (ci != 3)
418        return SZ_ERROR_UNSUPPORTED;
419      RINOK(LookInStream_SeekTo(inStream, startPos + offset));
420      tempSizes[2] = (SizeT)s3Size;
421      if (tempSizes[2] != s3Size)
422        return SZ_ERROR_MEM;
423      tempBuf[2] = (Byte *)IAlloc_Alloc(allocMain, tempSizes[2]);
424      if (tempBuf[2] == 0 && tempSizes[2] != 0)
425        return SZ_ERROR_MEM;
426      res = SzDecodeCopy(s3Size, inStream, tempBuf[2]);
427      RINOK(res)
428 
429      res = Bcj2_Decode(
430          tempBuf3, tempSize3,
431          tempBuf[0], tempSizes[0],
432          tempBuf[1], tempSizes[1],
433          tempBuf[2], tempSizes[2],
434          outBuffer, outSize);
435      RINOK(res)
436    }
437    else
438    {
439      if (ci != 1)
440        return SZ_ERROR_UNSUPPORTED;
441      switch(coder->MethodID)
442      {
443        case k_BCJ:
444        {
445          UInt32 state;
446          x86_Convert_Init(state);
447          x86_Convert(outBuffer, outSize, 0, &state, 0);
448          break;
449        }
450        CASE_BRA_CONV(ARM)
451        default:
452          return SZ_ERROR_UNSUPPORTED;
453      }
454    }
455  }
456  return SZ_OK;
457}
458 
459SRes SzFolder_Decode(const CSzFolder *folder, const UInt64 *packSizes,
460    ILookInStream *inStream, UInt64 startPos,
461    Byte *outBuffer, size_t outSize, ISzAlloc *allocMain)
462{
463  Byte *tempBuf[3] = { 0, 0, 0};
464  int i;
465  SRes res = SzFolder_Decode2(folder, packSizes, inStream, startPos,
466      outBuffer, (SizeT)outSize, allocMain, tempBuf);
467  for (i = 0; i < 3; i++)
468    IAlloc_Free(allocMain, tempBuf[i]);
469  return res;
470}
src/lib/lib7z/Sha256.h
r0r14440
1/* Sha256.h -- SHA-256 Hash
22010-06-11 : Igor Pavlov : Public domain */
3 
4#ifndef __CRYPTO_SHA256_H
5#define __CRYPTO_SHA256_H
6 
7#include "Types.h"
8 
9EXTERN_C_BEGIN
10 
11#define SHA256_DIGEST_SIZE 32
12 
13typedef struct
14{
15  UInt32 state[8];
16  UInt64 count;
17  Byte buffer[64];
18} CSha256;
19 
20void Sha256_Init(CSha256 *p);
21void Sha256_Update(CSha256 *p, const Byte *data, size_t size);
22void Sha256_Final(CSha256 *p, Byte *digest);
23 
24EXTERN_C_END
25 
26#endif
src/lib/lib7z/LzmaDec.c
r0r14440
1/* LzmaDec.c -- LZMA Decoder
22010-12-15 : Igor Pavlov : Public domain */
3 
4#include "LzmaDec.h"
5 
6#include <string.h>
7 
8#define kNumTopBits 24
9#define kTopValue ((UInt32)1 << kNumTopBits)
10 
11#define kNumBitModelTotalBits 11
12#define kBitModelTotal (1 << kNumBitModelTotalBits)
13#define kNumMoveBits 5
14 
15#define RC_INIT_SIZE 5
16 
17#define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); }
18 
19#define IF_BIT_0(p) ttt = *(p); NORMALIZE; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound)
20#define UPDATE_0(p) range = bound; *(p) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits));
21#define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits));
22#define GET_BIT2(p, i, A0, A1) IF_BIT_0(p) \
23  { UPDATE_0(p); i = (i + i); A0; } else \
24  { UPDATE_1(p); i = (i + i) + 1; A1; }
25#define GET_BIT(p, i) GET_BIT2(p, i, ; , ;)
26 
27#define TREE_GET_BIT(probs, i) { GET_BIT((probs + i), i); }
28#define TREE_DECODE(probs, limit, i) \
29  { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; }
30 
31/* #define _LZMA_SIZE_OPT */
32 
33#ifdef _LZMA_SIZE_OPT
34#define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i)
35#else
36#define TREE_6_DECODE(probs, i) \
37  { i = 1; \
38  TREE_GET_BIT(probs, i); \
39  TREE_GET_BIT(probs, i); \
40  TREE_GET_BIT(probs, i); \
41  TREE_GET_BIT(probs, i); \
42  TREE_GET_BIT(probs, i); \
43  TREE_GET_BIT(probs, i); \
44  i -= 0x40; }
45#endif
46 
47#define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_ERROR; range <<= 8; code = (code << 8) | (*buf++); }
48 
49#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound)
50#define UPDATE_0_CHECK range = bound;
51#define UPDATE_1_CHECK range -= bound; code -= bound;
52#define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p) \
53  { UPDATE_0_CHECK; i = (i + i); A0; } else \
54  { UPDATE_1_CHECK; i = (i + i) + 1; A1; }
55#define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ; , ;)
56#define TREE_DECODE_CHECK(probs, limit, i) \
57  { i = 1; do { GET_BIT_CHECK(probs + i, i) } while (i < limit); i -= limit; }
58 
59 
60#define kNumPosBitsMax 4
61#define kNumPosStatesMax (1 << kNumPosBitsMax)
62 
63#define kLenNumLowBits 3
64#define kLenNumLowSymbols (1 << kLenNumLowBits)
65#define kLenNumMidBits 3
66#define kLenNumMidSymbols (1 << kLenNumMidBits)
67#define kLenNumHighBits 8
68#define kLenNumHighSymbols (1 << kLenNumHighBits)
69 
70#define LenChoice 0
71#define LenChoice2 (LenChoice + 1)
72#define LenLow (LenChoice2 + 1)
73#define LenMid (LenLow + (kNumPosStatesMax << kLenNumLowBits))
74#define LenHigh (LenMid + (kNumPosStatesMax << kLenNumMidBits))
75#define kNumLenProbs (LenHigh + kLenNumHighSymbols)
76 
77 
78#define kNumStates 12
79#define kNumLitStates 7
80 
81#define kStartPosModelIndex 4
82#define kEndPosModelIndex 14
83#define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
84 
85#define kNumPosSlotBits 6
86#define kNumLenToPosStates 4
87 
88#define kNumAlignBits 4
89#define kAlignTableSize (1 << kNumAlignBits)
90 
91#define kMatchMinLen 2
92#define kMatchSpecLenStart (kMatchMinLen + kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols)
93 
94#define IsMatch 0
95#define IsRep (IsMatch + (kNumStates << kNumPosBitsMax))
96#define IsRepG0 (IsRep + kNumStates)
97#define IsRepG1 (IsRepG0 + kNumStates)
98#define IsRepG2 (IsRepG1 + kNumStates)
99#define IsRep0Long (IsRepG2 + kNumStates)
100#define PosSlot (IsRep0Long + (kNumStates << kNumPosBitsMax))
101#define SpecPos (PosSlot + (kNumLenToPosStates << kNumPosSlotBits))
102#define Align (SpecPos + kNumFullDistances - kEndPosModelIndex)
103#define LenCoder (Align + kAlignTableSize)
104#define RepLenCoder (LenCoder + kNumLenProbs)
105#define Literal (RepLenCoder + kNumLenProbs)
106 
107#define LZMA_BASE_SIZE 1846
108#define LZMA_LIT_SIZE 768
109 
110#define LzmaProps_GetNumProbs(p) ((UInt32)LZMA_BASE_SIZE + (LZMA_LIT_SIZE << ((p)->lc + (p)->lp)))
111 
112#if Literal != LZMA_BASE_SIZE
113StopCompilingDueBUG
114#endif
115 
116#define LZMA_DIC_MIN (1 << 12)
117 
118/* First LZMA-symbol is always decoded.
119And it decodes new LZMA-symbols while (buf < bufLimit), but "buf" is without last normalization
120Out:
121  Result:
122    SZ_OK - OK
123    SZ_ERROR_DATA - Error
124  p->remainLen:
125    < kMatchSpecLenStart : normal remain
126    = kMatchSpecLenStart : finished
127    = kMatchSpecLenStart + 1 : Flush marker
128    = kMatchSpecLenStart + 2 : State Init Marker
129*/
130 
131static int MY_FAST_CALL LzmaDec_DecodeReal(CLzmaDec *p, SizeT limit, const Byte *bufLimit)
132{
133  CLzmaProb *probs = p->probs;
134 
135  unsigned state = p->state;
136  UInt32 rep0 = p->reps[0], rep1 = p->reps[1], rep2 = p->reps[2], rep3 = p->reps[3];
137  unsigned pbMask = ((unsigned)1 << (p->prop.pb)) - 1;
138  unsigned lpMask = ((unsigned)1 << (p->prop.lp)) - 1;
139  unsigned lc = p->prop.lc;
140 
141  Byte *dic = p->dic;
142  SizeT dicBufSize = p->dicBufSize;
143  SizeT dicPos = p->dicPos;
144   
145  UInt32 processedPos = p->processedPos;
146  UInt32 checkDicSize = p->checkDicSize;
147  unsigned len = 0;
148 
149  const Byte *buf = p->buf;
150  UInt32 range = p->range;
151  UInt32 code = p->code;
152 
153  do
154  {
155    CLzmaProb *prob;
156    UInt32 bound;
157    unsigned ttt;
158    unsigned posState = processedPos & pbMask;
159 
160    prob = probs + IsMatch + (state << kNumPosBitsMax) + posState;
161    IF_BIT_0(prob)
162    {
163      unsigned symbol;
164      UPDATE_0(prob);
165      prob = probs + Literal;
166      if (checkDicSize != 0 || processedPos != 0)
167        prob += (LZMA_LIT_SIZE * (((processedPos & lpMask) << lc) +
168        (dic[(dicPos == 0 ? dicBufSize : dicPos) - 1] >> (8 - lc))));
169 
170      if (state < kNumLitStates)
171      {
172        state -= (state < 4) ? state : 3;
173        symbol = 1;
174        do { GET_BIT(prob + symbol, symbol) } while (symbol < 0x100);
175      }
176      else
177      {
178        unsigned matchByte = p->dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
179        unsigned offs = 0x100;
180        state -= (state < 10) ? 3 : 6;
181        symbol = 1;
182        do
183        {
184          unsigned bit;
185          CLzmaProb *probLit;
186          matchByte <<= 1;
187          bit = (matchByte & offs);
188          probLit = prob + offs + bit + symbol;
189          GET_BIT2(probLit, symbol, offs &= ~bit, offs &= bit)
190        }
191        while (symbol < 0x100);
192      }
193      dic[dicPos++] = (Byte)symbol;
194      processedPos++;
195      continue;
196    }
197    else
198    {
199      UPDATE_1(prob);
200      prob = probs + IsRep + state;
201      IF_BIT_0(prob)
202      {
203        UPDATE_0(prob);
204        state += kNumStates;
205        prob = probs + LenCoder;
206      }
207      else
208      {
209        UPDATE_1(prob);
210        if (checkDicSize == 0 && processedPos == 0)
211          return SZ_ERROR_DATA;
212        prob = probs + IsRepG0 + state;
213        IF_BIT_0(prob)
214        {
215          UPDATE_0(prob);
216          prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState;
217          IF_BIT_0(prob)
218          {
219            UPDATE_0(prob);
220            dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
221            dicPos++;
222            processedPos++;
223            state = state < kNumLitStates ? 9 : 11;
224            continue;
225          }
226          UPDATE_1(prob);
227        }
228        else
229        {
230          UInt32 distance;
231          UPDATE_1(prob);
232          prob = probs + IsRepG1 + state;
233          IF_BIT_0(prob)
234          {
235            UPDATE_0(prob);
236            distance = rep1;
237          }
238          else
239          {
240            UPDATE_1(prob);
241            prob = probs + IsRepG2 + state;
242            IF_BIT_0(prob)
243            {
244              UPDATE_0(prob);
245              distance = rep2;
246            }
247            else
248            {
249              UPDATE_1(prob);
250              distance = rep3;
251              rep3 = rep2;
252            }
253            rep2 = rep1;
254          }
255          rep1 = rep0;
256          rep0 = distance;
257        }
258        state = state < kNumLitStates ? 8 : 11;
259        prob = probs + RepLenCoder;
260      }
261      {
262        unsigned limit, offset;
263        CLzmaProb *probLen = prob + LenChoice;
264        IF_BIT_0(probLen)
265        {
266          UPDATE_0(probLen);
267          probLen = prob + LenLow + (posState << kLenNumLowBits);
268          offset = 0;
269          limit = (1 << kLenNumLowBits);
270        }
271        else
272        {
273          UPDATE_1(probLen);
274          probLen = prob + LenChoice2;
275          IF_BIT_0(probLen)
276          {
277            UPDATE_0(probLen);
278            probLen = prob + LenMid + (posState << kLenNumMidBits);
279            offset = kLenNumLowSymbols;
280            limit = (1 << kLenNumMidBits);
281          }
282          else
283          {
284            UPDATE_1(probLen);
285            probLen = prob + LenHigh;
286            offset = kLenNumLowSymbols + kLenNumMidSymbols;
287            limit = (1 << kLenNumHighBits);
288          }
289        }
290        TREE_DECODE(probLen, limit, len);
291        len += offset;
292      }
293 
294      if (state >= kNumStates)
295      {
296        UInt32 distance;
297        prob = probs + PosSlot +
298            ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits);
299        TREE_6_DECODE(prob, distance);
300        if (distance >= kStartPosModelIndex)
301        {
302          unsigned posSlot = (unsigned)distance;
303          int numDirectBits = (int)(((distance >> 1) - 1));
304          distance = (2 | (distance & 1));
305          if (posSlot < kEndPosModelIndex)
306          {
307            distance <<= numDirectBits;
308            prob = probs + SpecPos + distance - posSlot - 1;
309            {
310              UInt32 mask = 1;
311              unsigned i = 1;
312              do
313              {
314                GET_BIT2(prob + i, i, ; , distance |= mask);
315                mask <<= 1;
316              }
317              while (--numDirectBits != 0);
318            }
319          }
320          else
321          {
322            numDirectBits -= kNumAlignBits;
323            do
324            {
325              NORMALIZE
326              range >>= 1;
327               
328              {
329                UInt32 t;
330                code -= range;
331                t = (0 - ((UInt32)code >> 31)); /* (UInt32)((Int32)code >> 31) */
332                distance = (distance << 1) + (t + 1);
333                code += range & t;
334              }
335              /*
336              distance <<= 1;
337              if (code >= range)
338              {
339                code -= range;
340                distance |= 1;
341              }
342              */
343            }
344            while (--numDirectBits != 0);
345            prob = probs + Align;
346            distance <<= kNumAlignBits;
347            {
348              unsigned i = 1;
349              GET_BIT2(prob + i, i, ; , distance |= 1);
350              GET_BIT2(prob + i, i, ; , distance |= 2);
351              GET_BIT2(prob + i, i, ; , distance |= 4);
352              GET_BIT2(prob + i, i, ; , distance |= 8);
353            }
354            if (distance == (UInt32)0xFFFFFFFF)
355            {
356              len += kMatchSpecLenStart;
357              state -= kNumStates;
358              break;
359            }
360          }
361        }
362        rep3 = rep2;
363        rep2 = rep1;
364        rep1 = rep0;
365        rep0 = distance + 1;
366        if (checkDicSize == 0)
367        {
368          if (distance >= processedPos)
369            return SZ_ERROR_DATA;
370        }
371        else if (distance >= checkDicSize)
372          return SZ_ERROR_DATA;
373        state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3;
374      }
375 
376      len += kMatchMinLen;
377 
378      if (limit == dicPos)
379        return SZ_ERROR_DATA;
380      {
381        SizeT rem = limit - dicPos;
382        unsigned curLen = ((rem < len) ? (unsigned)rem : len);
383        SizeT pos = (dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0);
384 
385        processedPos += curLen;
386 
387        len -= curLen;
388        if (pos + curLen <= dicBufSize)
389        {
390          Byte *dest = dic + dicPos;
391          ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos;
392          const Byte *lim = dest + curLen;
393          dicPos += curLen;
394          do
395            *(dest) = (Byte)*(dest + src);
396          while (++dest != lim);
397        }
398        else
399        {
400          do
401          {
402            dic[dicPos++] = dic[pos];
403            if (++pos == dicBufSize)
404              pos = 0;
405          }
406          while (--curLen != 0);
407        }
408      }
409    }
410  }
411  while (dicPos < limit && buf < bufLimit);
412  NORMALIZE;
413  p->buf = buf;
414  p->range = range;
415  p->code = code;
416  p->remainLen = len;
417  p->dicPos = dicPos;
418  p->processedPos = processedPos;
419  p->reps[0] = rep0;
420  p->reps[1] = rep1;
421  p->reps[2] = rep2;
422  p->reps[3] = rep3;
423  p->state = state;
424 
425  return SZ_OK;
426}
427 
428static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit)
429{
430  if (p->remainLen != 0 && p->remainLen < kMatchSpecLenStart)
431  {
432    Byte *dic = p->dic;
433    SizeT dicPos = p->dicPos;
434    SizeT dicBufSize = p->dicBufSize;
435    unsigned len = p->remainLen;
436    UInt32 rep0 = p->reps[0];
437    if (limit - dicPos < len)
438      len = (unsigned)(limit - dicPos);
439 
440    if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= len)
441      p->checkDicSize = p->prop.dicSize;
442 
443    p->processedPos += len;
444    p->remainLen -= len;
445    while (len != 0)
446    {
447      len--;
448      dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
449      dicPos++;
450    }
451    p->dicPos = dicPos;
452  }
453}
454 
455static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit)
456{
457  do
458  {
459    SizeT limit2 = limit;
460    if (p->checkDicSize == 0)
461    {
462      UInt32 rem = p->prop.dicSize - p->processedPos;
463      if (limit - p->dicPos > rem)
464        limit2 = p->dicPos + rem;
465    }
466    RINOK(LzmaDec_DecodeReal(p, limit2, bufLimit));
467    if (p->processedPos >= p->prop.dicSize)
468      p->checkDicSize = p->prop.dicSize;
469    LzmaDec_WriteRem(p, limit);
470  }
471  while (p->dicPos < limit && p->buf < bufLimit && p->remainLen < kMatchSpecLenStart);
472 
473  if (p->remainLen > kMatchSpecLenStart)
474  {
475    p->remainLen = kMatchSpecLenStart;
476  }
477  return 0;
478}
479 
480typedef enum
481{
482  DUMMY_ERROR, /* unexpected end of input stream */
483  DUMMY_LIT,
484  DUMMY_MATCH,
485  DUMMY_REP
486} ELzmaDummy;
487 
488static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, SizeT inSize)
489{
490  UInt32 range = p->range;
491  UInt32 code = p->code;
492  const Byte *bufLimit = buf + inSize;
493  CLzmaProb *probs = p->probs;
494  unsigned state = p->state;
495  ELzmaDummy res;
496 
497  {
498    CLzmaProb *prob;
499    UInt32 bound;
500    unsigned ttt;
501    unsigned posState = (p->processedPos) & ((1 << p->prop.pb) - 1);
502 
503    prob = probs + IsMatch + (state << kNumPosBitsMax) + posState;
504    IF_BIT_0_CHECK(prob)
505    {
506      UPDATE_0_CHECK
507 
508      /* if (bufLimit - buf >= 7) return DUMMY_LIT; */
509 
510      prob = probs + Literal;
511      if (p->checkDicSize != 0 || p->processedPos != 0)
512        prob += (LZMA_LIT_SIZE *
513          ((((p->processedPos) & ((1 << (p->prop.lp)) - 1)) << p->prop.lc) +
514          (p->dic[(p->dicPos == 0 ? p->dicBufSize : p->dicPos) - 1] >> (8 - p->prop.lc))));
515 
516      if (state < kNumLitStates)
517      {
518        unsigned symbol = 1;
519        do { GET_BIT_CHECK(prob + symbol, symbol) } while (symbol < 0x100);
520      }
521      else
522      {
523        unsigned matchByte = p->dic[p->dicPos - p->reps[0] +
524            ((p->dicPos < p->reps[0]) ? p->dicBufSize : 0)];
525        unsigned offs = 0x100;
526        unsigned symbol = 1;
527        do
528        {
529          unsigned bit;
530          CLzmaProb *probLit;
531          matchByte <<= 1;
532          bit = (matchByte & offs);
533          probLit = prob + offs + bit + symbol;
534          GET_BIT2_CHECK(probLit, symbol, offs &= ~bit, offs &= bit)
535        }
536        while (symbol < 0x100);
537      }
538      res = DUMMY_LIT;
539    }
540    else
541    {
542      unsigned len;
543      UPDATE_1_CHECK;
544 
545      prob = probs + IsRep + state;
546      IF_BIT_0_CHECK(prob)
547      {
548        UPDATE_0_CHECK;
549        state = 0;
550        prob = probs + LenCoder;
551        res = DUMMY_MATCH;
552      }
553      else
554      {
555        UPDATE_1_CHECK;
556        res = DUMMY_REP;
557        prob = probs + IsRepG0 + state;
558        IF_BIT_0_CHECK(prob)
559        {
560          UPDATE_0_CHECK;
561          prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState;
562          IF_BIT_0_CHECK(prob)
563          {
564            UPDATE_0_CHECK;
565            NORMALIZE_CHECK;
566            return DUMMY_REP;
567          }
568          else
569          {
570            UPDATE_1_CHECK;
571          }
572        }
573        else
574        {
575          UPDATE_1_CHECK;
576          prob = probs + IsRepG1 + state;
577          IF_BIT_0_CHECK(prob)
578          {
579            UPDATE_0_CHECK;
580          }
581          else
582          {
583            UPDATE_1_CHECK;
584            prob = probs + IsRepG2 + state;
585            IF_BIT_0_CHECK(prob)
586            {
587              UPDATE_0_CHECK;
588            }
589            else
590            {
591              UPDATE_1_CHECK;
592            }
593          }
594        }
595        state = kNumStates;
596        prob = probs + RepLenCoder;
597      }
598      {
599        unsigned limit, offset;
600        CLzmaProb *probLen = prob + LenChoice;
601        IF_BIT_0_CHECK(probLen)
602        {
603          UPDATE_0_CHECK;
604          probLen = prob + LenLow + (posState << kLenNumLowBits);
605          offset = 0;
606          limit = 1 << kLenNumLowBits;
607        }
608        else
609        {
610          UPDATE_1_CHECK;
611          probLen = prob + LenChoice2;
612          IF_BIT_0_CHECK(probLen)
613          {
614            UPDATE_0_CHECK;
615            probLen = prob + LenMid + (posState << kLenNumMidBits);
616            offset = kLenNumLowSymbols;
617            limit = 1 << kLenNumMidBits;
618          }
619          else
620          {
621            UPDATE_1_CHECK;
622            probLen = prob + LenHigh;
623            offset = kLenNumLowSymbols + kLenNumMidSymbols;
624            limit = 1 << kLenNumHighBits;
625          }
626        }
627        TREE_DECODE_CHECK(probLen, limit, len);
628        len += offset;
629      }
630 
631      if (state < 4)
632      {
633        unsigned posSlot;
634        prob = probs + PosSlot +
635            ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) <<
636            kNumPosSlotBits);
637        TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot);
638        if (posSlot >= kStartPosModelIndex)
639        {
640          int numDirectBits = ((posSlot >> 1) - 1);
641 
642          /* if (bufLimit - buf >= 8) return DUMMY_MATCH; */
643 
644          if (posSlot < kEndPosModelIndex)
645          {
646            prob = probs + SpecPos + ((2 | (posSlot & 1)) << numDirectBits) - posSlot - 1;
647          }
648          else
649          {
650            numDirectBits -= kNumAlignBits;
651            do
652            {
653              NORMALIZE_CHECK
654              range >>= 1;
655              code -= range & (((code - range) >> 31) - 1);
656              /* if (code >= range) code -= range; */
657            }
658            while (--numDirectBits != 0);
659            prob = probs + Align;
660            numDirectBits = kNumAlignBits;
661          }
662          {
663            unsigned i = 1;
664            do
665            {
666              GET_BIT_CHECK(prob + i, i);
667            }
668            while (--numDirectBits != 0);
669          }
670        }
671      }
672    }
673  }
674  NORMALIZE_CHECK;
675  return res;
676}
677 
678 
679static void LzmaDec_InitRc(CLzmaDec *p, const Byte *data)
680{
681  p->code = ((UInt32)data[1] << 24) | ((UInt32)data[2] << 16) | ((UInt32)data[3] << 8) | ((UInt32)data[4]);
682  p->range = 0xFFFFFFFF;
683  p->needFlush = 0;
684}
685 
686void LzmaDec_InitDicAndState(CLzmaDec *p, Bool initDic, Bool initState)
687{
688  p->needFlush = 1;
689  p->remainLen = 0;
690  p->tempBufSize = 0;
691 
692  if (initDic)
693  {
694    p->processedPos = 0;
695    p->checkDicSize = 0;
696    p->needInitState = 1;
697  }
698  if (initState)
699    p->needInitState = 1;
700}
701 
702void LzmaDec_Init(CLzmaDec *p)
703{
704  p->dicPos = 0;
705  LzmaDec_InitDicAndState(p, True, True);
706}
707 
708static void LzmaDec_InitStateReal(CLzmaDec *p)
709{
710  UInt32 numProbs = Literal + ((UInt32)LZMA_LIT_SIZE << (p->prop.lc + p->prop.lp));
711  UInt32 i;
712  CLzmaProb *probs = p->probs;
713  for (i = 0; i < numProbs; i++)
714    probs[i] = kBitModelTotal >> 1;
715  p->reps[0] = p->reps[1] = p->reps[2] = p->reps[3] = 1;
716  p->state = 0;
717  p->needInitState = 0;
718}
719 
720SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *srcLen,
721    ELzmaFinishMode finishMode, ELzmaStatus *status)
722{
723  SizeT inSize = *srcLen;
724  (*srcLen) = 0;
725  LzmaDec_WriteRem(p, dicLimit);
726   
727  *status = LZMA_STATUS_NOT_SPECIFIED;
728 
729  while (p->remainLen != kMatchSpecLenStart)
730  {
731      int checkEndMarkNow;
732 
733      if (p->needFlush != 0)
734      {
735        for (; inSize > 0 && p->tempBufSize < RC_INIT_SIZE; (*srcLen)++, inSize--)
736          p->tempBuf[p->tempBufSize++] = *src++;
737        if (p->tempBufSize < RC_INIT_SIZE)
738        {
739          *status = LZMA_STATUS_NEEDS_MORE_INPUT;
740          return SZ_OK;
741        }
742        if (p->tempBuf[0] != 0)
743          return SZ_ERROR_DATA;
744 
745        LzmaDec_InitRc(p, p->tempBuf);
746        p->tempBufSize = 0;
747      }
748 
749      checkEndMarkNow = 0;
750      if (p->dicPos >= dicLimit)
751      {
752        if (p->remainLen == 0 && p->code == 0)
753        {
754          *status = LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK;
755          return SZ_OK;
756        }
757        if (finishMode == LZMA_FINISH_ANY)
758        {
759          *status = LZMA_STATUS_NOT_FINISHED;
760          return SZ_OK;
761        }
762        if (p->remainLen != 0)
763        {
764          *status = LZMA_STATUS_NOT_FINISHED;
765          return SZ_ERROR_DATA;
766        }
767        checkEndMarkNow = 1;
768      }
769 
770      if (p->needInitState)
771        LzmaDec_InitStateReal(p);
772   
773      if (p->tempBufSize == 0)
774      {
775        SizeT processed;
776        const Byte *bufLimit;
777        if (inSize < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow)
778        {
779          int dummyRes = LzmaDec_TryDummy(p, src, inSize);
780          if (dummyRes == DUMMY_ERROR)
781          {
782            memcpy(p->tempBuf, src, inSize);
783            p->tempBufSize = (unsigned)inSize;
784            (*srcLen) += inSize;
785            *status = LZMA_STATUS_NEEDS_MORE_INPUT;
786            return SZ_OK;
787          }
788          if (checkEndMarkNow && dummyRes != DUMMY_MATCH)
789          {
790            *status = LZMA_STATUS_NOT_FINISHED;
791            return SZ_ERROR_DATA;
792          }
793          bufLimit = src;
794        }
795        else
796          bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX;
797        p->buf = src;
798        if (LzmaDec_DecodeReal2(p, dicLimit, bufLimit) != 0)
799          return SZ_ERROR_DATA;
800        processed = (SizeT)(p->buf - src);
801        (*srcLen) += processed;
802        src += processed;
803        inSize -= processed;
804      }
805      else
806      {
807        unsigned rem = p->tempBufSize, lookAhead = 0;
808        while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize)
809          p->tempBuf[rem++] = src[lookAhead++];
810        p->tempBufSize = rem;
811        if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow)
812        {
813          int dummyRes = LzmaDec_TryDummy(p, p->tempBuf, rem);
814          if (dummyRes == DUMMY_ERROR)
815          {
816            (*srcLen) += lookAhead;
817            *status = LZMA_STATUS_NEEDS_MORE_INPUT;
818            return SZ_OK;
819          }
820          if (checkEndMarkNow && dummyRes != DUMMY_MATCH)
821          {
822            *status = LZMA_STATUS_NOT_FINISHED;
823            return SZ_ERROR_DATA;
824          }
825        }
826        p->buf = p->tempBuf;
827        if (LzmaDec_DecodeReal2(p, dicLimit, p->buf) != 0)
828          return SZ_ERROR_DATA;
829        lookAhead -= (rem - (unsigned)(p->buf - p->tempBuf));
830        (*srcLen) += lookAhead;
831        src += lookAhead;
832        inSize -= lookAhead;
833        p->tempBufSize = 0;
834      }
835  }
836  if (p->code == 0)
837    *status = LZMA_STATUS_FINISHED_WITH_MARK;
838  return (p->code == 0) ? SZ_OK : SZ_ERROR_DATA;
839}
840 
841SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status)
842{
843  SizeT outSize = *destLen;
844  SizeT inSize = *srcLen;
845  *srcLen = *destLen = 0;
846  for (;;)
847  {
848    SizeT inSizeCur = inSize, outSizeCur, dicPos;
849    ELzmaFinishMode curFinishMode;
850    SRes res;
851    if (p->dicPos == p->dicBufSize)
852      p->dicPos = 0;
853    dicPos = p->dicPos;
854    if (outSize > p->dicBufSize - dicPos)
855    {
856      outSizeCur = p->dicBufSize;
857      curFinishMode = LZMA_FINISH_ANY;
858    }
859    else
860    {
861      outSizeCur = dicPos + outSize;
862      curFinishMode = finishMode;
863    }
864 
865    res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status);
866    src += inSizeCur;
867    inSize -= inSizeCur;
868    *srcLen += inSizeCur;
869    outSizeCur = p->dicPos - dicPos;
870    memcpy(dest, p->dic + dicPos, outSizeCur);
871    dest += outSizeCur;
872    outSize -= outSizeCur;
873    *destLen += outSizeCur;
874    if (res != 0)
875      return res;
876    if (outSizeCur == 0 || outSize == 0)
877      return SZ_OK;
878  }
879}
880 
881void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc)
882{
883  alloc->Free(alloc, p->probs);
884  p->probs = 0;
885}
886 
887static void LzmaDec_FreeDict(CLzmaDec *p, ISzAlloc *alloc)
888{
889  alloc->Free(alloc, p->dic);
890  p->dic = 0;
891}
892 
893void LzmaDec_Free(CLzmaDec *p, ISzAlloc *alloc)
894{
895  LzmaDec_FreeProbs(p, alloc);
896  LzmaDec_FreeDict(p, alloc);
897}
898 
899SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size)
900{
901  UInt32 dicSize;
902  Byte d;
903   
904  if (size < LZMA_PROPS_SIZE)
905    return SZ_ERROR_UNSUPPORTED;
906  else
907    dicSize = data[1] | ((UInt32)data[2] << 8) | ((UInt32)data[3] << 16) | ((UInt32)data[4] << 24);
908 
909  if (dicSize < LZMA_DIC_MIN)
910    dicSize = LZMA_DIC_MIN;
911  p->dicSize = dicSize;
912 
913  d = data[0];
914  if (d >= (9 * 5 * 5))
915    return SZ_ERROR_UNSUPPORTED;
916 
917  p->lc = d % 9;
918  d /= 9;
919  p->pb = d / 5;
920  p->lp = d % 5;
921 
922  return SZ_OK;
923}
924 
925static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAlloc *alloc)
926{
927  UInt32 numProbs = LzmaProps_GetNumProbs(propNew);
928  if (p->probs == 0 || numProbs != p->numProbs)
929  {
930    LzmaDec_FreeProbs(p, alloc);
931    p->probs = (CLzmaProb *)alloc->Alloc(alloc, numProbs * sizeof(CLzmaProb));
932    p->numProbs = numProbs;
933    if (p->probs == 0)
934      return SZ_ERROR_MEM;
935  }
936  return SZ_OK;
937}
938 
939SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc)
940{
941  CLzmaProps propNew;
942  RINOK(LzmaProps_Decode(&propNew, props, propsSize));
943  RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc));
944  p->prop = propNew;
945  return SZ_OK;
946}
947 
948SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc)
949{
950  CLzmaProps propNew;
951  SizeT dicBufSize;
952  RINOK(LzmaProps_Decode(&propNew, props, propsSize));
953  RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc));
954  dicBufSize = propNew.dicSize;
955  if (p->dic == 0 || dicBufSize != p->dicBufSize)
956  {
957    LzmaDec_FreeDict(p, alloc);
958    p->dic = (Byte *)alloc->Alloc(alloc, dicBufSize);
959    if (p->dic == 0)
960    {
961      LzmaDec_FreeProbs(p, alloc);
962      return SZ_ERROR_MEM;
963    }
964  }
965  p->dicBufSize = dicBufSize;
966  p->prop = propNew;
967  return SZ_OK;
968}
969 
970SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
971    const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode,
972    ELzmaStatus *status, ISzAlloc *alloc)
973{
974  CLzmaDec p;
975  SRes res;
976  SizeT outSize = *destLen, inSize = *srcLen;
977  *destLen = *srcLen = 0;
978  *status = LZMA_STATUS_NOT_SPECIFIED;
979  if (inSize < RC_INIT_SIZE)
980    return SZ_ERROR_INPUT_EOF;
981  LzmaDec_Construct(&p);
982  RINOK(LzmaDec_AllocateProbs(&p, propData, propSize, alloc));
983  p.dic = dest;
984  p.dicBufSize = outSize;
985  LzmaDec_Init(&p);
986  *srcLen = inSize;
987  res = LzmaDec_DecodeToDic(&p, outSize, src, srcLen, finishMode, status);
988  *destLen = p.dicPos;
989  if (res == SZ_OK && *status == LZMA_STATUS_NEEDS_MORE_INPUT)
990    res = SZ_ERROR_INPUT_EOF;
991  LzmaDec_FreeProbs(&p, alloc);
992  return res;
993}
src/lib/lib7z/LzmaDec.h
r0r14440
1/* LzmaDec.h -- LZMA Decoder
22009-02-07 : Igor Pavlov : Public domain */
3 
4#ifndef __LZMA_DEC_H
5#define __LZMA_DEC_H
6 
7#include "Types.h"
8 
9#ifdef __cplusplus
10extern "C" {
11#endif
12 
13/* #define _LZMA_PROB32 */
14/* _LZMA_PROB32 can increase the speed on some CPUs,
15   but memory usage for CLzmaDec::probs will be doubled in that case */
16 
17#ifdef _LZMA_PROB32
18#define CLzmaProb UInt32
19#else
20#define CLzmaProb UInt16
21#endif
22 
23 
24/* ---------- LZMA Properties ---------- */
25 
26#define LZMA_PROPS_SIZE 5
27 
28typedef struct _CLzmaProps
29{
30  unsigned lc, lp, pb;
31  UInt32 dicSize;
32} CLzmaProps;
33 
34/* LzmaProps_Decode - decodes properties
35Returns:
36  SZ_OK
37  SZ_ERROR_UNSUPPORTED - Unsupported properties
38*/
39 
40SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size);
41 
42 
43/* ---------- LZMA Decoder state ---------- */
44 
45/* LZMA_REQUIRED_INPUT_MAX = number of required input bytes for worst case.
46   Num bits = log2((2^11 / 31) ^ 22) + 26 < 134 + 26 = 160; */
47 
48#define LZMA_REQUIRED_INPUT_MAX 20
49 
50typedef struct
51{
52  CLzmaProps prop;
53  CLzmaProb *probs;
54  Byte *dic;
55  const Byte *buf;
56  UInt32 range, code;
57  SizeT dicPos;
58  SizeT dicBufSize;
59  UInt32 processedPos;
60  UInt32 checkDicSize;
61  unsigned state;
62  UInt32 reps[4];
63  unsigned remainLen;
64  int needFlush;
65  int needInitState;
66  UInt32 numProbs;
67  unsigned tempBufSize;
68  Byte tempBuf[LZMA_REQUIRED_INPUT_MAX];
69} CLzmaDec;
70 
71#define LzmaDec_Construct(p) { (p)->dic = 0; (p)->probs = 0; }
72 
73void LzmaDec_Init(CLzmaDec *p);
74 
75/* There are two types of LZMA streams:
76     0) Stream with end mark. That end mark adds about 6 bytes to compressed size.
77     1) Stream without end mark. You must know exact uncompressed size to decompress such stream. */
78 
79typedef enum
80{
81  LZMA_FINISH_ANY,   /* finish at any point */
82  LZMA_FINISH_END    /* block must be finished at the end */
83} ELzmaFinishMode;
84 
85/* ELzmaFinishMode has meaning only if the decoding reaches output limit !!!
86 
87   You must use LZMA_FINISH_END, when you know that current output buffer
88   covers last bytes of block. In other cases you must use LZMA_FINISH_ANY.
89 
90   If LZMA decoder sees end marker before reaching output limit, it returns SZ_OK,
91   and output value of destLen will be less than output buffer size limit.
92   You can check status result also.
93 
94   You can use multiple checks to test data integrity after full decompression:
95     1) Check Result and "status" variable.
96     2) Check that output(destLen) = uncompressedSize, if you know real uncompressedSize.
97     3) Check that output(srcLen) = compressedSize, if you know real compressedSize.
98        You must use correct finish mode in that case. */
99 
100typedef enum
101{
102  LZMA_STATUS_NOT_SPECIFIED,               /* use main error code instead */
103  LZMA_STATUS_FINISHED_WITH_MARK,          /* stream was finished with end mark. */
104  LZMA_STATUS_NOT_FINISHED,                /* stream was not finished */
105  LZMA_STATUS_NEEDS_MORE_INPUT,            /* you must provide more input bytes */
106  LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK  /* there is probability that stream was finished without end mark */
107} ELzmaStatus;
108 
109/* ELzmaStatus is used only as output value for function call */
110 
111 
112/* ---------- Interfaces ---------- */
113 
114/* There are 3 levels of interfaces:
115     1) Dictionary Interface
116     2) Buffer Interface
117     3) One Call Interface
118   You can select any of these interfaces, but don't mix functions from different
119   groups for same object. */
120 
121 
122/* There are two variants to allocate state for Dictionary Interface:
123     1) LzmaDec_Allocate / LzmaDec_Free
124     2) LzmaDec_AllocateProbs / LzmaDec_FreeProbs
125   You can use variant 2, if you set dictionary buffer manually.
126   For Buffer Interface you must always use variant 1.
127 
128LzmaDec_Allocate* can return:
129  SZ_OK
130  SZ_ERROR_MEM         - Memory allocation error
131  SZ_ERROR_UNSUPPORTED - Unsupported properties
132*/
133   
134SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc);
135void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc);
136 
137SRes LzmaDec_Allocate(CLzmaDec *state, const Byte *prop, unsigned propsSize, ISzAlloc *alloc);
138void LzmaDec_Free(CLzmaDec *state, ISzAlloc *alloc);
139 
140/* ---------- Dictionary Interface ---------- */
141 
142/* You can use it, if you want to eliminate the overhead for data copying from
143   dictionary to some other external buffer.
144   You must work with CLzmaDec variables directly in this interface.
145 
146   STEPS:
147     LzmaDec_Constr()
148     LzmaDec_Allocate()
149     for (each new stream)
150     {
151       LzmaDec_Init()
152       while (it needs more decompression)
153       {
154         LzmaDec_DecodeToDic()
155         use data from CLzmaDec::dic and update CLzmaDec::dicPos
156       }
157     }
158     LzmaDec_Free()
159*/
160 
161/* LzmaDec_DecodeToDic
162   
163   The decoding to internal dictionary buffer (CLzmaDec::dic).
164   You must manually update CLzmaDec::dicPos, if it reaches CLzmaDec::dicBufSize !!!
165 
166finishMode:
167  It has meaning only if the decoding reaches output limit (dicLimit).
168  LZMA_FINISH_ANY - Decode just dicLimit bytes.
169  LZMA_FINISH_END - Stream must be finished after dicLimit.
170 
171Returns:
172  SZ_OK
173    status:
174      LZMA_STATUS_FINISHED_WITH_MARK
175      LZMA_STATUS_NOT_FINISHED
176      LZMA_STATUS_NEEDS_MORE_INPUT
177      LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
178  SZ_ERROR_DATA - Data error
179*/
180 
181SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit,
182    const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
183 
184 
185/* ---------- Buffer Interface ---------- */
186 
187/* It's zlib-like interface.
188   See LzmaDec_DecodeToDic description for information about STEPS and return results,
189   but you must use LzmaDec_DecodeToBuf instead of LzmaDec_DecodeToDic and you don't need
190   to work with CLzmaDec variables manually.
191 
192finishMode:
193  It has meaning only if the decoding reaches output limit (*destLen).
194  LZMA_FINISH_ANY - Decode just destLen bytes.
195  LZMA_FINISH_END - Stream must be finished after (*destLen).
196*/
197 
198SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen,
199    const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
200 
201 
202/* ---------- One Call Interface ---------- */
203 
204/* LzmaDecode
205 
206finishMode:
207  It has meaning only if the decoding reaches output limit (*destLen).
208  LZMA_FINISH_ANY - Decode just destLen bytes.
209  LZMA_FINISH_END - Stream must be finished after (*destLen).
210 
211Returns:
212  SZ_OK
213    status:
214      LZMA_STATUS_FINISHED_WITH_MARK
215      LZMA_STATUS_NOT_FINISHED
216      LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
217  SZ_ERROR_DATA - Data error
218  SZ_ERROR_MEM  - Memory allocation error
219  SZ_ERROR_UNSUPPORTED - Unsupported properties
220  SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src).
221*/
222 
223SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
224    const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode,
225    ELzmaStatus *status, ISzAlloc *alloc);
226 
227#ifdef __cplusplus
228}
229#endif
230 
231#endif
src/lib/lib7z/XzIn.c
r0r14440
1/* XzIn.c - Xz input
22011-02-01 : Igor Pavlov : Public domain */
3 
4#include <string.h>
5 
6#include "7zCrc.h"
7#include "CpuArch.h"
8#include "Xz.h"
9 
10SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream)
11{
12  Byte sig[XZ_STREAM_HEADER_SIZE];
13  RINOK(SeqInStream_Read2(inStream, sig, XZ_STREAM_HEADER_SIZE, SZ_ERROR_NO_ARCHIVE));
14  if (memcmp(sig, XZ_SIG, XZ_SIG_SIZE) != 0)
15    return SZ_ERROR_NO_ARCHIVE;
16  return Xz_ParseHeader(p, sig);
17}
18 
19#define READ_VARINT_AND_CHECK(buf, pos, size, res) \
20  { unsigned s = Xz_ReadVarInt(buf + pos, size - pos, res); \
21  if (s == 0) return SZ_ERROR_ARCHIVE; pos += s; }
22 
23SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, Bool *isIndex, UInt32 *headerSizeRes)
24{
25  Byte header[XZ_BLOCK_HEADER_SIZE_MAX];
26  unsigned headerSize;
27  *headerSizeRes = 0;
28  RINOK(SeqInStream_ReadByte(inStream, &header[0]));
29  headerSize = ((unsigned)header[0] << 2) + 4;
30  if (headerSize == 0)
31  {
32    *headerSizeRes = 1;
33    *isIndex = True;
34    return SZ_OK;
35  }
36 
37  *isIndex = False;
38  *headerSizeRes = headerSize;
39  RINOK(SeqInStream_Read(inStream, header + 1, headerSize - 1));
40  return XzBlock_Parse(p, header);
41}
42 
43#define ADD_SIZE_CHECH(size, val) \
44  { UInt64 newSize = size + (val); if (newSize < size) return XZ_SIZE_OVERFLOW; size = newSize; }
45 
46UInt64 Xz_GetUnpackSize(const CXzStream *p)
47{
48  UInt64 size = 0;
49  size_t i;
50  for (i = 0; i < p->numBlocks; i++)
51    ADD_SIZE_CHECH(size, p->blocks[i].unpackSize);
52  return size;
53}
54 
55UInt64 Xz_GetPackSize(const CXzStream *p)
56{
57  UInt64 size = 0;
58  size_t i;
59  for (i = 0; i < p->numBlocks; i++)
60    ADD_SIZE_CHECH(size, (p->blocks[i].totalSize + 3) & ~(UInt64)3);
61  return size;
62}
63 
64/*
65SRes XzBlock_ReadFooter(CXzBlock *p, CXzStreamFlags f, ISeqInStream *inStream)
66{
67  return SeqInStream_Read(inStream, p->check, XzFlags_GetCheckSize(f));
68}
69*/
70 
71static SRes Xz_ReadIndex2(CXzStream *p, const Byte *buf, size_t size, ISzAlloc *alloc)
72{
73  size_t i, numBlocks, crcStartPos, pos = 1;
74  UInt32 crc;
75 
76  if (size < 5 || buf[0] != 0)
77    return SZ_ERROR_ARCHIVE;
78 
79  size -= 4;
80  crc = CrcCalc(buf, size);
81  if (crc != GetUi32(buf + size))
82    return SZ_ERROR_ARCHIVE;
83 
84  {
85    UInt64 numBlocks64;
86    READ_VARINT_AND_CHECK(buf, pos, size, &numBlocks64);
87    numBlocks = (size_t)numBlocks64;
88    if (numBlocks != numBlocks64 || numBlocks * 2 > size)
89      return SZ_ERROR_ARCHIVE;
90  }
91   
92  crcStartPos = pos;
93  Xz_Free(p, alloc);
94  if (numBlocks != 0)
95  {
96    p->numBlocks = numBlocks;
97    p->numBlocksAllocated = numBlocks;
98    p->blocks = alloc->Alloc(alloc, sizeof(CXzBlockSizes) * numBlocks);
99    if (p->blocks == 0)
100      return SZ_ERROR_MEM;
101    for (i = 0; i < numBlocks; i++)
102    {
103      CXzBlockSizes *block = &p->blocks[i];
104      READ_VARINT_AND_CHECK(buf, pos, size, &block->totalSize);
105      READ_VARINT_AND_CHECK(buf, pos, size, &block->unpackSize);
106      if (block->totalSize == 0)
107        return SZ_ERROR_ARCHIVE;
108    }
109  }
110  while ((pos & 3) != 0)
111    if (buf[pos++] != 0)
112      return SZ_ERROR_ARCHIVE;
113  return (pos == size) ? SZ_OK : SZ_ERROR_ARCHIVE;
114}
115 
116static SRes Xz_ReadIndex(CXzStream *p, ILookInStream *stream, UInt64 indexSize, ISzAlloc *alloc)
117{
118  SRes res;
119  size_t size;
120  Byte *buf;
121  if (indexSize > ((UInt32)1 << 31))
122    return SZ_ERROR_UNSUPPORTED;
123  size = (size_t)indexSize;
124  if (size != indexSize)
125    return SZ_ERROR_UNSUPPORTED;
126  buf = alloc->Alloc(alloc, size);
127  if (buf == 0)
128    return SZ_ERROR_MEM;
129  res = LookInStream_Read2(stream, buf, size, SZ_ERROR_UNSUPPORTED);
130  if (res == SZ_OK)
131    res = Xz_ReadIndex2(p, buf, size, alloc);
132  alloc->Free(alloc, buf);
133  return res;
134}
135 
136static SRes SeekFromCur(ILookInStream *inStream, Int64 *res)
137{
138  return inStream->Seek(inStream, res, SZ_SEEK_CUR);
139}
140 
141static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOffset, ISzAlloc *alloc)
142{
143  UInt64 indexSize;
144  Byte buf[XZ_STREAM_FOOTER_SIZE];
145 
146  if ((*startOffset & 3) != 0 || *startOffset < XZ_STREAM_FOOTER_SIZE)
147    return SZ_ERROR_NO_ARCHIVE;
148  *startOffset = -XZ_STREAM_FOOTER_SIZE;
149  RINOK(SeekFromCur(stream, startOffset));
150 
151  RINOK(LookInStream_Read2(stream, buf, XZ_STREAM_FOOTER_SIZE, SZ_ERROR_NO_ARCHIVE));
152   
153  if (memcmp(buf + 10, XZ_FOOTER_SIG, XZ_FOOTER_SIG_SIZE) != 0)
154  {
155    UInt32 total = 0;
156    *startOffset += XZ_STREAM_FOOTER_SIZE;
157    for (;;)
158    {
159      size_t i;
160      #define TEMP_BUF_SIZE (1 << 10)
161      Byte tempBuf[TEMP_BUF_SIZE];
162      if (*startOffset < XZ_STREAM_FOOTER_SIZE || total > (1 << 16))
163        return SZ_ERROR_NO_ARCHIVE;
164      i = (*startOffset > TEMP_BUF_SIZE) ? TEMP_BUF_SIZE : (size_t)*startOffset;
165      total += (UInt32)i;
166      *startOffset = -(Int64)i;
167      RINOK(SeekFromCur(stream, startOffset));
168      RINOK(LookInStream_Read2(stream, tempBuf, i, SZ_ERROR_NO_ARCHIVE));
169      for (; i != 0; i--)
170        if (tempBuf[i - 1] != 0)
171          break;
172      if (i != 0)
173      {
174        if ((i & 3) != 0)
175          return SZ_ERROR_NO_ARCHIVE;
176        *startOffset += i;
177        break;
178      }
179    }
180    if (*startOffset < XZ_STREAM_FOOTER_SIZE)
181      return SZ_ERROR_NO_ARCHIVE;
182    *startOffset -= XZ_STREAM_FOOTER_SIZE;
183    RINOK(stream->Seek(stream, startOffset, SZ_SEEK_SET));
184    RINOK(LookInStream_Read2(stream, buf, XZ_STREAM_FOOTER_SIZE, SZ_ERROR_NO_ARCHIVE));
185    if (memcmp(buf + 10, XZ_FOOTER_SIG, XZ_FOOTER_SIG_SIZE) != 0)
186      return SZ_ERROR_NO_ARCHIVE;
187  }
188   
189  p->flags = (CXzStreamFlags)GetBe16(buf + 8);
190 
191  if (!XzFlags_IsSupported(p->flags))
192    return SZ_ERROR_UNSUPPORTED;
193 
194  if (GetUi32(buf) != CrcCalc(buf + 4, 6))
195    return SZ_ERROR_ARCHIVE;
196 
197  indexSize = ((UInt64)GetUi32(buf + 4) + 1) << 2;
198 
199  *startOffset = -(Int64)(indexSize + XZ_STREAM_FOOTER_SIZE);
200  RINOK(SeekFromCur(stream, startOffset));
201 
202  RINOK(Xz_ReadIndex(p, stream, indexSize, alloc));
203 
204  {
205    UInt64 totalSize = Xz_GetPackSize(p);
206    UInt64 sum = XZ_STREAM_HEADER_SIZE + totalSize + indexSize;
207    if (totalSize == XZ_SIZE_OVERFLOW ||
208      sum >= ((UInt64)1 << 63) ||
209      totalSize >= ((UInt64)1 << 63))
210      return SZ_ERROR_ARCHIVE;
211    *startOffset = -(Int64)sum;
212    RINOK(SeekFromCur(stream, startOffset));
213  }
214  {
215    CXzStreamFlags headerFlags;
216    CSecToRead secToRead;
217    SecToRead_CreateVTable(&secToRead);
218    secToRead.realStream = stream;
219 
220    RINOK(Xz_ReadHeader(&headerFlags, &secToRead.s));
221    return (p->flags == headerFlags) ? SZ_OK : SZ_ERROR_ARCHIVE;
222  }
223}
224 
225 
226/* ---------- Xz Streams ---------- */
227 
228void Xzs_Construct(CXzs *p)
229{
230  p->num = p->numAllocated = 0;
231  p->streams = 0;
232}
233 
234void Xzs_Free(CXzs *p, ISzAlloc *alloc)
235{
236  size_t i;
237  for (i = 0; i < p->num; i++)
238    Xz_Free(&p->streams[i], alloc);
239  alloc->Free(alloc, p->streams);
240  p->num = p->numAllocated = 0;
241  p->streams = 0;
242}
243 
244UInt64 Xzs_GetNumBlocks(const CXzs *p)
245{
246  UInt64 num = 0;
247  size_t i;
248  for (i = 0; i < p->num; i++)
249    num += p->streams[i].numBlocks;
250  return num;
251}
252 
253UInt64 Xzs_GetUnpackSize(const CXzs *p)
254{
255  UInt64 size = 0;
256  size_t i;
257  for (i = 0; i < p->num; i++)
258    ADD_SIZE_CHECH(size, Xz_GetUnpackSize(&p->streams[i]));
259  return size;
260}
261 
262/*
263UInt64 Xzs_GetPackSize(const CXzs *p)
264{
265  UInt64 size = 0;
266  size_t i;
267  for (i = 0; i < p->num; i++)
268    ADD_SIZE_CHECH(size, Xz_GetTotalSize(&p->streams[i]));
269  return size;
270}
271*/
272 
273SRes Xzs_ReadBackward(CXzs *p, ILookInStream *stream, Int64 *startOffset, ICompressProgress *progress, ISzAlloc *alloc)
274{
275  Int64 endOffset = 0;
276  RINOK(stream->Seek(stream, &endOffset, SZ_SEEK_END));
277  *startOffset = endOffset;
278  for (;;)
279  {
280    CXzStream st;
281    SRes res;
282    Xz_Construct(&st);
283    res = Xz_ReadBackward(&st, stream, startOffset, alloc);
284    st.startOffset = *startOffset;
285    RINOK(res);
286    if (p->num == p->numAllocated)
287    {
288      size_t newNum = p->num + p->num / 4 + 1;
289      Byte *data = (Byte *)alloc->Alloc(alloc, newNum * sizeof(CXzStream));
290      if (data == 0)
291        return SZ_ERROR_MEM;
292      p->numAllocated = newNum;
293      memcpy(data, p->streams, p->num * sizeof(CXzStream));
294      alloc->Free(alloc, p->streams);
295      p->streams = (CXzStream *)data;
296    }
297    p->streams[p->num++] = st;
298    if (*startOffset == 0)
299      break;
300    RINOK(stream->Seek(stream, startOffset, SZ_SEEK_SET));
301    if (progress && progress->Progress(progress, endOffset - *startOffset, (UInt64)(Int64)-1) != SZ_OK)
302      return SZ_ERROR_PROGRESS;
303  }
304  return SZ_OK;
305}
src/lib/lib7z/BraIA64.c
r0r14440
1/* BraIA64.c -- Converter for IA-64 code
22008-10-04 : Igor Pavlov : Public domain */
3 
4#include "Bra.h"
5 
6static const Byte kBranchTable[32] =
7{
8  0, 0, 0, 0, 0, 0, 0, 0,
9  0, 0, 0, 0, 0, 0, 0, 0,
10  4, 4, 6, 6, 0, 0, 7, 7,
11  4, 4, 0, 0, 4, 4, 0, 0
12};
13 
14SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding)
15{
16  SizeT i;
17  if (size < 16)
18    return 0;
19  size -= 16;
20  for (i = 0; i <= size; i += 16)
21  {
22    UInt32 instrTemplate = data[i] & 0x1F;
23    UInt32 mask = kBranchTable[instrTemplate];
24    UInt32 bitPos = 5;
25    int slot;
26    for (slot = 0; slot < 3; slot++, bitPos += 41)
27    {
28      UInt32 bytePos, bitRes;
29      UInt64 instruction, instNorm;
30      int j;
31      if (((mask >> slot) & 1) == 0)
32        continue;
33      bytePos = (bitPos >> 3);
34      bitRes = bitPos & 0x7;
35      instruction = 0;
36      for (j = 0; j < 6; j++)
37        instruction += (UInt64)data[i + j + bytePos] << (8 * j);
38 
39      instNorm = instruction >> bitRes;
40      if (((instNorm >> 37) & 0xF) == 0x5 && ((instNorm >> 9) & 0x7) == 0)
41      {
42        UInt32 src = (UInt32)((instNorm >> 13) & 0xFFFFF);
43        UInt32 dest;
44        src |= ((UInt32)(instNorm >> 36) & 1) << 20;
45         
46        src <<= 4;
47         
48        if (encoding)
49          dest = ip + (UInt32)i + src;
50        else
51          dest = src - (ip + (UInt32)i);
52         
53        dest >>= 4;
54         
55        instNorm &= ~((UInt64)(0x8FFFFF) << 13);
56        instNorm |= ((UInt64)(dest & 0xFFFFF) << 13);
57        instNorm |= ((UInt64)(dest & 0x100000) << (36 - 20));
58         
59        instruction &= (1 << bitRes) - 1;
60        instruction |= (instNorm << bitRes);
61        for (j = 0; j < 6; j++)
62          data[i + j + bytePos] = (Byte)(instruction >> (8 * j));
63      }
64    }
65  }
66  return i;
67}
src/lib/lib7z/LzHash.h
r0r14440
1/* LzHash.h -- HASH functions for LZ algorithms
22009-02-07 : Igor Pavlov : Public domain */
3 
4#ifndef __LZ_HASH_H
5#define __LZ_HASH_H
6 
7#define kHash2Size (1 << 10)
8#define kHash3Size (1 << 16)
9#define kHash4Size (1 << 20)
10 
11#define kFix3HashSize (kHash2Size)
12#define kFix4HashSize (kHash2Size + kHash3Size)
13#define kFix5HashSize (kHash2Size + kHash3Size + kHash4Size)
14 
15#define HASH2_CALC hashValue = cur[0] | ((UInt32)cur[1] << 8);
16 
17#define HASH3_CALC { \
18  UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
19  hash2Value = temp & (kHash2Size - 1); \
20  hashValue = (temp ^ ((UInt32)cur[2] << 8)) & p->hashMask; }
21 
22#define HASH4_CALC { \
23  UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
24  hash2Value = temp & (kHash2Size - 1); \
25  hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \
26  hashValue = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & p->hashMask; }
27 
28#define HASH5_CALC { \
29  UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
30  hash2Value = temp & (kHash2Size - 1); \
31  hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \
32  hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)); \
33  hashValue = (hash4Value ^ (p->crc[cur[4]] << 3)) & p->hashMask; \
34  hash4Value &= (kHash4Size - 1); }
35 
36/* #define HASH_ZIP_CALC hashValue = ((cur[0] | ((UInt32)cur[1] << 8)) ^ p->crc[cur[2]]) & 0xFFFF; */
37#define HASH_ZIP_CALC hashValue = ((cur[2] | ((UInt32)cur[0] << 8)) ^ p->crc[cur[1]]) & 0xFFFF;
38 
39 
40#define MT_HASH2_CALC \
41  hash2Value = (p->crc[cur[0]] ^ cur[1]) & (kHash2Size - 1);
42 
43#define MT_HASH3_CALC { \
44  UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
45  hash2Value = temp & (kHash2Size - 1); \
46  hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); }
47 
48#define MT_HASH4_CALC { \
49  UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
50  hash2Value = temp & (kHash2Size - 1); \
51  hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \
52  hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & (kHash4Size - 1); }
53 
54#endif
src/lib/lib7z/x7zAlloc.c
r0r14440
1/* 7zAlloc.c -- Allocation functions
22010-10-29 : Igor Pavlov : Public domain */
3 
4#include "7zAlloc.h"
5 
6/* #define _SZ_ALLOC_DEBUG */
7/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */
8 
9#ifdef _SZ_ALLOC_DEBUG
10 
11#ifdef _WIN32_7Z
12#include <windows.h>
13#endif
14 
15#include <stdio.h>
16int g_allocCount = 0;
17int g_allocCountTemp = 0;
18 
19#endif
20 
21void *SzAlloc(void *p, size_t size)
22{
23  p = p;
24  if (size == 0)
25    return 0;
26  #ifdef _SZ_ALLOC_DEBUG
27  fprintf(stderr, "\nAlloc %10d bytes; count = %10d", size, g_allocCount);
28  g_allocCount++;
29  #endif
30  return malloc(size);
31}
32 
33void SzFree(void *p, void *address)
34{
35  p = p;
36  #ifdef _SZ_ALLOC_DEBUG
37  if (address != 0)
38  {
39    g_allocCount--;
40    fprintf(stderr, "\nFree; count = %10d", g_allocCount);
41  }
42  #endif
43  free(address);
44}
45 
46void *SzAllocTemp(void *p, size_t size)
47{
48  p = p;
49  if (size == 0)
50    return 0;
51  #ifdef _SZ_ALLOC_DEBUG
52  fprintf(stderr, "\nAlloc_temp %10d bytes;  count = %10d", size, g_allocCountTemp);
53  g_allocCountTemp++;
54  #ifdef _WIN32_7Z
55  return HeapAlloc(GetProcessHeap(), 0, size);
56  #endif
57  #endif
58  return malloc(size);
59}
60 
61void SzFreeTemp(void *p, void *address)
62{
63  p = p;
64  #ifdef _SZ_ALLOC_DEBUG
65  if (address != 0)
66  {
67    g_allocCountTemp--;
68    fprintf(stderr, "\nFree_temp; count = %10d", g_allocCountTemp);
69  }
70  #ifdef _WIN32_7Z
71  HeapFree(GetProcessHeap(), 0, address);
72  return;
73  #endif
74  #endif
75  free(address);
76}
src/lib/lib7z/Ppmd.h
r0r14440
1/* Ppmd.h -- PPMD codec common code
22011-01-27 : Igor Pavlov : Public domain
3This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
4 
5#ifndef __PPMD_H
6#define __PPMD_H
7 
8#include "Types.h"
9#include "CpuArch.h"
10 
11EXTERN_C_BEGIN
12 
13#ifdef MY_CPU_32BIT
14  #define PPMD_32BIT
15#endif
16 
17#define PPMD_INT_BITS 7
18#define PPMD_PERIOD_BITS 7
19#define PPMD_BIN_SCALE (1 << (PPMD_INT_BITS + PPMD_PERIOD_BITS))
20 
21#define PPMD_GET_MEAN_SPEC(summ, shift, round) (((summ) + (1 << ((shift) - (round)))) >> (shift))
22#define PPMD_GET_MEAN(summ) PPMD_GET_MEAN_SPEC((summ), PPMD_PERIOD_BITS, 2)
23#define PPMD_UPDATE_PROB_0(prob) ((prob) + (1 << PPMD_INT_BITS) - PPMD_GET_MEAN(prob))
24#define PPMD_UPDATE_PROB_1(prob) ((prob) - PPMD_GET_MEAN(prob))
25 
26#define PPMD_N1 4
27#define PPMD_N2 4
28#define PPMD_N3 4
29#define PPMD_N4 ((128 + 3 - 1 * PPMD_N1 - 2 * PPMD_N2 - 3 * PPMD_N3) / 4)
30#define PPMD_NUM_INDEXES (PPMD_N1 + PPMD_N2 + PPMD_N3 + PPMD_N4)
31 
32#pragma pack(push, 1)
33/* Most compilers works OK here even without #pragma pack(push, 1), but some GCC compilers need it. */
34 
35/* SEE-contexts for PPM-contexts with masked symbols */
36typedef struct
37{
38  UInt16 Summ; /* Freq */
39  Byte Shift;  /* Speed of Freq change; low Shift is for fast change */
40  Byte Count;  /* Count to next change of Shift */
41} CPpmd_See;
42 
43#define Ppmd_See_Update(p)  if ((p)->Shift < PPMD_PERIOD_BITS && --(p)->Count == 0) \
44    { (p)->Summ <<= 1; (p)->Count = (Byte)(3 << (p)->Shift++); }
45 
46typedef struct
47{
48  Byte Symbol;
49  Byte Freq;
50  UInt16 SuccessorLow;
51  UInt16 SuccessorHigh;
52} CPpmd_State;
53 
54#pragma pack(pop)
55 
56typedef
57  #ifdef PPMD_32BIT
58    CPpmd_State *
59  #else
60    UInt32
61  #endif
62  CPpmd_State_Ref;
63 
64typedef
65  #ifdef PPMD_32BIT
66    void *
67  #else
68    UInt32
69  #endif
70  CPpmd_Void_Ref;
71 
72typedef
73  #ifdef PPMD_32BIT
74    Byte *
75  #else
76    UInt32
77  #endif
78  CPpmd_Byte_Ref;
79 
80#define PPMD_SetAllBitsIn256Bytes(p) \
81  { unsigned i; for (i = 0; i < 256 / sizeof(p[0]); i += 8) { \
82  p[i+7] = p[i+6] = p[i+5] = p[i+4] = p[i+3] = p[i+2] = p[i+1] = p[i+0] = ~(size_t)0; }}
83 
84EXTERN_C_END
85 
86#endif
src/lib/lib7z/Lzma86Enc.c
r0r14440
1/* Lzma86Enc.c -- LZMA + x86 (BCJ) Filter Encoder
22009-08-14 : Igor Pavlov : Public domain */
3 
4#include <string.h>
5 
6#include "Lzma86.h"
7 
8#include "Alloc.h"
9#include "Bra.h"
10#include "LzmaEnc.h"
11 
12#define SZE_OUT_OVERFLOW SZE_DATA_ERROR
13 
14static void *SzAlloc(void *p, size_t size) { p = p; return MyAlloc(size); }
15static void SzFree(void *p, void *address) { p = p; MyFree(address); }
16 
17int Lzma86_Encode(Byte *dest, size_t *destLen, const Byte *src, size_t srcLen,
18    int level, UInt32 dictSize, int filterMode)
19{
20  ISzAlloc g_Alloc = { SzAlloc, SzFree };
21  size_t outSize2 = *destLen;
22  Byte *filteredStream;
23  Bool useFilter;
24  int mainResult = SZ_ERROR_OUTPUT_EOF;
25  CLzmaEncProps props;
26  LzmaEncProps_Init(&props);
27  props.level = level;
28  props.dictSize = dictSize;
29   
30  *destLen = 0;
31  if (outSize2 < LZMA86_HEADER_SIZE)
32    return SZ_ERROR_OUTPUT_EOF;
33 
34  {
35    int i;
36    UInt64 t = srcLen;
37    for (i = 0; i < 8; i++, t >>= 8)
38      dest[LZMA86_SIZE_OFFSET + i] = (Byte)t;
39  }
40 
41  filteredStream = 0;
42  useFilter = (filterMode != SZ_FILTER_NO);
43  if (useFilter)
44  {
45    if (srcLen != 0)
46    {
47      filteredStream = (Byte *)MyAlloc(srcLen);
48      if (filteredStream == 0)
49        return SZ_ERROR_MEM;
50      memcpy(filteredStream, src, srcLen);
51    }
52    {
53      UInt32 x86State;
54      x86_Convert_Init(x86State);
55      x86_Convert(filteredStream, srcLen, 0, &x86State, 1);
56    }
57  }
58 
59  {
60    size_t minSize = 0;
61    Bool bestIsFiltered = False;
62 
63    /* passes for SZ_FILTER_AUTO:
64        0 - BCJ + LZMA
65        1 - LZMA
66        2 - BCJ + LZMA agaian, if pass 0 (BCJ + LZMA) is better.
67    */
68    int numPasses = (filterMode == SZ_FILTER_AUTO) ? 3 : 1;
69 
70    int i;
71    for (i = 0; i < numPasses; i++)
72    {
73      size_t outSizeProcessed = outSize2 - LZMA86_HEADER_SIZE;
74      size_t outPropsSize = 5;
75      SRes curRes;
76      Bool curModeIsFiltered = (numPasses > 1 && i == numPasses - 1);
77      if (curModeIsFiltered && !bestIsFiltered)
78        break;
79      if (useFilter && i == 0)
80        curModeIsFiltered = True;
81       
82      curRes = LzmaEncode(dest + LZMA86_HEADER_SIZE, &outSizeProcessed,
83          curModeIsFiltered ? filteredStream : src, srcLen,
84          &props, dest + 1, &outPropsSize, 0,
85          NULL, &g_Alloc, &g_Alloc);
86       
87      if (curRes != SZ_ERROR_OUTPUT_EOF)
88      {
89        if (curRes != SZ_OK)
90        {
91          mainResult = curRes;
92          break;
93        }
94        if (outSizeProcessed <= minSize || mainResult != SZ_OK)
95        {
96          minSize = outSizeProcessed;
97          bestIsFiltered = curModeIsFiltered;
98          mainResult = SZ_OK;
99        }
100      }
101    }
102    dest[0] = (bestIsFiltered ? 1 : 0);
103    *destLen = LZMA86_HEADER_SIZE + minSize;
104  }
105  if (useFilter)
106    MyFree(filteredStream);
107  return mainResult;
108}
src/lib/lib7z/x7zAlloc.h
r0r14440
1/* 7zAlloc.h -- Allocation functions
22010-10-29 : Igor Pavlov : Public domain */
3 
4#ifndef __7Z_ALLOC_H
5#define __7Z_ALLOC_H
6 
7#include <stdlib.h>
8 
9void *SzAlloc(void *p, size_t size);
10void SzFree(void *p, void *address);
11 
12void *SzAllocTemp(void *p, size_t size);
13void SzFreeTemp(void *p, void *address);
14 
15#endif
src/lib/lib7z/7zVersion.h
r0r14440
1#define MY_VER_MAJOR 9
2#define MY_VER_MINOR 22
3#define MY_VER_BUILD 00
4#define MY_VERSION "9.22 beta"
5#define MY_7ZIP_VERSION "9.22 beta"
6#define MY_DATE "2011-04-18"
7#define MY_COPYRIGHT ": Igor Pavlov : Public domain"
8#define MY_VERSION_COPYRIGHT_DATE MY_VERSION " " MY_COPYRIGHT " : " MY_DATE
src/lib/lib7z/7zStream.c
r0r14440
1/* 7zStream.c -- 7z Stream functions
22010-03-11 : Igor Pavlov : Public domain */
3 
4#include <string.h>
5 
6#include "Types.h"
7 
8SRes SeqInStream_Read2(ISeqInStream *stream, void *buf, size_t size, SRes errorType)
9{
10  while (size != 0)
11  {
12    size_t processed = size;
13    RINOK(stream->Read(stream, buf, &processed));
14    if (processed == 0)
15      return errorType;
16    buf = (void *)((Byte *)buf + processed);
17    size -= processed;
18  }
19  return SZ_OK;
20}
21 
22SRes SeqInStream_Read(ISeqInStream *stream, void *buf, size_t size)
23{
24  return SeqInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF);
25}
26 
27SRes SeqInStream_ReadByte(ISeqInStream *stream, Byte *buf)
28{
29  size_t processed = 1;
30  RINOK(stream->Read(stream, buf, &processed));
31  return (processed == 1) ? SZ_OK : SZ_ERROR_INPUT_EOF;
32}
33 
34SRes LookInStream_SeekTo(ILookInStream *stream, UInt64 offset)
35{
36  Int64 t = offset;
37  return stream->Seek(stream, &t, SZ_SEEK_SET);
38}
39 
40SRes LookInStream_LookRead(ILookInStream *stream, void *buf, size_t *size)
41{
42  const void *lookBuf;
43  if (*size == 0)
44    return SZ_OK;
45  RINOK(stream->Look(stream, &lookBuf, size));
46  memcpy(buf, lookBuf, *size);
47  return stream->Skip(stream, *size);
48}
49 
50SRes LookInStream_Read2(ILookInStream *stream, void *buf, size_t size, SRes errorType)
51{
52  while (size != 0)
53  {
54    size_t processed = size;
55    RINOK(stream->Read(stream, buf, &processed));
56    if (processed == 0)
57      return errorType;
58    buf = (void *)((Byte *)buf + processed);
59    size -= processed;
60  }
61  return SZ_OK;
62}
63 
64SRes LookInStream_Read(ILookInStream *stream, void *buf, size_t size)
65{
66  return LookInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF);
67}
68 
69static SRes LookToRead_Look_Lookahead(void *pp, const void **buf, size_t *size)
70{
71  SRes res = SZ_OK;
72  CLookToRead *p = (CLookToRead *)pp;
73  size_t size2 = p->size - p->pos;
74  if (size2 == 0 && *size > 0)
75  {
76    p->pos = 0;
77    size2 = LookToRead_BUF_SIZE;
78    res = p->realStream->Read(p->realStream, p->buf, &size2);
79    p->size = size2;
80  }
81  if (size2 < *size)
82    *size = size2;
83  *buf = p->buf + p->pos;
84  return res;
85}
86 
87static SRes LookToRead_Look_Exact(void *pp, const void **buf, size_t *size)
88{
89  SRes res = SZ_OK;
90  CLookToRead *p = (CLookToRead *)pp;
91  size_t size2 = p->size - p->pos;
92  if (size2 == 0 && *size > 0)
93  {
94    p->pos = 0;
95    if (*size > LookToRead_BUF_SIZE)
96      *size = LookToRead_BUF_SIZE;
97    res = p->realStream->Read(p->realStream, p->buf, size);
98    size2 = p->size = *size;
99  }
100  if (size2 < *size)
101    *size = size2;
102  *buf = p->buf + p->pos;
103  return res;
104}
105 
106static SRes LookToRead_Skip(void *pp, size_t offset)
107{
108  CLookToRead *p = (CLookToRead *)pp;
109  p->pos += offset;
110  return SZ_OK;
111}
112 
113static SRes LookToRead_Read(void *pp, void *buf, size_t *size)
114{
115  CLookToRead *p = (CLookToRead *)pp;
116  size_t rem = p->size - p->pos;
117  if (rem == 0)
118    return p->realStream->Read(p->realStream, buf, size);
119  if (rem > *size)
120    rem = *size;
121  memcpy(buf, p->buf + p->pos, rem);
122  p->pos += rem;
123  *size = rem;
124  return SZ_OK;
125}
126 
127static SRes LookToRead_Seek(void *pp, Int64 *pos, ESzSeek origin)
128{
129  CLookToRead *p = (CLookToRead *)pp;
130  p->pos = p->size = 0;
131  return p->realStream->Seek(p->realStream, pos, origin);
132}
133 
134void LookToRead_CreateVTable(CLookToRead *p, int lookahead)
135{
136  p->s.Look = lookahead ?
137      LookToRead_Look_Lookahead :
138      LookToRead_Look_Exact;
139  p->s.Skip = LookToRead_Skip;
140  p->s.Read = LookToRead_Read;
141  p->s.Seek = LookToRead_Seek;
142}
143 
144void LookToRead_Init(CLookToRead *p)
145{
146  p->pos = p->size = 0;
147}
148 
149static SRes SecToLook_Read(void *pp, void *buf, size_t *size)
150{
151  CSecToLook *p = (CSecToLook *)pp;
152  return LookInStream_LookRead(p->realStream, buf, size);
153}
154 
155void SecToLook_CreateVTable(CSecToLook *p)
156{
157  p->s.Read = SecToLook_Read;
158}
159 
160static SRes SecToRead_Read(void *pp, void *buf, size_t *size)
161{
162  CSecToRead *p = (CSecToRead *)pp;
163  return p->realStream->Read(p->realStream, buf, size);
164}
165 
166void SecToRead_CreateVTable(CSecToRead *p)
167{
168  p->s.Read = SecToRead_Read;
169}
src/lib/lib7z/Ppmd7.c
r0r14440
1/* Ppmd7.c -- PPMdH codec
22010-03-12 : Igor Pavlov : Public domain
3This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
4 
5#include <memory.h>
6 
7#include "Ppmd7.h"
8 
9const Byte PPMD7_kExpEscape[16] = { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 };
10static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051};
11 
12#define MAX_FREQ 124
13#define UNIT_SIZE 12
14 
15#define U2B(nu) ((UInt32)(nu) * UNIT_SIZE)
16#define U2I(nu) (p->Units2Indx[(nu) - 1])
17#define I2U(indx) (p->Indx2Units[indx])
18 
19#ifdef PPMD_32BIT
20  #define REF(ptr) (ptr)
21#else
22  #define REF(ptr) ((UInt32)((Byte *)(ptr) - (p)->Base))
23#endif
24 
25#define STATS_REF(ptr) ((CPpmd_State_Ref)REF(ptr))
26 
27#define CTX(ref) ((CPpmd7_Context *)Ppmd7_GetContext(p, ref))
28#define STATS(ctx) Ppmd7_GetStats(p, ctx)
29#define ONE_STATE(ctx) Ppmd7Context_OneState(ctx)
30#define SUFFIX(ctx) CTX((ctx)->Suffix)
31 
32typedef CPpmd7_Context * CTX_PTR;
33 
34struct CPpmd7_Node_;
35 
36typedef
37  #ifdef PPMD_32BIT
38    struct CPpmd7_Node_ *
39  #else
40    UInt32
41  #endif
42  CPpmd7_Node_Ref;
43 
44typedef struct CPpmd7_Node_
45{
46  UInt16 Stamp; /* must be at offset 0 as CPpmd7_Context::NumStats. Stamp=0 means free */
47  UInt16 NU;
48  CPpmd7_Node_Ref Next; /* must be at offset >= 4 */
49  CPpmd7_Node_Ref Prev;
50} CPpmd7_Node;
51 
52#ifdef PPMD_32BIT
53  #define NODE(ptr) (ptr)
54#else
55  #define NODE(offs) ((CPpmd7_Node *)(p->Base + (offs)))
56#endif
57 
58void Ppmd7_Construct(CPpmd7 *p)
59{
60  unsigned i, k, m;
61 
62  p->Base = 0;
63 
64  for (i = 0, k = 0; i < PPMD_NUM_INDEXES; i++)
65  {
66    unsigned step = (i >= 12 ? 4 : (i >> 2) + 1);
67    do { p->Units2Indx[k++] = (Byte)i; } while(--step);
68    p->Indx2Units[i] = (Byte)k;
69  }
70 
71  p->NS2BSIndx[0] = (0 << 1);
72  p->NS2BSIndx[1] = (1 << 1);
73  memset(p->NS2BSIndx + 2, (2 << 1), 9);
74  memset(p->NS2BSIndx + 11, (3 << 1), 256 - 11);
75 
76  for (i = 0; i < 3; i++)
77    p->NS2Indx[i] = (Byte)i;
78  for (m = i, k = 1; i < 256; i++)
79  {
80    p->NS2Indx[i] = (Byte)m;
81    if (--k == 0)
82      k = (++m) - 2;
83  }
84 
85  memset(p->HB2Flag, 0, 0x40);
86  memset(p->HB2Flag + 0x40, 8, 0x100 - 0x40);
87}
88 
89void Ppmd7_Free(CPpmd7 *p, ISzAlloc *alloc)
90{
91  alloc->Free(alloc, p->Base);
92  p->Size = 0;
93  p->Base = 0;
94}
95 
96Bool Ppmd7_Alloc(CPpmd7 *p, UInt32 size, ISzAlloc *alloc)
97{
98  if (p->Base == 0 || p->Size != size)
99  {
100    Ppmd7_Free(p, alloc);
101    p->AlignOffset =
102      #ifdef PPMD_32BIT
103        (4 - size) & 3;
104      #else
105        4 - (size & 3);
106      #endif
107    if ((p->Base = (Byte *)alloc->Alloc(alloc, p->AlignOffset + size
108        #ifndef PPMD_32BIT
109        + UNIT_SIZE
110        #endif
111        )) == 0)
112      return False;
113    p->Size = size;
114  }
115  return True;
116}
117 
118static void InsertNode(CPpmd7 *p, void *node, unsigned indx)
119{
120  *((CPpmd_Void_Ref *)node) = p->FreeList[indx];
121  p->FreeList[indx] = REF(node);
122}
123 
124static void *RemoveNode(CPpmd7 *p, unsigned indx)
125{
126  CPpmd_Void_Ref *node = (CPpmd_Void_Ref *)Ppmd7_GetPtr(p, p->FreeList[indx]);
127  p->FreeList[indx] = *node;
128  return node;
129}
130 
131static void SplitBlock(CPpmd7 *p, void *ptr, unsigned oldIndx, unsigned newIndx)
132{
133  unsigned i, nu = I2U(oldIndx) - I2U(newIndx);
134  ptr = (Byte *)ptr + U2B(I2U(newIndx));
135  if (I2U(i = U2I(nu)) != nu)
136  {
137    unsigned k = I2U(--i);
138    InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1);
139  }
140  InsertNode(p, ptr, i);
141}
142 
143static void GlueFreeBlocks(CPpmd7 *p)
144{
145  #ifdef PPMD_32BIT
146  CPpmd7_Node headItem;
147  CPpmd7_Node_Ref head = &headItem;
148  #else
149  CPpmd7_Node_Ref head = p->AlignOffset + p->Size;
150  #endif
151   
152  CPpmd7_Node_Ref n = head;
153  unsigned i;
154 
155  p->GlueCount = 255;
156 
157  /* create doubly-linked list of free blocks */
158  for (i = 0; i < PPMD_NUM_INDEXES; i++)
159  {
160    UInt16 nu = I2U(i);
161    CPpmd7_Node_Ref next = (CPpmd7_Node_Ref)p->FreeList[i];
162    p->FreeList[i] = 0;
163    while (next != 0)
164    {
165      CPpmd7_Node *node = NODE(next);
166      node->Next = n;
167      n = NODE(n)->Prev = next;
168      next = *(const CPpmd7_Node_Ref *)node;
169      node->Stamp = 0;
170      node->NU = (UInt16)nu;
171    }
172  }
173  NODE(head)->Stamp = 1;
174  NODE(head)->Next = n;
175  NODE(n)->Prev = head;
176  if (p->LoUnit != p->HiUnit)
177    ((CPpmd7_Node *)p->LoUnit)->Stamp = 1;
178   
179  /* Glue free blocks */
180  while (n != head)
181  {
182    CPpmd7_Node *node = NODE(n);
183    UInt32 nu = (UInt32)node->NU;
184    for (;;)
185    {
186      CPpmd7_Node *node2 = NODE(n) + nu;
187      nu += node2->NU;
188      if (node2->Stamp != 0 || nu >= 0x10000)
189        break;
190      NODE(node2->Prev)->Next = node2->Next;
191      NODE(node2->Next)->Prev = node2->Prev;
192      node->NU = (UInt16)nu;
193    }
194    n = node->Next;
195  }
196   
197  /* Fill lists of free blocks */
198  for (n = NODE(head)->Next; n != head;)
199  {
200    CPpmd7_Node *node = NODE(n);
201    unsigned nu;
202    CPpmd7_Node_Ref next = node->Next;
203    for (nu = node->NU; nu > 128; nu -= 128, node += 128)
204      InsertNode(p, node, PPMD_NUM_INDEXES - 1);
205    if (I2U(i = U2I(nu)) != nu)
206    {
207      unsigned k = I2U(--i);
208      InsertNode(p, node + k, nu - k - 1);
209    }
210    InsertNode(p, node, i);
211    n = next;
212  }
213}
214 
215static void *AllocUnitsRare(CPpmd7 *p, unsigned indx)
216{
217  unsigned i;
218  void *retVal;
219  if (p->GlueCount == 0)
220  {
221    GlueFreeBlocks(p);
222    if (p->FreeList[indx] != 0)
223      return RemoveNode(p, indx);
224  }
225  i = indx;
226  do
227  {
228    if (++i == PPMD_NUM_INDEXES)
229    {
230      UInt32 numBytes = U2B(I2U(indx));
231      p->GlueCount--;
232      return ((UInt32)(p->UnitsStart - p->Text) > numBytes) ? (p->UnitsStart -= numBytes) : (NULL);
233    }
234  }
235  while (p->FreeList[i] == 0);
236  retVal = RemoveNode(p, i);
237  SplitBlock(p, retVal, i, indx);
238  return retVal;
239}
240 
241static void *AllocUnits(CPpmd7 *p, unsigned indx)
242{
243  UInt32 numBytes;
244  if (p->FreeList[indx] != 0)
245    return RemoveNode(p, indx);
246  numBytes = U2B(I2U(indx));
247  if (numBytes <= (UInt32)(p->HiUnit - p->LoUnit))
248  {
249    void *retVal = p->LoUnit;
250    p->LoUnit += numBytes;
251    return retVal;
252  }
253  return AllocUnitsRare(p, indx);
254}
255 
256#define MyMem12Cpy(dest, src, num) \
257  { UInt32 *d = (UInt32 *)dest; const UInt32 *s = (const UInt32 *)src; UInt32 n = num; \
258    do { d[0] = s[0]; d[1] = s[1]; d[2] = s[2]; s += 3; d += 3; } while(--n); }
259 
260static void *ShrinkUnits(CPpmd7 *p, void *oldPtr, unsigned oldNU, unsigned newNU)
261{
262  unsigned i0 = U2I(oldNU);
263  unsigned i1 = U2I(newNU);
264  if (i0 == i1)
265    return oldPtr;
266  if (p->FreeList[i1] != 0)
267  {
268    void *ptr = RemoveNode(p, i1);
269    MyMem12Cpy(ptr, oldPtr, newNU);
270    InsertNode(p, oldPtr, i0);
271    return ptr;
272  }
273  SplitBlock(p, oldPtr, i0, i1);
274  return oldPtr;
275}
276 
277#define SUCCESSOR(p) ((CPpmd_Void_Ref)((p)->SuccessorLow | ((UInt32)(p)->SuccessorHigh << 16)))
278 
279static void SetSuccessor(CPpmd_State *p, CPpmd_Void_Ref v)
280{
281  (p)->SuccessorLow = (UInt16)((UInt32)(v) & 0xFFFF);
282  (p)->SuccessorHigh = (UInt16)(((UInt32)(v) >> 16) & 0xFFFF);
283}
284 
285static void RestartModel(CPpmd7 *p)
286{
287  unsigned i, k, m;
288 
289  memset(p->FreeList, 0, sizeof(p->FreeList));
290  p->Text = p->Base + p->AlignOffset;
291  p->HiUnit = p->Text + p->Size;
292  p->LoUnit = p->UnitsStart = p->HiUnit - p->Size / 8 / UNIT_SIZE * 7 * UNIT_SIZE;
293  p->GlueCount = 0;
294 
295  p->OrderFall = p->MaxOrder;
296  p->RunLength = p->InitRL = -(Int32)((p->MaxOrder < 12) ? p->MaxOrder : 12) - 1;
297  p->PrevSuccess = 0;
298 
299  p->MinContext = p->MaxContext = (CTX_PTR)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */
300  p->MinContext->Suffix = 0;
301  p->MinContext->NumStats = 256;
302  p->MinContext->SummFreq = 256 + 1;
303  p->FoundState = (CPpmd_State *)p->LoUnit; /* AllocUnits(p, PPMD_NUM_INDEXES - 1); */
304  p->LoUnit += U2B(256 / 2);
305  p->MinContext->Stats = REF(p->FoundState);
306  for (i = 0; i < 256; i++)
307  {
308    CPpmd_State *s = &p->FoundState[i];
309    s->Symbol = (Byte)i;
310    s->Freq = 1;
311    SetSuccessor(s, 0);
312  }
313 
314  for (i = 0; i < 128; i++)
315    for (k = 0; k < 8; k++)
316    {
317      UInt16 *dest = p->BinSumm[i] + k;
318      UInt16 val = (UInt16)(PPMD_BIN_SCALE - kInitBinEsc[k] / (i + 2));
319      for (m = 0; m < 64; m += 8)
320        dest[m] = val;
321    }
322   
323  for (i = 0; i < 25; i++)
324    for (k = 0; k < 16; k++)
325    {
326      CPpmd_See *s = &p->See[i][k];
327      s->Summ = (UInt16)((5 * i + 10) << (s->Shift = PPMD_PERIOD_BITS - 4));
328      s->Count = 4;
329    }
330}
331 
332void Ppmd7_Init(CPpmd7 *p, unsigned maxOrder)
333{
334  p->MaxOrder = maxOrder;
335  RestartModel(p);
336  p->DummySee.Shift = PPMD_PERIOD_BITS;
337  p->DummySee.Summ = 0; /* unused */
338  p->DummySee.Count = 64; /* unused */
339}
340 
341static CTX_PTR CreateSuccessors(CPpmd7 *p, Bool skip)
342{
343  CPpmd_State upState;
344  CTX_PTR c = p->MinContext;
345  CPpmd_Byte_Ref upBranch = (CPpmd_Byte_Ref)SUCCESSOR(p->FoundState);
346  CPpmd_State *ps[PPMD7_MAX_ORDER];
347  unsigned numPs = 0;
348   
349  if (!skip)
350    ps[numPs++] = p->FoundState;
351   
352  while (c->Suffix)
353  {
354    CPpmd_Void_Ref successor;
355    CPpmd_State *s;
356    c = SUFFIX(c);
357    if (c->NumStats != 1)
358    {
359      for (s = STATS(c); s->Symbol != p->FoundState->Symbol; s++);
360    }
361    else
362      s = ONE_STATE(c);
363    successor = SUCCESSOR(s);
364    if (successor != upBranch)
365    {
366      c = CTX(successor);
367      if (numPs == 0)
368        return c;
369      break;
370    }
371    ps[numPs++] = s;
372  }
373   
374  upState.Symbol = *(const Byte *)Ppmd7_GetPtr(p, upBranch);
375  SetSuccessor(&upState, upBranch + 1);
376   
377  if (c->NumStats == 1)
378    upState.Freq = ONE_STATE(c)->Freq;
379  else
380  {
381    UInt32 cf, s0;
382    CPpmd_State *s;
383    for (s = STATS(c); s->Symbol != upState.Symbol; s++);
384    cf = s->Freq - 1;
385    s0 = c->SummFreq - c->NumStats - cf;
386    upState.Freq = (Byte)(1 + ((2 * cf <= s0) ? (5 * cf > s0) : ((2 * cf + 3 * s0 - 1) / (2 * s0))));
387  }
388 
389  do
390  {
391    /* Create Child */
392    CTX_PTR c1; /* = AllocContext(p); */
393    if (p->HiUnit != p->LoUnit)
394      c1 = (CTX_PTR)(p->HiUnit -= UNIT_SIZE);
395    else if (p->FreeList[0] != 0)
396      c1 = (CTX_PTR)RemoveNode(p, 0);
397    else
398    {
399      c1 = (CTX_PTR)AllocUnitsRare(p, 0);
400      if (!c1)
401        return NULL;
402    }
403    c1->NumStats = 1;
404    *ONE_STATE(c1) = upState;
405    c1->Suffix = REF(c);
406    SetSuccessor(ps[--numPs], REF(c1));
407    c = c1;
408  }
409  while (numPs != 0);
410   
411  return c;
412}
413 
414static void SwapStates(CPpmd_State *t1, CPpmd_State *t2)
415{
416  CPpmd_State tmp = *t1;
417  *t1 = *t2;
418  *t2 = tmp;
419}
420 
421static void UpdateModel(CPpmd7 *p)
422{
423  CPpmd_Void_Ref successor, fSuccessor = SUCCESSOR(p->FoundState);
424  CTX_PTR c;
425  unsigned s0, ns;
426   
427  if (p->FoundState->Freq < MAX_FREQ / 4 && p->MinContext->Suffix != 0)
428  {
429    c = SUFFIX(p->MinContext);
430     
431    if (c->NumStats == 1)
432    {
433      CPpmd_State *s = ONE_STATE(c);
434      if (s->Freq < 32)
435        s->Freq++;
436    }
437    else
438    {
439      CPpmd_State *s = STATS(c);
440      if (s->Symbol != p->FoundState->Symbol)
441      {
442        do { s++; } while (s->Symbol != p->FoundState->Symbol);
443        if (s[0].Freq >= s[-1].Freq)
444        {
445          SwapStates(&s[0], &s[-1]);
446          s--;
447        }
448      }
449      if (s->Freq < MAX_FREQ - 9)
450      {
451        s->Freq += 2;
452        c->SummFreq += 2;
453      }
454    }
455  }
456 
457  if (p->OrderFall == 0)
458  {
459    p->MinContext = p->MaxContext = CreateSuccessors(p, True);
460    if (p->MinContext == 0)
461    {
462      RestartModel(p);
463      return;
464    }
465    SetSuccessor(p->FoundState, REF(p->MinContext));
466    return;
467  }
468   
469  *p->Text++ = p->FoundState->Symbol;
470  successor = REF(p->Text);
471  if (p->Text >= p->UnitsStart)
472  {
473    RestartModel(p);
474    return;
475  }
476   
477  if (fSuccessor)
478  {
479    if (fSuccessor <= successor)
480    {
481      CTX_PTR cs = CreateSuccessors(p, False);
482      if (cs == NULL)
483      {
484        RestartModel(p);
485        return;
486      }
487      fSuccessor = REF(cs);
488    }
489    if (--p->OrderFall == 0)
490    {
491      successor = fSuccessor;
492      p->Text -= (p->MaxContext != p->MinContext);
493    }
494  }
495  else
496  {
497    SetSuccessor(p->FoundState, successor);
498    fSuccessor = REF(p->MinContext);
499  }
500   
501  s0 = p->MinContext->SummFreq - (ns = p->MinContext->NumStats) - (p->FoundState->Freq - 1);
502   
503  for (c = p->MaxContext; c != p->MinContext; c = SUFFIX(c))
504  {
505    unsigned ns1;
506    UInt32 cf, sf;
507    if ((ns1 = c->NumStats) != 1)
508    {
509      if ((ns1 & 1) == 0)
510      {
511        /* Expand for one UNIT */
512        unsigned oldNU = ns1 >> 1;
513        unsigned i = U2I(oldNU);
514        if (i != U2I(oldNU + 1))
515        {
516          void *ptr = AllocUnits(p, i + 1);
517          void *oldPtr;
518          if (!ptr)
519          {
520            RestartModel(p);
521            return;
522          }
523          oldPtr = STATS(c);
524          MyMem12Cpy(ptr, oldPtr, oldNU);
525          InsertNode(p, oldPtr, i);
526          c->Stats = STATS_REF(ptr);
527        }
528      }
529      c->SummFreq = (UInt16)(c->SummFreq + (2 * ns1 < ns) + 2 * ((4 * ns1 <= ns) & (c->SummFreq <= 8 * ns1)));
530    }
531    else
532    {
533      CPpmd_State *s = (CPpmd_State*)AllocUnits(p, 0);
534      if (!s)
535      {
536        RestartModel(p);
537        return;
538      }
539      *s = *ONE_STATE(c);
540      c->Stats = REF(s);
541      if (s->Freq < MAX_FREQ / 4 - 1)
542        s->Freq <<= 1;
543      else
544        s->Freq = MAX_FREQ - 4;
545      c->SummFreq = (UInt16)(s->Freq + p->InitEsc + (ns > 3));
546    }
547    cf = 2 * (UInt32)p->FoundState->Freq * (c->SummFreq + 6);
548    sf = (UInt32)s0 + c->SummFreq;
549    if (cf < 6 * sf)
550    {
551      cf = 1 + (cf > sf) + (cf >= 4 * sf);
552      c->SummFreq += 3;
553    }
554    else
555    {
556      cf = 4 + (cf >= 9 * sf) + (cf >= 12 * sf) + (cf >= 15 * sf);
557      c->SummFreq = (UInt16)(c->SummFreq + cf);
558    }
559    {
560      CPpmd_State *s = STATS(c) + ns1;
561      SetSuccessor(s, successor);
562      s->Symbol = p->FoundState->Symbol;
563      s->Freq = (Byte)cf;
564      c->NumStats = (UInt16)(ns1 + 1);
565    }
566  }
567  p->MaxContext = p->MinContext = CTX(fSuccessor);
568}
569   
570static void Rescale(CPpmd7 *p)
571{
572  unsigned i, adder, sumFreq, escFreq;
573  CPpmd_State *stats = STATS(p->MinContext);
574  CPpmd_State *s = p->FoundState;
575  {
576    CPpmd_State tmp = *s;
577    for (; s != stats; s--)
578      s[0] = s[-1];
579    *s = tmp;
580  }
581  escFreq = p->MinContext->SummFreq - s->Freq;
582  s->Freq += 4;
583  adder = (p->OrderFall != 0);
584  s->Freq = (Byte)((s->Freq + adder) >> 1);
585  sumFreq = s->Freq;
586   
587  i = p->MinContext->NumStats - 1;
588  do
589  {
590    escFreq -= (++s)->Freq;
591    s->Freq = (Byte)((s->Freq + adder) >> 1);
592    sumFreq += s->Freq;
593    if (s[0].Freq > s[-1].Freq)
594    {
595      CPpmd_State *s1 = s;
596      CPpmd_State tmp = *s1;
597      do
598        s1[0] = s1[-1];
599      while (--s1 != stats && tmp.Freq > s1[-1].Freq);
600      *s1 = tmp;
601    }
602  }
603  while (--i);
604   
605  if (s->Freq == 0)
606  {
607    unsigned numStats = p->MinContext->NumStats;
608    unsigned n0, n1;
609    do { i++; } while ((--s)->Freq == 0);
610    escFreq += i;
611    p->MinContext->NumStats = (UInt16)(p->MinContext->NumStats - i);
612    if (p->MinContext->NumStats == 1)
613    {
614      CPpmd_State tmp = *stats;
615      do
616      {
617        tmp.Freq = (Byte)(tmp.Freq - (tmp.Freq >> 1));
618        escFreq >>= 1;
619      }
620      while (escFreq > 1);
621      InsertNode(p, stats, U2I(((numStats + 1) >> 1)));
622      *(p->FoundState = ONE_STATE(p->MinContext)) = tmp;
623      return;
624    }
625    n0 = (numStats + 1) >> 1;
626    n1 = (p->MinContext->NumStats + 1) >> 1;
627    if (n0 != n1)
628      p->MinContext->Stats = STATS_REF(ShrinkUnits(p, stats, n0, n1));
629  }
630  p->MinContext->SummFreq = (UInt16)(sumFreq + escFreq - (escFreq >> 1));
631  p->FoundState = STATS(p->MinContext);
632}
633 
634CPpmd_See *Ppmd7_MakeEscFreq(CPpmd7 *p, unsigned numMasked, UInt32 *escFreq)
635{
636  CPpmd_See *see;
637  unsigned nonMasked = p->MinContext->NumStats - numMasked;
638  if (p->MinContext->NumStats != 256)
639  {
640    see = p->See[p->NS2Indx[nonMasked - 1]] +
641        (nonMasked < (unsigned)SUFFIX(p->MinContext)->NumStats - p->MinContext->NumStats) +
642        2 * (p->MinContext->SummFreq < 11 * p->MinContext->NumStats) +
643        4 * (numMasked > nonMasked) +
644        p->HiBitsFlag;
645    {
646      unsigned r = (see->Summ >> see->Shift);
647      see->Summ = (UInt16)(see->Summ - r);
648      *escFreq = r + (r == 0);
649    }
650  }
651  else
652  {
653    see = &p->DummySee;
654    *escFreq = 1;
655  }
656  return see;
657}
658 
659static void NextContext(CPpmd7 *p)
660{
661  CTX_PTR c = CTX(SUCCESSOR(p->FoundState));
662  if (p->OrderFall == 0 && (Byte *)c > p->Text)
663    p->MinContext = p->MaxContext = c;
664  else
665    UpdateModel(p);
666}
667 
668void Ppmd7_Update1(CPpmd7 *p)
669{
670  CPpmd_State *s = p->FoundState;
671  s->Freq += 4;
672  p->MinContext->SummFreq += 4;
673  if (s[0].Freq > s[-1].Freq)
674  {
675    SwapStates(&s[0], &s[-1]);
676    p->FoundState = --s;
677    if (s->Freq > MAX_FREQ)
678      Rescale(p);
679  }
680  NextContext(p);
681}
682 
683void Ppmd7_Update1_0(CPpmd7 *p)
684{
685  p->PrevSuccess = (2 * p->FoundState->Freq > p->MinContext->SummFreq);
686  p->RunLength += p->PrevSuccess;
687  p->MinContext->SummFreq += 4;
688  if ((p->FoundState->Freq += 4) > MAX_FREQ)
689    Rescale(p);
690  NextContext(p);
691}
692 
693void Ppmd7_UpdateBin(CPpmd7 *p)
694{
695  p->FoundState->Freq = (Byte)(p->FoundState->Freq + (p->FoundState->Freq < 128 ? 1: 0));
696  p->PrevSuccess = 1;
697  p->RunLength++;
698  NextContext(p);
699}
700 
701void Ppmd7_Update2(CPpmd7 *p)
702{
703  p->MinContext->SummFreq += 4;
704  if ((p->FoundState->Freq += 4) > MAX_FREQ)
705    Rescale(p);
706  p->RunLength = p->InitRL;
707  UpdateModel(p);
708}
src/lib/lib7z/Alloc.c
r0r14440
1/* Alloc.c -- Memory allocation functions
22008-09-24
3Igor Pavlov
4Public domain */
5 
6#ifdef _WIN32_7Z
7#include <windows.h>
8#endif
9#include <stdlib.h>
10 
11#include "Alloc.h"
12 
13/* #define _SZ_ALLOC_DEBUG */
14 
15/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */
16#ifdef _SZ_ALLOC_DEBUG
17#include <stdio.h>
18int g_allocCount = 0;
19int g_allocCountMid = 0;
20int g_allocCountBig = 0;
21#endif
22 
23void *MyAlloc(size_t size)
24{
25  if (size == 0)
26    return 0;
27  #ifdef _SZ_ALLOC_DEBUG
28  {
29    void *p = malloc(size);
30    fprintf(stderr, "\nAlloc %10d bytes, count = %10d,  addr = %8X", size, g_allocCount++, (unsigned)p);
31    return p;
32  }
33  #else
34  return malloc(size);
35  #endif
36}
37 
38void MyFree(void *address)
39{
40  #ifdef _SZ_ALLOC_DEBUG
41  if (address != 0)
42    fprintf(stderr, "\nFree; count = %10d,  addr = %8X", --g_allocCount, (unsigned)address);
43  #endif
44  free(address);
45}
46 
47#ifdef _WIN32_7Z
48 
49void *MidAlloc(size_t size)
50{
51  if (size == 0)
52    return 0;
53  #ifdef _SZ_ALLOC_DEBUG
54  fprintf(stderr, "\nAlloc_Mid %10d bytes;  count = %10d", size, g_allocCountMid++);
55  #endif
56  return VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE);
57}
58 
59void MidFree(void *address)
60{
61  #ifdef _SZ_ALLOC_DEBUG
62  if (address != 0)
63    fprintf(stderr, "\nFree_Mid; count = %10d", --g_allocCountMid);
64  #endif
65  if (address == 0)
66    return;
67  VirtualFree(address, 0, MEM_RELEASE);
68}
69 
70#ifndef MEM_LARGE_PAGES
71#undef _7ZIP_LARGE_PAGES
72#endif
73 
74#ifdef _7ZIP_LARGE_PAGES
75SIZE_T g_LargePageSize = 0;
76typedef SIZE_T (WINAPI *GetLargePageMinimumP)();
77#endif
78 
79void SetLargePageSize()
80{
81  #ifdef _7ZIP_LARGE_PAGES
82  SIZE_T size = 0;
83  GetLargePageMinimumP largePageMinimum = (GetLargePageMinimumP)
84        GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetLargePageMinimum");
85  if (largePageMinimum == 0)
86    return;
87  size = largePageMinimum();
88  if (size == 0 || (size & (size - 1)) != 0)
89    return;
90  g_LargePageSize = size;
91  #endif
92}
93 
94 
95void *BigAlloc(size_t size)
96{
97  if (size == 0)
98    return 0;
99  #ifdef _SZ_ALLOC_DEBUG
100  fprintf(stderr, "\nAlloc_Big %10d bytes;  count = %10d", size, g_allocCountBig++);
101  #endif
102   
103  #ifdef _7ZIP_LARGE_PAGES
104  if (g_LargePageSize != 0 && g_LargePageSize <= (1 << 30) && size >= (1 << 18))
105  {
106    void *res = VirtualAlloc(0, (size + g_LargePageSize - 1) & (~(g_LargePageSize - 1)),
107        MEM_COMMIT | MEM_LARGE_PAGES, PAGE_READWRITE);
108    if (res != 0)
109      return res;
110  }
111  #endif
112  return VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE);
113}
114 
115void BigFree(void *address)
116{
117  #ifdef _SZ_ALLOC_DEBUG
118  if (address != 0)
119    fprintf(stderr, "\nFree_Big; count = %10d", --g_allocCountBig);
120  #endif
121   
122  if (address == 0)
123    return;
124  VirtualFree(address, 0, MEM_RELEASE);
125}
126 
127#endif
src/lib/lib7z/Ppmd7.h
r0r14440
1/* Ppmd7.h -- PPMdH compression codec
22010-03-12 : Igor Pavlov : Public domain
3This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
4 
5/* This code supports virtual RangeDecoder and includes the implementation
6of RangeCoder from 7z, instead of RangeCoder from original PPMd var.H.
7If you need the compatibility with original PPMd var.H, you can use external RangeDecoder */
8 
9#ifndef __PPMD7_H
10#define __PPMD7_H
11 
12#include "Ppmd.h"
13 
14EXTERN_C_BEGIN
15 
16#define PPMD7_MIN_ORDER 2
17#define PPMD7_MAX_ORDER 64
18 
19#define PPMD7_MIN_MEM_SIZE (1 << 11)
20#define PPMD7_MAX_MEM_SIZE (0xFFFFFFFF - 12 * 3)
21 
22struct CPpmd7_Context_;
23 
24typedef
25  #ifdef PPMD_32BIT
26    struct CPpmd7_Context_ *
27  #else
28    UInt32
29  #endif
30  CPpmd7_Context_Ref;
31 
32typedef struct CPpmd7_Context_
33{
34  UInt16 NumStats;
35  UInt16 SummFreq;
36  CPpmd_State_Ref Stats;
37  CPpmd7_Context_Ref Suffix;
38} CPpmd7_Context;
39 
40#define Ppmd7Context_OneState(p) ((CPpmd_State *)&(p)->SummFreq)
41 
42typedef struct
43{
44  CPpmd7_Context *MinContext, *MaxContext;
45  CPpmd_State *FoundState;
46  unsigned OrderFall, InitEsc, PrevSuccess, MaxOrder, HiBitsFlag;
47  Int32 RunLength, InitRL; /* must be 32-bit at least */
48 
49  UInt32 Size;
50  UInt32 GlueCount;
51  Byte *Base, *LoUnit, *HiUnit, *Text, *UnitsStart;
52  UInt32 AlignOffset;
53 
54  Byte Indx2Units[PPMD_NUM_INDEXES];
55  Byte Units2Indx[128];
56  CPpmd_Void_Ref FreeList[PPMD_NUM_INDEXES];
57  Byte NS2Indx[256], NS2BSIndx[256], HB2Flag[256];
58  CPpmd_See DummySee, See[25][16];
59  UInt16 BinSumm[128][64];
60} CPpmd7;
61 
62void Ppmd7_Construct(CPpmd7 *p);
63Bool Ppmd7_Alloc(CPpmd7 *p, UInt32 size, ISzAlloc *alloc);
64void Ppmd7_Free(CPpmd7 *p, ISzAlloc *alloc);
65void Ppmd7_Init(CPpmd7 *p, unsigned maxOrder);
66#define Ppmd7_WasAllocated(p) ((p)->Base != NULL)
67 
68 
69/* ---------- Internal Functions ---------- */
70 
71extern const Byte PPMD7_kExpEscape[16];
72 
73#ifdef PPMD_32BIT
74  #define Ppmd7_GetPtr(p, ptr) (ptr)
75  #define Ppmd7_GetContext(p, ptr) (ptr)
76  #define Ppmd7_GetStats(p, ctx) ((ctx)->Stats)
77#else
78  #define Ppmd7_GetPtr(p, offs) ((void *)((p)->Base + (offs)))
79  #define Ppmd7_GetContext(p, offs) ((CPpmd7_Context *)Ppmd7_GetPtr((p), (offs)))
80  #define Ppmd7_GetStats(p, ctx) ((CPpmd_State *)Ppmd7_GetPtr((p), ((ctx)->Stats)))
81#endif
82 
83void Ppmd7_Update1(CPpmd7 *p);
84void Ppmd7_Update1_0(CPpmd7 *p);
85void Ppmd7_Update2(CPpmd7 *p);
86void Ppmd7_UpdateBin(CPpmd7 *p);
87 
88#define Ppmd7_GetBinSumm(p) \
89    &p->BinSumm[Ppmd7Context_OneState(p->MinContext)->Freq - 1][p->PrevSuccess + \
90    p->NS2BSIndx[Ppmd7_GetContext(p, p->MinContext->Suffix)->NumStats - 1] + \
91    (p->HiBitsFlag = p->HB2Flag[p->FoundState->Symbol]) + \
92    2 * p->HB2Flag[Ppmd7Context_OneState(p->MinContext)->Symbol] + \
93    ((p->RunLength >> 26) & 0x20)]
94 
95CPpmd_See *Ppmd7_MakeEscFreq(CPpmd7 *p, unsigned numMasked, UInt32 *scale);
96 
97 
98/* ---------- Decode ---------- */
99 
100typedef struct
101{
102  UInt32 (*GetThreshold)(void *p, UInt32 total);
103  void (*Decode)(void *p, UInt32 start, UInt32 size);
104  UInt32 (*DecodeBit)(void *p, UInt32 size0);
105} IPpmd7_RangeDec;
106 
107typedef struct
108{
109  IPpmd7_RangeDec p;
110  UInt32 Range;
111  UInt32 Code;
112  IByteIn *Stream;
113} CPpmd7z_RangeDec;
114 
115void Ppmd7z_RangeDec_CreateVTable(CPpmd7z_RangeDec *p);
116Bool Ppmd7z_RangeDec_Init(CPpmd7z_RangeDec *p);
117#define Ppmd7z_RangeDec_IsFinishedOK(p) ((p)->Code == 0)
118 
119int Ppmd7_DecodeSymbol(CPpmd7 *p, IPpmd7_RangeDec *rc);
120 
121 
122/* ---------- Encode ---------- */
123 
124typedef struct
125{
126  UInt64 Low;
127  UInt32 Range;
128  Byte Cache;
129  UInt64 CacheSize;
130  IByteOut *Stream;
131} CPpmd7z_RangeEnc;
132 
133void Ppmd7z_RangeEnc_Init(CPpmd7z_RangeEnc *p);
134void Ppmd7z_RangeEnc_FlushData(CPpmd7z_RangeEnc *p);
135 
136void Ppmd7_EncodeSymbol(CPpmd7 *p, CPpmd7z_RangeEnc *rc, int symbol);
137 
138EXTERN_C_END
139 
140#endif
src/lib/lib7z/Lzma86Dec.c
r0r14440
1/* Lzma86Dec.c -- LZMA + x86 (BCJ) Filter Decoder
22009-08-14 : Igor Pavlov : Public domain */
3 
4#include "Lzma86.h"
5 
6#include "Alloc.h"
7#include "Bra.h"
8#include "LzmaDec.h"
9 
10static void *SzAlloc(void *p, size_t size) { p = p; return MyAlloc(size); }
11static void SzFree(void *p, void *address) { p = p; MyFree(address); }
12 
13SRes Lzma86_GetUnpackSize(const Byte *src, SizeT srcLen, UInt64 *unpackSize)
14{
15  unsigned i;
16  if (srcLen < LZMA86_HEADER_SIZE)
17    return SZ_ERROR_INPUT_EOF;
18  *unpackSize = 0;
19  for (i = 0; i < sizeof(UInt64); i++)
20    *unpackSize += ((UInt64)src[LZMA86_SIZE_OFFSET + i]) << (8 * i);
21  return SZ_OK;
22}
23 
24SRes Lzma86_Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen)
25{
26  ISzAlloc g_Alloc = { SzAlloc, SzFree };
27  SRes res;
28  int useFilter;
29  SizeT inSizePure;
30  ELzmaStatus status;
31 
32  if (*srcLen < LZMA86_HEADER_SIZE)
33    return SZ_ERROR_INPUT_EOF;
34 
35  useFilter = src[0];
36 
37  if (useFilter > 1)
38  {
39    *destLen = 0;
40    return SZ_ERROR_UNSUPPORTED;
41  }
42 
43  inSizePure = *srcLen - LZMA86_HEADER_SIZE;
44  res = LzmaDecode(dest, destLen, src + LZMA86_HEADER_SIZE, &inSizePure,
45      src + 1, LZMA_PROPS_SIZE, LZMA_FINISH_ANY, &status, &g_Alloc);
46  *srcLen = inSizePure + LZMA86_HEADER_SIZE;
47  if (res != SZ_OK)
48    return res;
49  if (useFilter == 1)
50  {
51    UInt32 x86State;
52    x86_Convert_Init(x86State);
53    x86_Convert(dest, *destLen, 0, &x86State, 0);
54  }
55  return SZ_OK;
56}
src/lib/lib7z/Alloc.h
r0r14440
1/* Alloc.h -- Memory allocation functions
22009-02-07 : Igor Pavlov : Public domain */
3 
4#ifndef __COMMON_ALLOC_H
5#define __COMMON_ALLOC_H
6 
7#include <stddef.h>
8 
9#ifdef __cplusplus
10extern "C" {
11#endif
12 
13void *MyAlloc(size_t size);
14void MyFree(void *address);
15 
16#ifdef _WIN32_7Z
17 
18void SetLargePageSize();
19 
20void *MidAlloc(size_t size);
21void MidFree(void *address);
22void *BigAlloc(size_t size);
23void BigFree(void *address);
24 
25#else
26 
27#define MidAlloc(size) MyAlloc(size)
28#define MidFree(address) MyFree(address)
29#define BigAlloc(size) MyAlloc(size)
30#define BigFree(address) MyFree(address)
31 
32#endif
33 
34#ifdef __cplusplus
35}
36#endif
37 
38#endif
src/lib/lib7z/BwtSort.c
r0r14440
1/* BwtSort.c -- BWT block sorting
22008-08-17
3Igor Pavlov
4Public domain */
5 
6#include "BwtSort.h"
7#include "Sort.h"
8 
9/* #define BLOCK_SORT_USE_HEAP_SORT */
10 
11#define NO_INLINE MY_FAST_CALL
12 
13/* Don't change it !!! */
14#define kNumHashBytes 2
15#define kNumHashValues (1 << (kNumHashBytes * 8))
16 
17/* kNumRefBitsMax must be < (kNumHashBytes * 8) = 16 */
18#define kNumRefBitsMax 12
19 
20#define BS_TEMP_SIZE kNumHashValues
21 
22#ifdef BLOCK_SORT_EXTERNAL_FLAGS
23 
24/* 32 Flags in UInt32 word */
25#define kNumFlagsBits 5
26#define kNumFlagsInWord (1 << kNumFlagsBits)
27#define kFlagsMask (kNumFlagsInWord - 1)
28#define kAllFlags 0xFFFFFFFF
29 
30#else
31 
32#define kNumBitsMax 20
33#define kIndexMask ((1 << kNumBitsMax) - 1)
34#define kNumExtraBits (32 - kNumBitsMax)
35#define kNumExtra0Bits (kNumExtraBits - 2)
36#define kNumExtra0Mask ((1 << kNumExtra0Bits) - 1)
37 
38#define SetFinishedGroupSize(p, size) \
39  {  *(p) |= ((((size) - 1) & kNumExtra0Mask) << kNumBitsMax); \
40    if ((size) > (1 << kNumExtra0Bits)) { \
41    *(p) |= 0x40000000;  *((p) + 1) |= ((((size) - 1)>> kNumExtra0Bits) << kNumBitsMax); } } \
42 
43static void SetGroupSize(UInt32 *p, UInt32 size)
44{
45  if (--size == 0)
46    return;
47  *p |= 0x80000000 | ((size & kNumExtra0Mask) << kNumBitsMax);
48  if (size >= (1 << kNumExtra0Bits))
49  {
50    *p |= 0x40000000;
51    p[1] |= ((size >> kNumExtra0Bits) << kNumBitsMax);
52  }
53}
54 
55#endif
56 
57/*
58SortGroup - is recursive Range-Sort function with HeapSort optimization for small blocks
59  "range" is not real range. It's only for optimization.
60returns: 1 - if there are groups, 0 - no more groups
61*/
62 
63UInt32 NO_INLINE SortGroup(UInt32 BlockSize, UInt32 NumSortedBytes, UInt32 groupOffset, UInt32 groupSize, int NumRefBits, UInt32 *Indices
64  #ifndef BLOCK_SORT_USE_HEAP_SORT
65  , UInt32 left, UInt32 range
66  #endif
67  )
68{
69  UInt32 *ind2 = Indices + groupOffset;
70  UInt32 *Groups;
71  if (groupSize <= 1)
72  {
73    /*
74    #ifndef BLOCK_SORT_EXTERNAL_FLAGS
75    SetFinishedGroupSize(ind2, 1);
76    #endif
77    */
78    return 0;
79  }
80  Groups = Indices + BlockSize + BS_TEMP_SIZE;
81  if (groupSize <= ((UInt32)1 << NumRefBits)
82      #ifndef BLOCK_SORT_USE_HEAP_SORT
83      && groupSize <= range
84      #endif
85      )
86  {
87    UInt32 *temp = Indices + BlockSize;
88    UInt32 j;
89    UInt32 mask, thereAreGroups, group, cg;
90    {
91      UInt32 gPrev;
92      UInt32 gRes = 0;
93      {
94        UInt32 sp = ind2[0] + NumSortedBytes;
95        if (sp >= BlockSize) sp -= BlockSize;
96        gPrev = Groups[sp];
97        temp[0] = (gPrev << NumRefBits);
98      }
99       
100      for (j = 1; j < groupSize; j++)
101      {
102        UInt32 sp = ind2[j] + NumSortedBytes;
103        UInt32 g;
104        if (sp >= BlockSize) sp -= BlockSize;
105        g = Groups[sp];
106        temp[j] = (g << NumRefBits) | j;
107        gRes |= (gPrev ^ g);
108      }
109      if (gRes == 0)
110      {
111        #ifndef BLOCK_SORT_EXTERNAL_FLAGS
112        SetGroupSize(ind2, groupSize);
113        #endif
114        return 1;
115      }
116    }
117     
118    HeapSort(temp, groupSize);
119    mask = ((1 << NumRefBits) - 1);
120    thereAreGroups = 0;
121     
122    group = groupOffset;
123    cg = (temp[0] >> NumRefBits);
124    temp[0] = ind2[temp[0] & mask];
125 
126    {
127    #ifdef BLOCK_SORT_EXTERNAL_FLAGS
128    UInt32 *Flags = Groups + BlockSize;
129    #else
130    UInt32 prevGroupStart = 0;
131    #endif
132     
133    for (j = 1; j < groupSize; j++)
134    {
135      UInt32 val = temp[j];
136      UInt32 cgCur = (val >> NumRefBits);
137       
138      if (cgCur != cg)
139      {
140        cg = cgCur;
141        group = groupOffset + j;
142 
143        #ifdef BLOCK_SORT_EXTERNAL_FLAGS
144        {
145        UInt32 t = group - 1;
146        Flags[t >> kNumFlagsBits] &= ~(1 << (t & kFlagsMask));
147        }
148        #else
149        SetGroupSize(temp + prevGroupStart, j - prevGroupStart);
150        prevGroupStart = j;
151        #endif
152      }
153      else
154        thereAreGroups = 1;
155      {
156      UInt32 ind = ind2[val & mask];
157      temp[j] = ind;
158      Groups[ind] = group;
159      }
160    }
161 
162    #ifndef BLOCK_SORT_EXTERNAL_FLAGS
163    SetGroupSize(temp + prevGroupStart, j - prevGroupStart);
164    #endif
165    }
166 
167    for (j = 0; j < groupSize; j++)
168      ind2[j] = temp[j];
169    return thereAreGroups;
170  }
171 
172  /* Check that all strings are in one group (cannot sort) */
173  {
174    UInt32 group, j;
175    UInt32 sp = ind2[0] + NumSortedBytes; if (sp >= BlockSize) sp -= BlockSize;
176    group = Groups[sp];
177    for (j = 1; j < groupSize; j++)
178    {
179      sp = ind2[j] + NumSortedBytes; if (sp >= BlockSize) sp -= BlockSize;
180      if (Groups[sp] != group)
181        break;
182    }
183    if (j == groupSize)
184    {
185      #ifndef BLOCK_SORT_EXTERNAL_FLAGS
186      SetGroupSize(ind2, groupSize);
187      #endif
188      return 1;
189    }
190  }
191 
192  #ifndef BLOCK_SORT_USE_HEAP_SORT
193  {
194  /* ---------- Range Sort ---------- */
195  UInt32 i;
196  UInt32 mid;
197  for (;;)
198  {
199    UInt32 j;
200    if (range <= 1)
201    {
202      #ifndef BLOCK_SORT_EXTERNAL_FLAGS
203      SetGroupSize(ind2, groupSize);
204      #endif
205      return 1;
206    }
207    mid = left + ((range + 1) >> 1);
208    j = groupSize;
209    i = 0;
210    do
211    {
212      UInt32 sp = ind2[i] + NumSortedBytes; if (sp >= BlockSize) sp -= BlockSize;
213      if (Groups[sp] >= mid)
214      {
215        for (j--; j > i; j--)
216        {
217          sp = ind2[j] + NumSortedBytes; if (sp >= BlockSize) sp -= BlockSize;
218          if (Groups[sp] < mid)
219          {
220            UInt32 temp = ind2[i]; ind2[i] = ind2[j]; ind2[j] = temp;
221            break;
222          }
223        }
224        if (i >= j)
225          break;
226      }
227    }
228    while (++i < j);
229    if (i == 0)
230    {
231      range = range - (mid - left);
232      left = mid;
233    }
234    else if (i == groupSize)
235      range = (mid - left);
236    else
237      break;
238  }
239 
240  #ifdef BLOCK_SORT_EXTERNAL_FLAGS
241  {
242    UInt32 t = (groupOffset + i - 1);
243    UInt32 *Flags = Groups + BlockSize;
244    Flags[t >> kNumFlagsBits] &= ~(1 << (t & kFlagsMask));
245  }
246  #endif
247 
248  {
249    UInt32 j;
250    for (j = i; j < groupSize; j++)
251      Groups[ind2[j]] = groupOffset + i;
252  }
253 
254  {
255  UInt32 res = SortGroup(BlockSize, NumSortedBytes, groupOffset, i, NumRefBits, Indices, left, mid - left);
256  return res | SortGroup(BlockSize, NumSortedBytes, groupOffset + i, groupSize - i, NumRefBits, Indices, mid, range - (mid - left));
257  }
258 
259  }
260 
261  #else
262 
263  /* ---------- Heap Sort ---------- */
264 
265  {
266    UInt32 j;
267    for (j = 0; j < groupSize; j++)
268    {
269      UInt32 sp = ind2[j] + NumSortedBytes; if (sp >= BlockSize) sp -= BlockSize;
270      ind2[j] = sp;
271    }
272 
273    HeapSortRef(ind2, Groups, groupSize);
274 
275    /* Write Flags */
276    {
277    UInt32 sp = ind2[0];
278    UInt32 group = Groups[sp];
279 
280    #ifdef BLOCK_SORT_EXTERNAL_FLAGS
281    UInt32 *Flags = Groups + BlockSize;
282    #else
283    UInt32 prevGroupStart = 0;
284    #endif
285 
286    for (j = 1; j < groupSize; j++)
287    {
288      sp = ind2[j];
289      if (Groups[sp] != group)
290      {
291        group = Groups[sp];
292        #ifdef BLOCK_SORT_EXTERNAL_FLAGS
293        {
294        UInt32 t = groupOffset + j - 1;
295        Flags[t >> kNumFlagsBits] &= ~(1 << (t & kFlagsMask));
296        }
297        #else
298        SetGroupSize(ind2 + prevGroupStart, j - prevGroupStart);
299        prevGroupStart = j;
300        #endif
301      }
302    }
303 
304    #ifndef BLOCK_SORT_EXTERNAL_FLAGS
305    SetGroupSize(ind2 + prevGroupStart, j - prevGroupStart);
306    #endif
307    }
308    {
309    /* Write new Groups values and Check that there are groups */
310    UInt32 thereAreGroups = 0;
311    for (j = 0; j < groupSize; j++)
312    {
313      UInt32 group = groupOffset + j;
314      #ifndef BLOCK_SORT_EXTERNAL_FLAGS
315      UInt32 subGroupSize = ((ind2[j] & ~0xC0000000) >> kNumBitsMax);
316      if ((ind2[j] & 0x40000000) != 0)
317        subGroupSize += ((ind2[j + 1] >> kNumBitsMax) << kNumExtra0Bits);
318      subGroupSize++;
319      for (;;)
320      {
321        UInt32 original = ind2[j];
322        UInt32 sp = original & kIndexMask;
323        if (sp < NumSortedBytes) sp += BlockSize; sp -= NumSortedBytes;
324        ind2[j] = sp | (original & ~kIndexMask);
325        Groups[sp] = group;
326        if (--subGroupSize == 0)
327          break;
328        j++;
329        thereAreGroups = 1;
330      }
331      #else
332      UInt32 *Flags = Groups + BlockSize;
333      for (;;)
334      {
335        UInt32 sp = ind2[j]; if (sp < NumSortedBytes) sp += BlockSize; sp -= NumSortedBytes;
336        ind2[j] = sp;
337        Groups[sp] = group;
338        if ((Flags[(groupOffset + j) >> kNumFlagsBits] & (1 << ((groupOffset + j) & kFlagsMask))) == 0)
339          break;
340        j++;
341        thereAreGroups = 1;
342      }
343      #endif
344    }
345    return thereAreGroups;
346    }
347  }
348  #endif
349}
350 
351/* conditions: blockSize > 0 */
352UInt32 BlockSort(UInt32 *Indices, const Byte *data, UInt32 blockSize)
353{
354  UInt32 *counters = Indices + blockSize;
355  UInt32 i;
356  UInt32 *Groups;
357  #ifdef BLOCK_SORT_EXTERNAL_FLAGS
358  UInt32 *Flags;
359  #endif
360 
361  /* Radix-Sort for 2 bytes */
362  for (i = 0; i < kNumHashValues; i++)
363    counters[i] = 0;
364  for (i = 0; i < blockSize - 1; i++)
365    counters[((UInt32)data[i] << 8) | data[i + 1]]++;
366  counters[((UInt32)data[i] << 8) | data[0]]++;
367 
368  Groups = counters + BS_TEMP_SIZE;
369  #ifdef BLOCK_SORT_EXTERNAL_FLAGS
370  Flags = Groups + blockSize;
371    {
372      UInt32 numWords = (blockSize + kFlagsMask) >> kNumFlagsBits;
373      for (i = 0; i < numWords; i++)
374        Flags[i] = kAllFlags;
375    }
376  #endif
377 
378  {
379    UInt32 sum = 0;
380    for (i = 0; i < kNumHashValues; i++)
381    {
382      UInt32 groupSize = counters[i];
383      if (groupSize > 0)
384      {
385        #ifdef BLOCK_SORT_EXTERNAL_FLAGS
386        UInt32 t = sum + groupSize - 1;
387        Flags[t >> kNumFlagsBits] &= ~(1 << (t & kFlagsMask));
388        #endif
389        sum += groupSize;
390      }
391      counters[i] = sum - groupSize;
392    }
393 
394    for (i = 0; i < blockSize - 1; i++)
395      Groups[i] = counters[((UInt32)data[i] << 8) | data[i + 1]];
396    Groups[i] = counters[((UInt32)data[i] << 8) | data[0]];
397 
398    for (i = 0; i < blockSize - 1; i++)
399      Indices[counters[((UInt32)data[i] << 8) | data[i + 1]]++] = i;
400    Indices[counters[((UInt32)data[i] << 8) | data[0]]++] = i;
401     
402    #ifndef BLOCK_SORT_EXTERNAL_FLAGS
403    {
404    UInt32 prev = 0;
405    for (i = 0; i < kNumHashValues; i++)
406    {
407      UInt32 prevGroupSize = counters[i] - prev;
408      if (prevGroupSize == 0)
409        continue;
410      SetGroupSize(Indices + prev, prevGroupSize);
411      prev = counters[i];
412    }
413    }
414    #endif
415  }
416 
417  {
418  int NumRefBits;
419  UInt32 NumSortedBytes;
420  for (NumRefBits = 0; ((blockSize - 1) >> NumRefBits) != 0; NumRefBits++);
421  NumRefBits = 32 - NumRefBits;
422  if (NumRefBits > kNumRefBitsMax)
423    NumRefBits = kNumRefBitsMax;
424 
425  for (NumSortedBytes = kNumHashBytes; ; NumSortedBytes <<= 1)
426  {
427    #ifndef BLOCK_SORT_EXTERNAL_FLAGS
428    UInt32 finishedGroupSize = 0;
429    #endif
430    UInt32 newLimit = 0;
431    for (i = 0; i < blockSize;)
432    {
433      UInt32 groupSize;
434      #ifdef BLOCK_SORT_EXTERNAL_FLAGS
435 
436      if ((Flags[i >> kNumFlagsBits] & (1 << (i & kFlagsMask))) == 0)
437      {
438        i++;
439        continue;
440      }
441      for (groupSize = 1;
442        (Flags[(i + groupSize) >> kNumFlagsBits] & (1 << ((i + groupSize) & kFlagsMask))) != 0;
443        groupSize++);
444       
445      groupSize++;
446 
447      #else
448 
449      groupSize = ((Indices[i] & ~0xC0000000) >> kNumBitsMax);
450      {
451      Bool finishedGroup = ((Indices[i] & 0x80000000) == 0);
452      if ((Indices[i] & 0x40000000) != 0)
453      {
454        groupSize += ((Indices[i + 1] >> kNumBitsMax) << kNumExtra0Bits);
455        Indices[i + 1] &= kIndexMask;
456      }
457      Indices[i] &= kIndexMask;
458      groupSize++;
459      if (finishedGroup || groupSize == 1)
460      {
461        Indices[i - finishedGroupSize] &= kIndexMask;
462        if (finishedGroupSize > 1)
463          Indices[i - finishedGroupSize + 1] &= kIndexMask;
464        {
465        UInt32 newGroupSize = groupSize + finishedGroupSize;
466        SetFinishedGroupSize(Indices + i - finishedGroupSize, newGroupSize);
467        finishedGroupSize = newGroupSize;
468        }
469        i += groupSize;
470        continue;
471      }
472      finishedGroupSize = 0;
473      }
474 
475      #endif
476       
477      if (NumSortedBytes >= blockSize)
478      {
479        UInt32 j;
480        for (j = 0; j < groupSize; j++)
481        {
482          UInt32 t = (i + j);
483          /* Flags[t >> kNumFlagsBits] &= ~(1 << (t & kFlagsMask)); */
484          Groups[Indices[t]] = t;
485        }
486      }
487      else
488        if (SortGroup(blockSize, NumSortedBytes, i, groupSize, NumRefBits, Indices
489          #ifndef BLOCK_SORT_USE_HEAP_SORT
490          , 0, blockSize
491          #endif
492          ) != 0)
493          newLimit = i + groupSize;
494      i += groupSize;
495    }
496    if (newLimit == 0)
497      break;
498  }
499  }
500  #ifndef BLOCK_SORT_EXTERNAL_FLAGS
501  for (i = 0; i < blockSize;)
502  {
503    UInt32 groupSize = ((Indices[i] & ~0xC0000000) >> kNumBitsMax);
504    if ((Indices[i] & 0x40000000) != 0)
505    {
506      groupSize += ((Indices[i + 1] >> kNumBitsMax) << kNumExtra0Bits);
507      Indices[i + 1] &= kIndexMask;
508    }
509    Indices[i] &= kIndexMask;
510    groupSize++;
511    i += groupSize;
512  }
513  #endif
514  return Groups[0];
515}
516 
src/lib/lib7z/Bra.c
r0r14440
1/* Bra.c -- Converters for RISC code
22010-04-16 : Igor Pavlov : Public domain */
3 
4#include "Bra.h"
5 
6SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding)
7{
8  SizeT i;
9  if (size < 4)
10    return 0;
11  size -= 4;
12  ip += 8;
13  for (i = 0; i <= size; i += 4)
14  {
15    if (data[i + 3] == 0xEB)
16    {
17      UInt32 dest;
18      UInt32 src = ((UInt32)data[i + 2] << 16) | ((UInt32)data[i + 1] << 8) | (data[i + 0]);
19      src <<= 2;
20      if (encoding)
21        dest = ip + (UInt32)i + src;
22      else
23        dest = src - (ip + (UInt32)i);
24      dest >>= 2;
25      data[i + 2] = (Byte)(dest >> 16);
26      data[i + 1] = (Byte)(dest >> 8);
27      data[i + 0] = (Byte)dest;
28    }
29  }
30  return i;
31}
32 
33SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding)
34{
35  SizeT i;
36  if (size < 4)
37    return 0;
38  size -= 4;
39  ip += 4;
40  for (i = 0; i <= size; i += 2)
41  {
42    if ((data[i + 1] & 0xF8) == 0xF0 &&
43        (data[i + 3] & 0xF8) == 0xF8)
44    {
45      UInt32 dest;
46      UInt32 src =
47        (((UInt32)data[i + 1] & 0x7) << 19) |
48        ((UInt32)data[i + 0] << 11) |
49        (((UInt32)data[i + 3] & 0x7) << 8) |
50        (data[i + 2]);
51       
52      src <<= 1;
53      if (encoding)
54        dest = ip + (UInt32)i + src;
55      else
56        dest = src - (ip + (UInt32)i);
57      dest >>= 1;
58       
59      data[i + 1] = (Byte)(0xF0 | ((dest >> 19) & 0x7));
60      data[i + 0] = (Byte)(dest >> 11);
61      data[i + 3] = (Byte)(0xF8 | ((dest >> 8) & 0x7));
62      data[i + 2] = (Byte)dest;
63      i += 2;
64    }
65  }
66  return i;
67}
68 
69SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding)
70{
71  SizeT i;
72  if (size < 4)
73    return 0;
74  size -= 4;
75  for (i = 0; i <= size; i += 4)
76  {
77    if ((data[i] >> 2) == 0x12 && (data[i + 3] & 3) == 1)
78    {
79      UInt32 src = ((UInt32)(data[i + 0] & 3) << 24) |
80        ((UInt32)data[i + 1] << 16) |
81        ((UInt32)data[i + 2] << 8) |
82        ((UInt32)data[i + 3] & (~3));
83       
84      UInt32 dest;
85      if (encoding)
86        dest = ip + (UInt32)i + src;
87      else
88        dest = src - (ip + (UInt32)i);
89      data[i + 0] = (Byte)(0x48 | ((dest >> 24) &  0x3));
90      data[i + 1] = (Byte)(dest >> 16);
91      data[i + 2] = (Byte)(dest >> 8);
92      data[i + 3] &= 0x3;
93      data[i + 3] |= dest;
94    }
95  }
96  return i;
97}
98 
99SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding)
100{
101  UInt32 i;
102  if (size < 4)
103    return 0;
104  size -= 4;
105  for (i = 0; i <= size; i += 4)
106  {
107    if ((data[i] == 0x40 && (data[i + 1] & 0xC0) == 0x00) ||
108        (data[i] == 0x7F && (data[i + 1] & 0xC0) == 0xC0))
109    {
110      UInt32 src =
111        ((UInt32)data[i + 0] << 24) |
112        ((UInt32)data[i + 1] << 16) |
113        ((UInt32)data[i + 2] << 8) |
114        ((UInt32)data[i + 3]);
115      UInt32 dest;
116       
117      src <<= 2;
118      if (encoding)
119        dest = ip + i + src;
120      else
121        dest = src - (ip + i);
122      dest >>= 2;
123       
124      dest = (((0 - ((dest >> 22) & 1)) << 22) & 0x3FFFFFFF) | (dest & 0x3FFFFF) | 0x40000000;
125 
126      data[i + 0] = (Byte)(dest >> 24);
127      data[i + 1] = (Byte)(dest >> 16);
128      data[i + 2] = (Byte)(dest >> 8);
129      data[i + 3] = (Byte)dest;
130    }
131  }
132  return i;
133}
src/lib/lib7z/Bra.h
r0r14440
1/* Bra.h -- Branch converters for executables
22009-02-07 : Igor Pavlov : Public domain */
3 
4#ifndef __BRA_H
5#define __BRA_H
6 
7#include "Types.h"
8 
9#ifdef __cplusplus
10extern "C" {
11#endif
12 
13/*
14These functions convert relative addresses to absolute addresses
15in CALL instructions to increase the compression ratio.
16   
17  In:
18    data     - data buffer
19    size     - size of data
20    ip       - current virtual Instruction Pinter (IP) value
21    state    - state variable for x86 converter
22    encoding - 0 (for decoding), 1 (for encoding)
23   
24  Out:
25    state    - state variable for x86 converter
26 
27  Returns:
28    The number of processed bytes. If you call these functions with multiple calls,
29    you must start next call with first byte after block of processed bytes.
30   
31  Type   Endian  Alignment  LookAhead
32   
33  x86    little      1          4
34  ARMT   little      2          2
35  ARM    little      4          0
36  PPC     big        4          0
37  SPARC   big        4          0
38  IA64   little     16          0
39 
40  size must be >= Alignment + LookAhead, if it's not last block.
41  If (size < Alignment + LookAhead), converter returns 0.
42 
43  Example:
44 
45    UInt32 ip = 0;
46    for ()
47    {
48      ; size must be >= Alignment + LookAhead, if it's not last block
49      SizeT processed = Convert(data, size, ip, 1);
50      data += processed;
51      size -= processed;
52      ip += processed;
53    }
54*/
55 
56#define x86_Convert_Init(state) { state = 0; }
57SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding);
58SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
59SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
60SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
61SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
62SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
63 
64#ifdef __cplusplus
65}
66#endif
67 
68#endif
src/lib/lib7z/BwtSort.h
r0r14440
1/* BwtSort.h -- BWT block sorting
22009-02-07 : Igor Pavlov : Public domain */
3 
4#ifndef __BWT_SORT_H
5#define __BWT_SORT_H
6 
7#include "Types.h"
8 
9#ifdef __cplusplus
10extern "C" {
11#endif
12 
13/* use BLOCK_SORT_EXTERNAL_FLAGS if blockSize can be > 1M */
14/* #define BLOCK_SORT_EXTERNAL_FLAGS */
15 
16#ifdef BLOCK_SORT_EXTERNAL_FLAGS
17#define BLOCK_SORT_EXTERNAL_SIZE(blockSize) ((((blockSize) + 31) >> 5))
18#else
19#define BLOCK_SORT_EXTERNAL_SIZE(blockSize) 0
20#endif
21 
22#define BLOCK_SORT_BUF_SIZE(blockSize) ((blockSize) * 2 + BLOCK_SORT_EXTERNAL_SIZE(blockSize) + (1 << 16))
23 
24UInt32 BlockSort(UInt32 *indices, const Byte *data, UInt32 blockSize);
25 
26#ifdef __cplusplus
27}
28#endif
29 
30#endif
src/lib/lib7z/Ppmd7Enc.c
r0r14440
1/* Ppmd7Enc.c -- PPMdH Encoder
22010-03-12 : Igor Pavlov : Public domain
3This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
4 
5#include "Ppmd7.h"
6 
7#define kTopValue (1 << 24)
8 
9void Ppmd7z_RangeEnc_Init(CPpmd7z_RangeEnc *p)
10{
11  p->Low = 0;
12  p->Range = 0xFFFFFFFF;
13  p->Cache = 0;
14  p->CacheSize = 1;
15}
16 
17static void RangeEnc_ShiftLow(CPpmd7z_RangeEnc *p)
18{
19  if ((UInt32)p->Low < (UInt32)0xFF000000 || (unsigned)(p->Low >> 32) != 0)
20  {
21    Byte temp = p->Cache;
22    do
23    {
24      p->Stream->Write(p->Stream, (Byte)(temp + (Byte)(p->Low >> 32)));
25      temp = 0xFF;
26    }
27    while(--p->CacheSize != 0);
28    p->Cache = (Byte)((UInt32)p->Low >> 24);
29  }
30  p->CacheSize++;
31  p->Low = (UInt32)p->Low << 8;
32}
33 
34static void RangeEnc_Encode(CPpmd7z_RangeEnc *p, UInt32 start, UInt32 size, UInt32 total)
35{
36  p->Low += start * (p->Range /= total);
37  p->Range *= size;
38  while (p->Range < kTopValue)
39  {
40    p->Range <<= 8;
41    RangeEnc_ShiftLow(p);
42  }
43}
44 
45static void RangeEnc_EncodeBit_0(CPpmd7z_RangeEnc *p, UInt32 size0)
46{
47  p->Range = (p->Range >> 14) * size0;
48  while (p->Range < kTopValue)
49  {
50    p->Range <<= 8;
51    RangeEnc_ShiftLow(p);
52  }
53}
54 
55static void RangeEnc_EncodeBit_1(CPpmd7z_RangeEnc *p, UInt32 size0)
56{
57  UInt32 newBound = (p->Range >> 14) * size0;
58  p->Low += newBound;
59  p->Range -= newBound;
60  while (p->Range < kTopValue)
61  {
62    p->Range <<= 8;
63    RangeEnc_ShiftLow(p);
64  }
65}
66 
67void Ppmd7z_RangeEnc_FlushData(CPpmd7z_RangeEnc *p)
68{
69  unsigned i;
70  for (i = 0; i < 5; i++)
71    RangeEnc_ShiftLow(p);
72}
73 
74 
75#define MASK(sym) ((signed char *)charMask)[sym]
76 
77void Ppmd7_EncodeSymbol(CPpmd7 *p, CPpmd7z_RangeEnc *rc, int symbol)
78{
79  size_t charMask[256 / sizeof(size_t)];
80  if (p->MinContext->NumStats != 1)
81  {
82    CPpmd_State *s = Ppmd7_GetStats(p, p->MinContext);
83    UInt32 sum;
84    unsigned i;
85    if (s->Symbol == symbol)
86    {
87      RangeEnc_Encode(rc, 0, s->Freq, p->MinContext->SummFreq);
88      p->FoundState = s;
89      Ppmd7_Update1_0(p);
90      return;
91    }
92    p->PrevSuccess = 0;
93    sum = s->Freq;
94    i = p->MinContext->NumStats - 1;
95    do
96    {
97      if ((++s)->Symbol == symbol)
98      {
99        RangeEnc_Encode(rc, sum, s->Freq, p->MinContext->SummFreq);
100        p->FoundState = s;
101        Ppmd7_Update1(p);
102        return;
103      }
104      sum += s->Freq;
105    }
106    while (--i);
107     
108    p->HiBitsFlag = p->HB2Flag[p->FoundState->Symbol];
109    PPMD_SetAllBitsIn256Bytes(charMask);
110    MASK(s->Symbol) = 0;
111    i = p->MinContext->NumStats - 1;
112    do { MASK((--s)->Symbol) = 0; } while (--i);
113    RangeEnc_Encode(rc, sum, p->MinContext->SummFreq - sum, p->MinContext->SummFreq);
114  }
115  else
116  {
117    UInt16 *prob = Ppmd7_GetBinSumm(p);
118    CPpmd_State *s = Ppmd7Context_OneState(p->MinContext);
119    if (s->Symbol == symbol)
120    {
121      RangeEnc_EncodeBit_0(rc, *prob);
122      *prob = (UInt16)PPMD_UPDATE_PROB_0(*prob);
123      p->FoundState = s;
124      Ppmd7_UpdateBin(p);
125      return;
126    }
127    else
128    {
129      RangeEnc_EncodeBit_1(rc, *prob);
130      *prob = (UInt16)PPMD_UPDATE_PROB_1(*prob);
131      p->InitEsc = PPMD7_kExpEscape[*prob >> 10];
132      PPMD_SetAllBitsIn256Bytes(charMask);
133      MASK(s->Symbol) = 0;
134      p->PrevSuccess = 0;
135    }
136  }
137  for (;;)
138  {
139    UInt32 escFreq;
140    CPpmd_See *see;
141    CPpmd_State *s;
142    UInt32 sum;
143    unsigned i, numMasked = p->MinContext->NumStats;
144    do
145    {
146      p->OrderFall++;
147      if (!p->MinContext->Suffix)
148        return; /* EndMarker (symbol = -1) */
149      p->MinContext = Ppmd7_GetContext(p, p->MinContext->Suffix);
150    }
151    while (p->MinContext->NumStats == numMasked);
152     
153    see = Ppmd7_MakeEscFreq(p, numMasked, &escFreq);
154    s = Ppmd7_GetStats(p, p->MinContext);
155    sum = 0;
156    i = p->MinContext->NumStats;
157    do
158    {
159      int cur = s->Symbol;
160      if (cur == symbol)
161      {
162        UInt32 low = sum;
163        CPpmd_State *s1 = s;
164        do
165        {
166          sum += (s->Freq & (int)(MASK(s->Symbol)));
167          s++;
168        }
169        while (--i);
170        RangeEnc_Encode(rc, low, s1->Freq, sum + escFreq);
171        Ppmd_See_Update(see);
172        p->FoundState = s1;
173        Ppmd7_Update2(p);
174        return;
175      }
176      sum += (s->Freq & (int)(MASK(cur)));
177      MASK(cur) = 0;
178      s++;
179    }
180    while (--i);
181     
182    RangeEnc_Encode(rc, sum, escFreq, sum + escFreq);
183    see->Summ = (UInt16)(see->Summ + sum + escFreq);
184  }
185}
src/lib/lib7z/7zBuf2.c
r0r14440
1/* 7zBuf2.c -- Byte Buffer
22008-10-04 : Igor Pavlov : Public domain */
3 
4#include <string.h>
5#include "7zBuf.h"
6 
7void DynBuf_Construct(CDynBuf *p)
8{
9  p->data = 0;
10  p->size = 0;
11  p->pos = 0;
12}
13 
14void DynBuf_SeekToBeg(CDynBuf *p)
15{
16  p->pos = 0;
17}
18 
19int DynBuf_Write(CDynBuf *p, const Byte *buf, size_t size, ISzAlloc *alloc)
20{
21  if (size > p->size - p->pos)
22  {
23    size_t newSize = p->pos + size;
24    Byte *data;
25    newSize += newSize / 4;
26    data = (Byte *)alloc->Alloc(alloc, newSize);
27    if (data == 0)
28      return 0;
29    p->size = newSize;
30    memcpy(data, p->data, p->pos);
31    alloc->Free(alloc, p->data);
32    p->data = data;
33  }
34  memcpy(p->data + p->pos, buf, size);
35  p->pos += size;
36  return 1;
37}
38 
39void DynBuf_Free(CDynBuf *p, ISzAlloc *alloc)
40{
41  alloc->Free(alloc, p->data);
42  p->data = 0;
43  p->size = 0;
44  p->pos = 0;
45}
src/lib/lib7z/CpuArch.c
r0r14440
1/* CpuArch.c -- CPU specific code
22010-10-26: Igor Pavlov : Public domain */
3 
4#include "CpuArch.h"
5 
6#ifdef MY_CPU_X86_OR_AMD64
7 
8#if (defined(_MSC_VER) && !defined(MY_CPU_AMD64)) || defined(__GNUC__)
9#define USE_ASM
10#endif
11 
12#if defined(USE_ASM) && !defined(MY_CPU_AMD64)
13static UInt32 CheckFlag(UInt32 flag)
14{
15  #ifdef _MSC_VER
16  __asm pushfd;
17  __asm pop EAX;
18  __asm mov EDX, EAX;
19  __asm xor EAX, flag;
20  __asm push EAX;
21  __asm popfd;
22  __asm pushfd;
23  __asm pop EAX;
24  __asm xor EAX, EDX;
25  __asm push EDX;
26  __asm popfd;
27  __asm and flag, EAX;
28  #else
29  __asm__ __volatile__ (
30    "pushf\n\t"
31    "pop  %%EAX\n\t"
32    "movl %%EAX,%%EDX\n\t"
33    "xorl %0,%%EAX\n\t"
34    "push %%EAX\n\t"
35    "popf\n\t"
36    "pushf\n\t"
37    "pop  %%EAX\n\t"
38    "xorl %%EDX,%%EAX\n\t"
39    "push %%EDX\n\t"
40    "popf\n\t"
41    "andl %%EAX, %0\n\t":
42    "=c" (flag) : "c" (flag));
43  #endif
44  return flag;
45}
46#define CHECK_CPUID_IS_SUPPORTED if (CheckFlag(1 << 18) == 0 || CheckFlag(1 << 21) == 0) return False;
47#else
48#define CHECK_CPUID_IS_SUPPORTED
49#endif
50 
51static void MyCPUID(UInt32 function, UInt32 *a, UInt32 *b, UInt32 *c, UInt32 *d)
52{
53  #ifdef USE_ASM
54 
55  #ifdef _MSC_VER
56 
57  UInt32 a2, b2, c2, d2;
58  __asm xor EBX, EBX;
59  __asm xor ECX, ECX;
60  __asm xor EDX, EDX;
61  __asm mov EAX, function;
62  __asm cpuid;
63  __asm mov a2, EAX;
64  __asm mov b2, EBX;
65  __asm mov c2, ECX;
66  __asm mov d2, EDX;
67 
68  *a = a2;
69  *b = b2;
70  *c = c2;
71  *d = d2;
72 
73  #else
74 
75  __asm__ __volatile__ (
76    "cpuid"
77    : "=a" (*a) ,
78      "=b" (*b) ,
79      "=c" (*c) ,
80      "=d" (*d)
81    : "0" (function)) ;
82 
83  #endif
84   
85  #else
86 
87  int CPUInfo[4];
88  __cpuid(CPUInfo, function);
89  *a = CPUInfo[0];
90  *b = CPUInfo[1];
91  *c = CPUInfo[2];
92  *d = CPUInfo[3];
93 
94  #endif
95}
96 
97Bool x86cpuid_CheckAndRead(Cx86cpuid *p)
98{
99  CHECK_CPUID_IS_SUPPORTED
100  MyCPUID(0, &p->maxFunc, &p->vendor[0], &p->vendor[2], &p->vendor[1]);
101  MyCPUID(1, &p->ver, &p->b, &p->c, &p->d);
102  return True;
103}
104 
105static UInt32 kVendors[][3] =
106{
107  { 0x756E6547, 0x49656E69, 0x6C65746E},
108  { 0x68747541, 0x69746E65, 0x444D4163},
109  { 0x746E6543, 0x48727561, 0x736C7561}
110};
111 
112int x86cpuid_GetFirm(const Cx86cpuid *p)
113{
114  unsigned i;
115  for (i = 0; i < sizeof(kVendors) / sizeof(kVendors[i]); i++)
116  {
117    const UInt32 *v = kVendors[i];
118    if (v[0] == p->vendor[0] &&
119        v[1] == p->vendor[1] &&
120        v[2] == p->vendor[2])
121      return (int)i;
122  }
123  return -1;
124}
125 
126Bool CPU_Is_InOrder(void)
127{
128  Cx86cpuid p;
129  int firm;
130  UInt32 family, model;
131  if (!x86cpuid_CheckAndRead(&p))
132    return True;
133  family = x86cpuid_GetFamily(&p);
134  model = x86cpuid_GetModel(&p);
135  firm = x86cpuid_GetFirm(&p);
136  switch (firm)
137  {
138    case CPU_FIRM_INTEL: return (family < 6 || (family == 6 && model == 0x100C));
139    case CPU_FIRM_AMD: return (family < 5 || (family == 5 && (model < 6 || model == 0xA)));
140    case CPU_FIRM_VIA: return (family < 6 || (family == 6 && model < 0xF));
141  }
142  return True;
143}
144 
145#if !defined(MY_CPU_AMD64) && defined(_WIN32_7Z)
146static Bool CPU_Sys_Is_SSE_Supported(void)
147{
148  OSVERSIONINFO vi;
149  vi.dwOSVersionInfoSize = sizeof(vi);
150  if (!GetVersionEx(&vi))
151    return False;
152  return (vi.dwMajorVersion >= 5);
153}
154#define CHECK_SYS_SSE_SUPPORT if (!CPU_Sys_Is_SSE_Supported()) return False;
155#else
156#define CHECK_SYS_SSE_SUPPORT
157#endif
158 
159Bool CPU_Is_Aes_Supported(void)
160{
161  Cx86cpuid p;
162  CHECK_SYS_SSE_SUPPORT
163  if (!x86cpuid_CheckAndRead(&p))
164    return False;
165  return (p.c >> 25) & 1;
166}
167 
168#endif
src/lib/lib7z/Lzma86.h
r0r14440
1/* Lzma86.h -- LZMA + x86 (BCJ) Filter
22009-08-14 : Igor Pavlov : Public domain */
3 
4#ifndef __LZMA86_H
5#define __LZMA86_H
6 
7#include "Types.h"
8 
9EXTERN_C_BEGIN
10 
11#define LZMA86_SIZE_OFFSET (1 + 5)
12#define LZMA86_HEADER_SIZE (LZMA86_SIZE_OFFSET + 8)
13 
14/*
15It's an example for LZMA + x86 Filter use.
16You can use .lzma86 extension, if you write that stream to file.
17.lzma86 header adds one additional byte to standard .lzma header.
18.lzma86 header (14 bytes):
19  Offset Size  Description
20    0     1    = 0 - no filter, pure LZMA
21               = 1 - x86 filter + LZMA
22    1     1    lc, lp and pb in encoded form
23    2     4    dictSize (little endian)
24    6     8    uncompressed size (little endian)
25 
26 
27Lzma86_Encode
28-------------
29level - compression level: 0 <= level <= 9, the default value for "level" is 5.
30 
31dictSize - The dictionary size in bytes. The maximum value is
32        128 MB = (1 << 27) bytes for 32-bit version
33          1 GB = (1 << 30) bytes for 64-bit version
34     The default value is 16 MB = (1 << 24) bytes, for level = 5.
35     It's recommended to use the dictionary that is larger than 4 KB and
36     that can be calculated as (1 << N) or (3 << N) sizes.
37     For better compression ratio dictSize must be >= inSize.
38 
39filterMode:
40    SZ_FILTER_NO   - no Filter
41    SZ_FILTER_YES  - x86 Filter
42    SZ_FILTER_AUTO - it tries both alternatives to select best.
43              Encoder will use 2 or 3 passes:
44              2 passes when FILTER_NO provides better compression.
45              3 passes when FILTER_YES provides better compression.
46 
47Lzma86Encode allocates Data with MyAlloc functions.
48RAM Requirements for compressing:
49  RamSize = dictionarySize * 11.5 + 6MB + FilterBlockSize
50      filterMode     FilterBlockSize
51     SZ_FILTER_NO         0
52     SZ_FILTER_YES      inSize
53     SZ_FILTER_AUTO     inSize
54 
55 
56Return code:
57  SZ_OK               - OK
58  SZ_ERROR_MEM        - Memory allocation error
59  SZ_ERROR_PARAM      - Incorrect paramater
60  SZ_ERROR_OUTPUT_EOF - output buffer overflow
61  SZ_ERROR_THREAD     - errors in multithreading functions (only for Mt version)
62*/
63 
64enum ESzFilterMode
65{
66  SZ_FILTER_NO,
67  SZ_FILTER_YES,
68  SZ_FILTER_AUTO
69};
70 
71SRes Lzma86_Encode(Byte *dest, size_t *destLen, const Byte *src, size_t srcLen,
72    int level, UInt32 dictSize, int filterMode);
73 
74 
75/*
76Lzma86_GetUnpackSize:
77  In:
78    src      - input data
79    srcLen   - input data size
80  Out:
81    unpackSize - size of uncompressed stream
82  Return code:
83    SZ_OK               - OK
84    SZ_ERROR_INPUT_EOF  - Error in headers
85*/
86 
87SRes Lzma86_GetUnpackSize(const Byte *src, SizeT srcLen, UInt64 *unpackSize);
88 
89/*
90Lzma86_Decode:
91  In:
92    dest     - output data
93    destLen  - output data size
94    src      - input data
95    srcLen   - input data size
96  Out:
97    destLen  - processed output size
98    srcLen   - processed input size
99  Return code:
100    SZ_OK           - OK
101    SZ_ERROR_DATA  - Data error
102    SZ_ERROR_MEM   - Memory allocation error
103    SZ_ERROR_UNSUPPORTED - unsupported file
104    SZ_ERROR_INPUT_EOF - it needs more bytes in input buffer
105*/
106 
107SRes Lzma86_Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen);
108 
109EXTERN_C_END
110 
111#endif
src/lib/lib7z/LzFindMt.c
r0r14440
1/* LzFindMt.c -- multithreaded Match finder for LZ algorithms
22009-09-20 : Igor Pavlov : Public domain */
3 
4#include "LzHash.h"
5 
6#include "LzFindMt.h"
7 
8void MtSync_Construct(CMtSync *p)
9{
10  p->wasCreated = False;
11  p->csWasInitialized = False;
12  p->csWasEntered = False;
13  Thread_Construct(&p->thread);
14  Event_Construct(&p->canStart);
15  Event_Construct(&p->wasStarted);
16  Event_Construct(&p->wasStopped);
17  Semaphore_Construct(&p->freeSemaphore);
18  Semaphore_Construct(&p->filledSemaphore);
19}
20 
21void MtSync_GetNextBlock(CMtSync *p)
22{
23  if (p->needStart)
24  {
25    p->numProcessedBlocks = 1;
26    p->needStart = False;
27    p->stopWriting = False;
28    p->exit = False;
29    Event_Reset(&p->wasStarted);
30    Event_Reset(&p->wasStopped);
31 
32    Event_Set(&p->canStart);
33    Event_Wait(&p->wasStarted);
34  }
35  else
36  {
37    CriticalSection_Leave(&p->cs);
38    p->csWasEntered = False;
39    p->numProcessedBlocks++;
40    Semaphore_Release1(&p->freeSemaphore);
41  }
42  Semaphore_Wait(&p->filledSemaphore);
43  CriticalSection_Enter(&p->cs);
44  p->csWasEntered = True;
45}
46 
47/* MtSync_StopWriting must be called if Writing was started */
48 
49void MtSync_StopWriting(CMtSync *p)
50{
51  UInt32 myNumBlocks = p->numProcessedBlocks;
52  if (!Thread_WasCreated(&p->thread) || p->needStart)
53    return;
54  p->stopWriting = True;
55  if (p->csWasEntered)
56  {
57    CriticalSection_Leave(&p->cs);
58    p->csWasEntered = False;
59  }
60  Semaphore_Release1(&p->freeSemaphore);
61 
62  Event_Wait(&p->wasStopped);
63 
64  while (myNumBlocks++ != p->numProcessedBlocks)
65  {
66    Semaphore_Wait(&p->filledSemaphore);
67    Semaphore_Release1(&p->freeSemaphore);
68  }
69  p->needStart = True;
70}
71 
72void MtSync_Destruct(CMtSync *p)
73{
74  if (Thread_WasCreated(&p->thread))
75  {
76    MtSync_StopWriting(p);
77    p->exit = True;
78    if (p->needStart)
79      Event_Set(&p->canStart);
80    Thread_Wait(&p->thread);
81    Thread_Close(&p->thread);
82  }
83  if (p->csWasInitialized)
84  {
85    CriticalSection_Delete(&p->cs);
86    p->csWasInitialized = False;
87  }
88 
89  Event_Close(&p->canStart);
90  Event_Close(&p->wasStarted);
91  Event_Close(&p->wasStopped);
92  Semaphore_Close(&p->freeSemaphore);
93  Semaphore_Close(&p->filledSemaphore);
94 
95  p->wasCreated = False;
96}
97 
98#define RINOK_THREAD(x) { if ((x) != 0) return SZ_ERROR_THREAD; }
99 
100static SRes MtSync_Create2(CMtSync *p, unsigned (MY_STD_CALL *startAddress)(void *), void *obj, UInt32 numBlocks)
101{
102  if (p->wasCreated)
103    return SZ_OK;
104 
105  RINOK_THREAD(CriticalSection_Init(&p->cs));
106  p->csWasInitialized = True;
107 
108  RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->canStart));
109  RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->wasStarted));
110  RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->wasStopped));
111   
112  RINOK_THREAD(Semaphore_Create(&p->freeSemaphore, numBlocks, numBlocks));
113  RINOK_THREAD(Semaphore_Create(&p->filledSemaphore, 0, numBlocks));
114 
115  p->needStart = True;
116   
117  RINOK_THREAD(Thread_Create(&p->thread, startAddress, obj));
118  p->wasCreated = True;
119  return SZ_OK;
120}
121 
122static SRes MtSync_Create(CMtSync *p, unsigned (MY_STD_CALL *startAddress)(void *), void *obj, UInt32 numBlocks)
123{
124  SRes res = MtSync_Create2(p, startAddress, obj, numBlocks);
125  if (res != SZ_OK)
126    MtSync_Destruct(p);
127  return res;
128}
129 
130void MtSync_Init(CMtSync *p) { p->needStart = True; }
131 
132#define kMtMaxValForNormalize 0xFFFFFFFF
133 
134#define DEF_GetHeads2(name, v, action) \
135static void GetHeads ## name(const Byte *p, UInt32 pos, \
136UInt32 *hash, UInt32 hashMask, UInt32 *heads, UInt32 numHeads, const UInt32 *crc) \
137{ action; for (; numHeads != 0; numHeads--) { \
138const UInt32 value = (v); p++; *heads++ = pos - hash[value]; hash[value] = pos++;  } }
139 
140#define DEF_GetHeads(name, v) DEF_GetHeads2(name, v, ;)
141 
142DEF_GetHeads2(2,  (p[0] | ((UInt32)p[1] << 8)), hashMask = hashMask; crc = crc; )
143DEF_GetHeads(3,  (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8)) & hashMask)
144DEF_GetHeads(4,  (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8) ^ (crc[p[3]] << 5)) & hashMask)
145DEF_GetHeads(4b, (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8) ^ ((UInt32)p[3] << 16)) & hashMask)
146/* DEF_GetHeads(5,  (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8) ^ (crc[p[3]] << 5) ^ (crc[p[4]] << 3)) & hashMask) */
147 
148void HashThreadFunc(CMatchFinderMt *mt)
149{
150  CMtSync *p = &mt->hashSync;
151  for (;;)
152  {
153    UInt32 numProcessedBlocks = 0;
154    Event_Wait(&p->canStart);
155    Event_Set(&p->wasStarted);
156    for (;;)
157    {
158      if (p->exit)
159        return;
160      if (p->stopWriting)
161      {
162        p->numProcessedBlocks = numProcessedBlocks;
163        Event_Set(&p->wasStopped);
164        break;
165      }
166 
167      {
168        CMatchFinder *mf = mt->MatchFinder;
169        if (MatchFinder_NeedMove(mf))
170        {
171          CriticalSection_Enter(&mt->btSync.cs);
172          CriticalSection_Enter(&mt->hashSync.cs);
173          {
174            const Byte *beforePtr = MatchFinder_GetPointerToCurrentPos(mf);
175            const Byte *afterPtr;
176            MatchFinder_MoveBlock(mf);
177            afterPtr = MatchFinder_GetPointerToCurrentPos(mf);
178            mt->pointerToCurPos -= beforePtr - afterPtr;
179            mt->buffer -= beforePtr - afterPtr;
180          }
181          CriticalSection_Leave(&mt->btSync.cs);
182          CriticalSection_Leave(&mt->hashSync.cs);
183          continue;
184        }
185 
186        Semaphore_Wait(&p->freeSemaphore);
187 
188        MatchFinder_ReadIfRequired(mf);
189        if (mf->pos > (kMtMaxValForNormalize - kMtHashBlockSize))
190        {
191          UInt32 subValue = (mf->pos - mf->historySize - 1);
192          MatchFinder_ReduceOffsets(mf, subValue);
193          MatchFinder_Normalize3(subValue, mf->hash + mf->fixedHashSize, mf->hashMask + 1);
194        }
195        {
196          UInt32 *heads = mt->hashBuf + ((numProcessedBlocks++) & kMtHashNumBlocksMask) * kMtHashBlockSize;
197          UInt32 num = mf->streamPos - mf->pos;
198          heads[0] = 2;
199          heads[1] = num;
200          if (num >= mf->numHashBytes)
201          {
202            num = num - mf->numHashBytes + 1;
203            if (num > kMtHashBlockSize - 2)
204              num = kMtHashBlockSize - 2;
205            mt->GetHeadsFunc(mf->buffer, mf->pos, mf->hash + mf->fixedHashSize, mf->hashMask, heads + 2, num, mf->crc);
206            heads[0] += num;
207          }
208          mf->pos += num;
209          mf->buffer += num;
210        }
211      }
212 
213      Semaphore_Release1(&p->filledSemaphore);
214    }
215  }
216}
217 
218void MatchFinderMt_GetNextBlock_Hash(CMatchFinderMt *p)
219{
220  MtSync_GetNextBlock(&p->hashSync);
221  p->hashBufPosLimit = p->hashBufPos = ((p->hashSync.numProcessedBlocks - 1) & kMtHashNumBlocksMask) * kMtHashBlockSize;
222  p->hashBufPosLimit += p->hashBuf[p->hashBufPos++];
223  p->hashNumAvail = p->hashBuf[p->hashBufPos++];
224}
225 
226#define kEmptyHashValue 0
227 
228/* #define MFMT_GM_INLINE */
229 
230#ifdef MFMT_GM_INLINE
231 
232#define NO_INLINE MY_FAST_CALL
233 
234Int32 NO_INLINE GetMatchesSpecN(UInt32 lenLimit, UInt32 pos, const Byte *cur, CLzRef *son,
235    UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 _cutValue,
236    UInt32 *_distances, UInt32 _maxLen, const UInt32 *hash, Int32 limit, UInt32 size, UInt32 *posRes)
237{
238  do
239  {
240  UInt32 *distances = _distances + 1;
241  UInt32 curMatch = pos - *hash++;
242 
243  CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1;
244  CLzRef *ptr1 = son + (_cyclicBufferPos << 1);
245  UInt32 len0 = 0, len1 = 0;
246  UInt32 cutValue = _cutValue;
247  UInt32 maxLen = _maxLen;
248  for (;;)
249  {
250    UInt32 delta = pos - curMatch;
251    if (cutValue-- == 0 || delta >= _cyclicBufferSize)
252    {
253      *ptr0 = *ptr1 = kEmptyHashValue;
254      break;
255    }
256    {
257      CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1);
258      const Byte *pb = cur - delta;
259      UInt32 len = (len0 < len1 ? len0 : len1);
260      if (pb[len] == cur[len])
261      {
262        if (++len != lenLimit && pb[len] == cur[len])
263          while (++len != lenLimit)
264            if (pb[len] != cur[len])
265              break;
266        if (maxLen < len)
267        {
268          *distances++ = maxLen = len;
269          *distances++ = delta - 1;
270          if (len == lenLimit)
271          {
272            *ptr1 = pair[0];
273            *ptr0 = pair[1];
274            break;
275          }
276        }
277      }
278      if (pb[len] < cur[len])
279      {
280        *ptr1 = curMatch;
281        ptr1 = pair + 1;
282        curMatch = *ptr1;
283        len1 = len;
284      }
285      else
286      {
287        *ptr0 = curMatch;
288        ptr0 = pair;
289        curMatch = *ptr0;
290        len0 = len;
291      }
292    }
293  }
294  pos++;
295  _cyclicBufferPos++;
296  cur++;
297  {
298    UInt32 num = (UInt32)(distances - _distances);
299    *_distances = num - 1;
300    _distances += num;
301    limit -= num;
302  }
303  }
304  while (limit > 0 && --size != 0);
305  *posRes = pos;
306  return limit;
307}
308 
309#endif
310 
311void BtGetMatches(CMatchFinderMt *p, UInt32 *distances)
312{
313  UInt32 numProcessed = 0;
314  UInt32 curPos = 2;
315  UInt32 limit = kMtBtBlockSize - (p->matchMaxLen * 2);
316  distances[1] = p->hashNumAvail;
317  while (curPos < limit)
318  {
319    if (p->hashBufPos == p->hashBufPosLimit)
320    {
321      MatchFinderMt_GetNextBlock_Hash(p);
322      distances[1] = numProcessed + p->hashNumAvail;
323      if (p->hashNumAvail >= p->numHashBytes)
324        continue;
325      for (; p->hashNumAvail != 0; p->hashNumAvail--)
326        distances[curPos++] = 0;
327      break;
328    }
329    {
330      UInt32 size = p->hashBufPosLimit - p->hashBufPos;
331      UInt32 lenLimit = p->matchMaxLen;
332      UInt32 pos = p->pos;
333      UInt32 cyclicBufferPos = p->cyclicBufferPos;
334      if (lenLimit >= p->hashNumAvail)
335        lenLimit = p->hashNumAvail;
336      {
337        UInt32 size2 = p->hashNumAvail - lenLimit + 1;
338        if (size2 < size)
339          size = size2;
340        size2 = p->cyclicBufferSize - cyclicBufferPos;
341        if (size2 < size)
342          size = size2;
343      }
344      #ifndef MFMT_GM_INLINE
345      while (curPos < limit && size-- != 0)
346      {
347        UInt32 *startDistances = distances + curPos;
348        UInt32 num = (UInt32)(GetMatchesSpec1(lenLimit, pos - p->hashBuf[p->hashBufPos++],
349          pos, p->buffer, p->son, cyclicBufferPos, p->cyclicBufferSize, p->cutValue,
350          startDistances + 1, p->numHashBytes - 1) - startDistances);
351        *startDistances = num - 1;
352        curPos += num;
353        cyclicBufferPos++;
354        pos++;
355        p->buffer++;
356      }
357      #else
358      {
359        UInt32 posRes;
360        curPos = limit - GetMatchesSpecN(lenLimit, pos, p->buffer, p->son, cyclicBufferPos, p->cyclicBufferSize, p->cutValue,
361          distances + curPos, p->numHashBytes - 1, p->hashBuf + p->hashBufPos, (Int32)(limit - curPos) , size, &posRes);
362        p->hashBufPos += posRes - pos;
363        cyclicBufferPos += posRes - pos;
364        p->buffer += posRes - pos;
365        pos = posRes;
366      }
367      #endif
368 
369      numProcessed += pos - p->pos;
370      p->hashNumAvail -= pos - p->pos;
371      p->pos = pos;
372      if (cyclicBufferPos == p->cyclicBufferSize)
373        cyclicBufferPos = 0;
374      p->cyclicBufferPos = cyclicBufferPos;
375    }
376  }
377  distances[0] = curPos;
378}
379 
380void BtFillBlock(CMatchFinderMt *p, UInt32 globalBlockIndex)
381{
382  CMtSync *sync = &p->hashSync;
383  if (!sync->needStart)
384  {
385    CriticalSection_Enter(&sync->cs);
386    sync->csWasEntered = True;
387  }
388   
389  BtGetMatches(p, p->btBuf + (globalBlockIndex & kMtBtNumBlocksMask) * kMtBtBlockSize);
390 
391  if (p->pos > kMtMaxValForNormalize - kMtBtBlockSize)
392  {
393    UInt32 subValue = p->pos - p->cyclicBufferSize;
394    MatchFinder_Normalize3(subValue, p->son, p->cyclicBufferSize * 2);
395    p->pos -= subValue;
396  }
397 
398  if (!sync->needStart)
399  {
400    CriticalSection_Leave(&sync->cs);
401    sync->csWasEntered = False;
402  }
403}
404 
405void BtThreadFunc(CMatchFinderMt *mt)
406{
407  CMtSync *p = &mt->btSync;
408  for (;;)
409  {
410    UInt32 blockIndex = 0;
411    Event_Wait(&p->canStart);
412    Event_Set(&p->wasStarted);
413    for (;;)
414    {
415      if (p->exit)
416        return;
417      if (p->stopWriting)
418      {
419        p->numProcessedBlocks = blockIndex;
420        MtSync_StopWriting(&mt->hashSync);
421        Event_Set(&p->wasStopped);
422        break;
423      }
424      Semaphore_Wait(&p->freeSemaphore);
425      BtFillBlock(mt, blockIndex++);
426      Semaphore_Release1(&p->filledSemaphore);
427    }
428  }
429}
430 
431void MatchFinderMt_Construct(CMatchFinderMt *p)
432{
433  p->hashBuf = 0;
434  MtSync_Construct(&p->hashSync);
435  MtSync_Construct(&p->btSync);
436}
437 
438void MatchFinderMt_FreeMem(CMatchFinderMt *p, ISzAlloc *alloc)
439{
440  alloc->Free(alloc, p->hashBuf);
441  p->hashBuf = 0;
442}
443 
444void MatchFinderMt_Destruct(CMatchFinderMt *p, ISzAlloc *alloc)
445{
446  MtSync_Destruct(&p->hashSync);
447  MtSync_Destruct(&p->btSync);
448  MatchFinderMt_FreeMem(p, alloc);
449}
450 
451#define kHashBufferSize (kMtHashBlockSize * kMtHashNumBlocks)
452#define kBtBufferSize (kMtBtBlockSize * kMtBtNumBlocks)
453 
454static unsigned MY_STD_CALL HashThreadFunc2(void *p) { HashThreadFunc((CMatchFinderMt *)p);  return 0; }
455static unsigned MY_STD_CALL BtThreadFunc2(void *p)
456{
457  Byte allocaDummy[0x180];
458  int i = 0;
459  for (i = 0; i < 16; i++)
460    allocaDummy[i] = (Byte)i;
461  BtThreadFunc((CMatchFinderMt *)p);
462  return 0;
463}
464 
465SRes MatchFinderMt_Create(CMatchFinderMt *p, UInt32 historySize, UInt32 keepAddBufferBefore,
466    UInt32 matchMaxLen, UInt32 keepAddBufferAfter, ISzAlloc *alloc)
467{
468  CMatchFinder *mf = p->MatchFinder;
469  p->historySize = historySize;
470  if (kMtBtBlockSize <= matchMaxLen * 4)
471    return SZ_ERROR_PARAM;
472  if (p->hashBuf == 0)
473  {
474    p->hashBuf = (UInt32 *)alloc->Alloc(alloc, (kHashBufferSize + kBtBufferSize) * sizeof(UInt32));
475    if (p->hashBuf == 0)
476      return SZ_ERROR_MEM;
477    p->btBuf = p->hashBuf + kHashBufferSize;
478  }
479  keepAddBufferBefore += (kHashBufferSize + kBtBufferSize);
480  keepAddBufferAfter += kMtHashBlockSize;
481  if (!MatchFinder_Create(mf, historySize, keepAddBufferBefore, matchMaxLen, keepAddBufferAfter, alloc))
482    return SZ_ERROR_MEM;
483 
484  RINOK(MtSync_Create(&p->hashSync, HashThreadFunc2, p, kMtHashNumBlocks));
485  RINOK(MtSync_Create(&p->btSync, BtThreadFunc2, p, kMtBtNumBlocks));
486  return SZ_OK;
487}
488 
489/* Call it after ReleaseStream / SetStream */
490void MatchFinderMt_Init(CMatchFinderMt *p)
491{
492  CMatchFinder *mf = p->MatchFinder;
493  p->btBufPos = p->btBufPosLimit = 0;
494  p->hashBufPos = p->hashBufPosLimit = 0;
495  MatchFinder_Init(mf);
496  p->pointerToCurPos = MatchFinder_GetPointerToCurrentPos(mf);
497  p->btNumAvailBytes = 0;
498  p->lzPos = p->historySize + 1;
499 
500  p->hash = mf->hash;
501  p->fixedHashSize = mf->fixedHashSize;
502  p->crc = mf->crc;
503 
504  p->son = mf->son;
505  p->matchMaxLen = mf->matchMaxLen;
506  p->numHashBytes = mf->numHashBytes;
507  p->pos = mf->pos;
508  p->buffer = mf->buffer;
509  p->cyclicBufferPos = mf->cyclicBufferPos;
510  p->cyclicBufferSize = mf->cyclicBufferSize;
511  p->cutValue = mf->cutValue;
512}
513 
514/* ReleaseStream is required to finish multithreading */
515void MatchFinderMt_ReleaseStream(CMatchFinderMt *p)
516{
517  MtSync_StopWriting(&p->btSync);
518  /* p->MatchFinder->ReleaseStream(); */
519}
520 
521void MatchFinderMt_Normalize(CMatchFinderMt *p)
522{
523  MatchFinder_Normalize3(p->lzPos - p->historySize - 1, p->hash, p->fixedHashSize);
524  p->lzPos = p->historySize + 1;
525}
526 
527void MatchFinderMt_GetNextBlock_Bt(CMatchFinderMt *p)
528{
529  UInt32 blockIndex;
530  MtSync_GetNextBlock(&p->btSync);
531  blockIndex = ((p->btSync.numProcessedBlocks - 1) & kMtBtNumBlocksMask);
532  p->btBufPosLimit = p->btBufPos = blockIndex * kMtBtBlockSize;
533  p->btBufPosLimit += p->btBuf[p->btBufPos++];
534  p->btNumAvailBytes = p->btBuf[p->btBufPos++];
535  if (p->lzPos >= kMtMaxValForNormalize - kMtBtBlockSize)
536    MatchFinderMt_Normalize(p);
537}
538 
539const Byte * MatchFinderMt_GetPointerToCurrentPos(CMatchFinderMt *p)
540{
541  return p->pointerToCurPos;
542}
543 
544#define GET_NEXT_BLOCK_IF_REQUIRED if (p->btBufPos == p->btBufPosLimit) MatchFinderMt_GetNextBlock_Bt(p);
545 
546UInt32 MatchFinderMt_GetNumAvailableBytes(CMatchFinderMt *p)
547{
548  GET_NEXT_BLOCK_IF_REQUIRED;
549  return p->btNumAvailBytes;
550}
551 
552Byte MatchFinderMt_GetIndexByte(CMatchFinderMt *p, Int32 index)
553{
554  return p->pointerToCurPos[index];
555}
556 
557UInt32 * MixMatches2(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *distances)
558{
559  UInt32 hash2Value, curMatch2;
560  UInt32 *hash = p->hash;
561  const Byte *cur = p->pointerToCurPos;
562  UInt32 lzPos = p->lzPos;
563  MT_HASH2_CALC
564       
565  curMatch2 = hash[hash2Value];
566  hash[hash2Value] = lzPos;
567 
568  if (curMatch2 >= matchMinPos)
569    if (cur[(ptrdiff_t)curMatch2 - lzPos] == cur[0])
570    {
571      *distances++ = 2;
572      *distances++ = lzPos - curMatch2 - 1;
573    }
574  return distances;
575}
576 
577UInt32 * MixMatches3(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *distances)
578{
579  UInt32 hash2Value, hash3Value, curMatch2, curMatch3;
580  UInt32 *hash = p->hash;
581  const Byte *cur = p->pointerToCurPos;
582  UInt32 lzPos = p->lzPos;
583  MT_HASH3_CALC
584 
585  curMatch2 = hash[                hash2Value];
586  curMatch3 = hash[kFix3HashSize + hash3Value];
587   
588  hash[                hash2Value] =
589  hash[kFix3HashSize + hash3Value] =
590    lzPos;
591 
592  if (curMatch2 >= matchMinPos && cur[(ptrdiff_t)curMatch2 - lzPos] == cur[0])
593  {
594    distances[1] = lzPos - curMatch2 - 1;
595    if (cur[(ptrdiff_t)curMatch2 - lzPos + 2] == cur[2])
596    {
597      distances[0] = 3;
598      return distances + 2;
599    }
600    distances[0] = 2;
601    distances += 2;
602  }
603  if (curMatch3 >= matchMinPos && cur[(ptrdiff_t)curMatch3 - lzPos] == cur[0])
604  {
605    *distances++ = 3;
606    *distances++ = lzPos - curMatch3 - 1;
607  }
608  return distances;
609}
610 
611/*
612UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *distances)
613{
614  UInt32 hash2Value, hash3Value, hash4Value, curMatch2, curMatch3, curMatch4;
615  UInt32 *hash = p->hash;
616  const Byte *cur = p->pointerToCurPos;
617  UInt32 lzPos = p->lzPos;
618  MT_HASH4_CALC
619       
620  curMatch2 = hash[                hash2Value];
621  curMatch3 = hash[kFix3HashSize + hash3Value];
622  curMatch4 = hash[kFix4HashSize + hash4Value];
623   
624  hash[                hash2Value] =
625  hash[kFix3HashSize + hash3Value] =
626  hash[kFix4HashSize + hash4Value] =
627    lzPos;
628 
629  if (curMatch2 >= matchMinPos && cur[(ptrdiff_t)curMatch2 - lzPos] == cur[0])
630  {
631    distances[1] = lzPos - curMatch2 - 1;
632    if (cur[(ptrdiff_t)curMatch2 - lzPos + 2] == cur[2])
633    {
634      distances[0] =  (cur[(ptrdiff_t)curMatch2 - lzPos + 3] == cur[3]) ? 4 : 3;
635      return distances + 2;
636    }
637    distances[0] = 2;
638    distances += 2;
639  }
640  if (curMatch3 >= matchMinPos && cur[(ptrdiff_t)curMatch3 - lzPos] == cur[0])
641  {
642    distances[1] = lzPos - curMatch3 - 1;
643    if (cur[(ptrdiff_t)curMatch3 - lzPos + 3] == cur[3])
644    {
645      distances[0] = 4;
646      return distances + 2;
647    }
648    distances[0] = 3;
649    distances += 2;
650  }
651 
652  if (curMatch4 >= matchMinPos)
653    if (
654      cur[(ptrdiff_t)curMatch4 - lzPos] == cur[0] &&
655      cur[(ptrdiff_t)curMatch4 - lzPos + 3] == cur[3]
656      )
657    {
658      *distances++ = 4;
659      *distances++ = lzPos - curMatch4 - 1;
660    }
661  return distances;
662}
663*/
664 
665#define INCREASE_LZ_POS p->lzPos++; p->pointerToCurPos++;
666 
667UInt32 MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *distances)
668{
669  const UInt32 *btBuf = p->btBuf + p->btBufPos;
670  UInt32 len = *btBuf++;
671  p->btBufPos += 1 + len;
672  p->btNumAvailBytes--;
673  {
674    UInt32 i;
675    for (i = 0; i < len; i += 2)
676    {
677      *distances++ = *btBuf++;
678      *distances++ = *btBuf++;
679    }
680  }
681  INCREASE_LZ_POS
682  return len;
683}
684 
685UInt32 MatchFinderMt_GetMatches(CMatchFinderMt *p, UInt32 *distances)
686{
687  const UInt32 *btBuf = p->btBuf + p->btBufPos;
688  UInt32 len = *btBuf++;
689  p->btBufPos += 1 + len;
690 
691  if (len == 0)
692  {
693    if (p->btNumAvailBytes-- >= 4)
694      len = (UInt32)(p->MixMatchesFunc(p, p->lzPos - p->historySize, distances) - (distances));
695  }
696  else
697  {
698    /* Condition: there are matches in btBuf with length < p->numHashBytes */
699    UInt32 *distances2;
700    p->btNumAvailBytes--;
701    distances2 = p->MixMatchesFunc(p, p->lzPos - btBuf[1], distances);
702    do
703    {
704      *distances2++ = *btBuf++;
705      *distances2++ = *btBuf++;
706    }
707    while ((len -= 2) != 0);
708    len  = (UInt32)(distances2 - (distances));
709  }
710  INCREASE_LZ_POS
711  return len;
712}
713 
714#define SKIP_HEADER2_MT  do { GET_NEXT_BLOCK_IF_REQUIRED
715#define SKIP_HEADER_MT(n) SKIP_HEADER2_MT if (p->btNumAvailBytes-- >= (n)) { const Byte *cur = p->pointerToCurPos; UInt32 *hash = p->hash;
716#define SKIP_FOOTER_MT } INCREASE_LZ_POS p->btBufPos += p->btBuf[p->btBufPos] + 1; } while (--num != 0);
717 
718void MatchFinderMt0_Skip(CMatchFinderMt *p, UInt32 num)
719{
720  SKIP_HEADER2_MT { p->btNumAvailBytes--;
721  SKIP_FOOTER_MT
722}
723 
724void MatchFinderMt2_Skip(CMatchFinderMt *p, UInt32 num)
725{
726  SKIP_HEADER_MT(2)
727      UInt32 hash2Value;
728      MT_HASH2_CALC
729      hash[hash2Value] = p->lzPos;
730  SKIP_FOOTER_MT
731}
732 
733void MatchFinderMt3_Skip(CMatchFinderMt *p, UInt32 num)
734{
735  SKIP_HEADER_MT(3)
736      UInt32 hash2Value, hash3Value;
737      MT_HASH3_CALC
738      hash[kFix3HashSize + hash3Value] =
739      hash[                hash2Value] =
740        p->lzPos;
741  SKIP_FOOTER_MT
742}
743 
744/*
745void MatchFinderMt4_Skip(CMatchFinderMt *p, UInt32 num)
746{
747  SKIP_HEADER_MT(4)
748      UInt32 hash2Value, hash3Value, hash4Value;
749      MT_HASH4_CALC
750      hash[kFix4HashSize + hash4Value] =
751      hash[kFix3HashSize + hash3Value] =
752      hash[                hash2Value] =
753        p->lzPos;
754  SKIP_FOOTER_MT
755}
756*/
757 
758void MatchFinderMt_CreateVTable(CMatchFinderMt *p, IMatchFinder *vTable)
759{
760  vTable->Init = (Mf_Init_Func)MatchFinderMt_Init;
761  vTable->GetIndexByte = (Mf_GetIndexByte_Func)MatchFinderMt_GetIndexByte;
762  vTable->GetNumAvailableBytes = (Mf_GetNumAvailableBytes_Func)MatchFinderMt_GetNumAvailableBytes;
763  vTable->GetPointerToCurrentPos = (Mf_GetPointerToCurrentPos_Func)MatchFinderMt_GetPointerToCurrentPos;
764  vTable->GetMatches = (Mf_GetMatches_Func)MatchFinderMt_GetMatches;
765  switch(p->MatchFinder->numHashBytes)
766  {
767    case 2:
768      p->GetHeadsFunc = GetHeads2;
769      p->MixMatchesFunc = (Mf_Mix_Matches)0;
770      vTable->Skip = (Mf_Skip_Func)MatchFinderMt0_Skip;
771      vTable->GetMatches = (Mf_GetMatches_Func)MatchFinderMt2_GetMatches;
772      break;
773    case 3:
774      p->GetHeadsFunc = GetHeads3;
775      p->MixMatchesFunc = (Mf_Mix_Matches)MixMatches2;
776      vTable->Skip = (Mf_Skip_Func)MatchFinderMt2_Skip;
777      break;
778    default:
779    /* case 4: */
780      p->GetHeadsFunc = p->MatchFinder->bigHash ? GetHeads4b : GetHeads4;
781      /* p->GetHeadsFunc = GetHeads4; */
782      p->MixMatchesFunc = (Mf_Mix_Matches)MixMatches3;
783      vTable->Skip = (Mf_Skip_Func)MatchFinderMt3_Skip;
784      break;
785    /*
786    default:
787      p->GetHeadsFunc = GetHeads5;
788      p->MixMatchesFunc = (Mf_Mix_Matches)MixMatches4;
789      vTable->Skip = (Mf_Skip_Func)MatchFinderMt4_Skip;
790      break;
791    */
792  }
793}
src/lib/lib7z/7zIn.c
r0r14440
1/* 7zIn.c -- 7z Input functions
22010-10-29 : Igor Pavlov : Public domain */
3 
4#include <string.h>
5 
6#include "7z.h"
7#include "7zCrc.h"
8#include "CpuArch.h"
9 
10Byte k7zSignature[k7zSignatureSize] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C};
11 
12#define RINOM(x) { if ((x) == 0) return SZ_ERROR_MEM; }
13 
14#define NUM_FOLDER_CODERS_MAX 32
15#define NUM_CODER_STREAMS_MAX 32
16 
17void SzCoderInfo_Init(CSzCoderInfo *p)
18{
19  Buf_Init(&p->Props);
20}
21 
22void SzCoderInfo_Free(CSzCoderInfo *p, ISzAlloc *alloc)
23{
24  Buf_Free(&p->Props, alloc);
25  SzCoderInfo_Init(p);
26}
27 
28void SzFolder_Init(CSzFolder *p)
29{
30  p->Coders = 0;
31  p->BindPairs = 0;
32  p->PackStreams = 0;
33  p->UnpackSizes = 0;
34  p->NumCoders = 0;
35  p->NumBindPairs = 0;
36  p->NumPackStreams = 0;
37  p->UnpackCRCDefined = 0;
38  p->UnpackCRC = 0;
39  p->NumUnpackStreams = 0;
40}
41 
42void SzFolder_Free(CSzFolder *p, ISzAlloc *alloc)
43{
44  UInt32 i;
45  if (p->Coders)
46    for (i = 0; i < p->NumCoders; i++)
47      SzCoderInfo_Free(&p->Coders[i], alloc);
48  IAlloc_Free(alloc, p->Coders);
49  IAlloc_Free(alloc, p->BindPairs);
50  IAlloc_Free(alloc, p->PackStreams);
51  IAlloc_Free(alloc, p->UnpackSizes);
52  SzFolder_Init(p);
53}
54 
55UInt32 SzFolder_GetNumOutStreams(CSzFolder *p)
56{
57  UInt32 result = 0;
58  UInt32 i;
59  for (i = 0; i < p->NumCoders; i++)
60    result += p->Coders[i].NumOutStreams;
61  return result;
62}
63 
64int SzFolder_FindBindPairForInStream(CSzFolder *p, UInt32 inStreamIndex)
65{
66  UInt32 i;
67  for (i = 0; i < p->NumBindPairs; i++)
68    if (p->BindPairs[i].InIndex == inStreamIndex)
69      return i;
70  return -1;
71}
72 
73 
74int SzFolder_FindBindPairForOutStream(CSzFolder *p, UInt32 outStreamIndex)
75{
76  UInt32 i;
77  for (i = 0; i < p->NumBindPairs; i++)
78    if (p->BindPairs[i].OutIndex == outStreamIndex)
79      return i;
80  return -1;
81}
82 
83UInt64 SzFolder_GetUnpackSize(CSzFolder *p)
84{
85  int i = (int)SzFolder_GetNumOutStreams(p);
86  if (i == 0)
87    return 0;
88  for (i--; i >= 0; i--)
89    if (SzFolder_FindBindPairForOutStream(p, i) < 0)
90      return p->UnpackSizes[i];
91  /* throw 1; */
92  return 0;
93}
94 
95void SzFile_Init(CSzFileItem *p)
96{
97  p->HasStream = 1;
98  p->IsDir = 0;
99  p->IsAnti = 0;
100  p->CrcDefined = 0;
101  p->MTimeDefined = 0;
102}
103 
104void SzAr_Init(CSzAr *p)
105{
106  p->PackSizes = 0;
107  p->PackCRCsDefined = 0;
108  p->PackCRCs = 0;
109  p->Folders = 0;
110  p->Files = 0;
111  p->NumPackStreams = 0;
112  p->NumFolders = 0;
113  p->NumFiles = 0;
114}
115 
116void SzAr_Free(CSzAr *p, ISzAlloc *alloc)
117{
118  UInt32 i;
119  if (p->Folders)
120    for (i = 0; i < p->NumFolders; i++)
121      SzFolder_Free(&p->Folders[i], alloc);
122 
123  IAlloc_Free(alloc, p->PackSizes);
124  IAlloc_Free(alloc, p->PackCRCsDefined);
125  IAlloc_Free(alloc, p->PackCRCs);
126  IAlloc_Free(alloc, p->Folders);
127  IAlloc_Free(alloc, p->Files);
128  SzAr_Init(p);
129}
130 
131 
132void SzArEx_Init(CSzArEx *p)
133{
134  SzAr_Init(&p->db);
135  p->FolderStartPackStreamIndex = 0;
136  p->PackStreamStartPositions = 0;
137  p->FolderStartFileIndex = 0;
138  p->FileIndexToFolderIndexMap = 0;
139  p->FileNameOffsets = 0;
140  Buf_Init(&p->FileNames);
141}
142 
143void SzArEx_Free(CSzArEx *p, ISzAlloc *alloc)
144{
145  IAlloc_Free(alloc, p->FolderStartPackStreamIndex);
146  IAlloc_Free(alloc, p->PackStreamStartPositions);
147  IAlloc_Free(alloc, p->FolderStartFileIndex);
148  IAlloc_Free(alloc, p->FileIndexToFolderIndexMap);
149 
150  IAlloc_Free(alloc, p->FileNameOffsets);
151  Buf_Free(&p->FileNames, alloc);
152 
153  SzAr_Free(&p->db, alloc);
154  SzArEx_Init(p);
155}
156 
157/*
158UInt64 GetFolderPackStreamSize(int folderIndex, int streamIndex) const
159{
160  return PackSizes[FolderStartPackStreamIndex[folderIndex] + streamIndex];
161}
162 
163UInt64 GetFilePackSize(int fileIndex) const
164{
165  int folderIndex = FileIndexToFolderIndexMap[fileIndex];
166  if (folderIndex >= 0)
167  {
168    const CSzFolder &folderInfo = Folders[folderIndex];
169    if (FolderStartFileIndex[folderIndex] == fileIndex)
170    return GetFolderFullPackSize(folderIndex);
171  }
172  return 0;
173}
174*/
175 
176#define MY_ALLOC(T, p, size, alloc) { if ((size) == 0) p = 0; else \
177  if ((p = (T *)IAlloc_Alloc(alloc, (size) * sizeof(T))) == 0) return SZ_ERROR_MEM; }
178 
179static SRes SzArEx_Fill(CSzArEx *p, ISzAlloc *alloc)
180{
181  UInt32 startPos = 0;
182  UInt64 startPosSize = 0;
183  UInt32 i;
184  UInt32 folderIndex = 0;
185  UInt32 indexInFolder = 0;
186  MY_ALLOC(UInt32, p->FolderStartPackStreamIndex, p->db.NumFolders, alloc);
187  for (i = 0; i < p->db.NumFolders; i++)
188  {
189    p->FolderStartPackStreamIndex[i] = startPos;
190    startPos += p->db.Folders[i].NumPackStreams;
191  }
192 
193  MY_ALLOC(UInt64, p->PackStreamStartPositions, p->db.NumPackStreams, alloc);
194 
195  for (i = 0; i < p->db.NumPackStreams; i++)
196  {
197    p->PackStreamStartPositions[i] = startPosSize;
198    startPosSize += p->db.PackSizes[i];
199  }
200 
201  MY_ALLOC(UInt32, p->FolderStartFileIndex, p->db.NumFolders, alloc);
202  MY_ALLOC(UInt32, p->FileIndexToFolderIndexMap, p->db.NumFiles, alloc);
203 
204  for (i = 0; i < p->db.NumFiles; i++)
205  {
206    CSzFileItem *file = p->db.Files + i;
207    int emptyStream = !file->HasStream;
208    if (emptyStream && indexInFolder == 0)
209    {
210      p->FileIndexToFolderIndexMap[i] = (UInt32)-1;
211      continue;
212    }
213    if (indexInFolder == 0)
214    {
215      /*
216      v3.13 incorrectly worked with empty folders
217      v4.07: Loop for skipping empty folders
218      */
219      for (;;)
220      {
221        if (folderIndex >= p->db.NumFolders)
222          return SZ_ERROR_ARCHIVE;
223        p->FolderStartFileIndex[folderIndex] = i;
224        if (p->db.Folders[folderIndex].NumUnpackStreams != 0)
225          break;
226        folderIndex++;
227      }
228    }
229    p->FileIndexToFolderIndexMap[i] = folderIndex;
230    if (emptyStream)
231      continue;
232    indexInFolder++;
233    if (indexInFolder >= p->db.Folders[folderIndex].NumUnpackStreams)
234    {
235      folderIndex++;
236      indexInFolder = 0;
237    }
238  }
239  return SZ_OK;
240}
241 
242 
243UInt64 SzArEx_GetFolderStreamPos(const CSzArEx *p, UInt32 folderIndex, UInt32 indexInFolder)
244{
245  return p->dataPos +
246    p->PackStreamStartPositions[p->FolderStartPackStreamIndex[folderIndex] + indexInFolder];
247}
248 
249int SzArEx_GetFolderFullPackSize(const CSzArEx *p, UInt32 folderIndex, UInt64 *resSize)
250{
251  UInt32 packStreamIndex = p->FolderStartPackStreamIndex[folderIndex];
252  CSzFolder *folder = p->db.Folders + folderIndex;
253  UInt64 size = 0;
254  UInt32 i;
255  for (i = 0; i < folder->NumPackStreams; i++)
256  {
257    UInt64 t = size + p->db.PackSizes[packStreamIndex + i];
258    if (t < size) /* check it */
259      return SZ_ERROR_FAIL;
260    size = t;
261  }
262  *resSize = size;
263  return SZ_OK;
264}
265 
266 
267/*
268SRes SzReadTime(const CObjectVector<CBuf> &dataVector,
269    CObjectVector<CSzFileItem> &files, UInt64 type)
270{
271  CBoolVector boolVector;
272  RINOK(ReadBoolVector2(files.Size(), boolVector))
273 
274  CStreamSwitch streamSwitch;
275  RINOK(streamSwitch.Set(this, &dataVector));
276 
277  for (int i = 0; i < files.Size(); i++)
278  {
279    CSzFileItem &file = files[i];
280    CArchiveFileTime fileTime;
281    bool defined = boolVector[i];
282    if (defined)
283    {
284      UInt32 low, high;
285      RINOK(SzReadUInt32(low));
286      RINOK(SzReadUInt32(high));
287      fileTime.dwLowDateTime = low;
288      fileTime.dwHighDateTime = high;
289    }
290    switch(type)
291    {
292      case k7zIdCTime: file.IsCTimeDefined = defined; if (defined) file.CTime = fileTime; break;
293      case k7zIdATime: file.IsATimeDefined = defined; if (defined) file.ATime = fileTime; break;
294      case k7zIdMTime: file.IsMTimeDefined = defined; if (defined) file.MTime = fileTime; break;
295    }
296  }
297  return SZ_OK;
298}
299*/
300 
301static int TestSignatureCandidate(Byte *testBytes)
302{
303  size_t i;
304  for (i = 0; i < k7zSignatureSize; i++)
305    if (testBytes[i] != k7zSignature[i])
306      return 0;
307  return 1;
308}
309 
310typedef struct _CSzState
311{
312  Byte *Data;
313  size_t Size;
314}CSzData;
315 
316static SRes SzReadByte(CSzData *sd, Byte *b)
317{
318  if (sd->Size == 0)
319    return SZ_ERROR_ARCHIVE;
320  sd->Size--;
321  *b = *sd->Data++;
322  return SZ_OK;
323}
324 
325static SRes SzReadBytes(CSzData *sd, Byte *data, size_t size)
326{
327  size_t i;
328  for (i = 0; i < size; i++)
329  {
330    RINOK(SzReadByte(sd, data + i));
331  }
332  return SZ_OK;
333}
334 
335static SRes SzReadUInt32(CSzData *sd, UInt32 *value)
336{
337  int i;
338  *value = 0;
339  for (i = 0; i < 4; i++)
340  {
341    Byte b;
342    RINOK(SzReadByte(sd, &b));
343    *value |= ((UInt32)(b) << (8 * i));
344  }
345  return SZ_OK;
346}
347 
348static SRes SzReadNumber(CSzData *sd, UInt64 *value)
349{
350  Byte firstByte;
351  Byte mask = 0x80;
352  int i;
353  RINOK(SzReadByte(sd, &firstByte));
354  *value = 0;
355  for (i = 0; i < 8; i++)
356  {
357    Byte b;
358    if ((firstByte & mask) == 0)
359    {
360      UInt64 highPart = firstByte & (mask - 1);
361      *value += (highPart << (8 * i));
362      return SZ_OK;
363    }
364    RINOK(SzReadByte(sd, &b));
365    *value |= ((UInt64)b << (8 * i));
366    mask >>= 1;
367  }
368  return SZ_OK;
369}
370 
371static SRes SzReadNumber32(CSzData *sd, UInt32 *value)
372{
373  UInt64 value64;
374  RINOK(SzReadNumber(sd, &value64));
375  if (value64 >= 0x80000000)
376    return SZ_ERROR_UNSUPPORTED;
377  if (value64 >= ((UInt64)(1) << ((sizeof(size_t) - 1) * 8 + 2)))
378    return SZ_ERROR_UNSUPPORTED;
379  *value = (UInt32)value64;
380  return SZ_OK;
381}
382 
383static SRes SzReadID(CSzData *sd, UInt64 *value)
384{
385  return SzReadNumber(sd, value);
386}
387 
388static SRes SzSkeepDataSize(CSzData *sd, UInt64 size)
389{
390  if (size > sd->Size)
391    return SZ_ERROR_ARCHIVE;
392  sd->Size -= (size_t)size;
393  sd->Data += (size_t)size;
394  return SZ_OK;
395}
396 
397static SRes SzSkeepData(CSzData *sd)
398{
399  UInt64 size;
400  RINOK(SzReadNumber(sd, &size));
401  return SzSkeepDataSize(sd, size);
402}
403 
404static SRes SzReadArchiveProperties(CSzData *sd)
405{
406  for (;;)
407  {
408    UInt64 type;
409    RINOK(SzReadID(sd, &type));
410    if (type == k7zIdEnd)
411      break;
412    SzSkeepData(sd);
413  }
414  return SZ_OK;
415}
416 
417static SRes SzWaitAttribute(CSzData *sd, UInt64 attribute)
418{
419  for (;;)
420  {
421    UInt64 type;
422    RINOK(SzReadID(sd, &type));
423    if (type == attribute)
424      return SZ_OK;
425    if (type == k7zIdEnd)
426      return SZ_ERROR_ARCHIVE;
427    RINOK(SzSkeepData(sd));
428  }
429}
430 
431static SRes SzReadBoolVector(CSzData *sd, size_t numItems, Byte **v, ISzAlloc *alloc)
432{
433  Byte b = 0;
434  Byte mask = 0;
435  size_t i;
436  MY_ALLOC(Byte, *v, numItems, alloc);
437  for (i = 0; i < numItems; i++)
438  {
439    if (mask == 0)
440    {
441      RINOK(SzReadByte(sd, &b));
442      mask = 0x80;
443    }
444    (*v)[i] = (Byte)(((b & mask) != 0) ? 1 : 0);
445    mask >>= 1;
446  }
447  return SZ_OK;
448}
449 
450static SRes SzReadBoolVector2(CSzData *sd, size_t numItems, Byte **v, ISzAlloc *alloc)
451{
452  Byte allAreDefined;
453  size_t i;
454  RINOK(SzReadByte(sd, &allAreDefined));
455  if (allAreDefined == 0)
456    return SzReadBoolVector(sd, numItems, v, alloc);
457  MY_ALLOC(Byte, *v, numItems, alloc);
458  for (i = 0; i < numItems; i++)
459    (*v)[i] = 1;
460  return SZ_OK;
461}
462 
463static SRes SzReadHashDigests(
464    CSzData *sd,
465    size_t numItems,
466    Byte **digestsDefined,
467    UInt32 **digests,
468    ISzAlloc *alloc)
469{
470  size_t i;
471  RINOK(SzReadBoolVector2(sd, numItems, digestsDefined, alloc));
472  MY_ALLOC(UInt32, *digests, numItems, alloc);
473  for (i = 0; i < numItems; i++)
474    if ((*digestsDefined)[i])
475    {
476      RINOK(SzReadUInt32(sd, (*digests) + i));
477    }
478  return SZ_OK;
479}
480 
481static SRes SzReadPackInfo(
482    CSzData *sd,
483    UInt64 *dataOffset,
484    UInt32 *numPackStreams,
485    UInt64 **packSizes,
486    Byte **packCRCsDefined,
487    UInt32 **packCRCs,
488    ISzAlloc *alloc)
489{
490  UInt32 i;
491  RINOK(SzReadNumber(sd, dataOffset));
492  RINOK(SzReadNumber32(sd, numPackStreams));
493 
494  RINOK(SzWaitAttribute(sd, k7zIdSize));
495 
496  MY_ALLOC(UInt64, *packSizes, (size_t)*numPackStreams, alloc);
497 
498  for (i = 0; i < *numPackStreams; i++)
499  {
500    RINOK(SzReadNumber(sd, (*packSizes) + i));
501  }
502 
503  for (;;)
504  {
505    UInt64 type;
506    RINOK(SzReadID(sd, &type));
507    if (type == k7zIdEnd)
508      break;
509    if (type == k7zIdCRC)
510    {
511      RINOK(SzReadHashDigests(sd, (size_t)*numPackStreams, packCRCsDefined, packCRCs, alloc));
512      continue;
513    }
514    RINOK(SzSkeepData(sd));
515  }
516  if (*packCRCsDefined == 0)
517  {
518    MY_ALLOC(Byte, *packCRCsDefined, (size_t)*numPackStreams, alloc);
519    MY_ALLOC(UInt32, *packCRCs, (size_t)*numPackStreams, alloc);
520    for (i = 0; i < *numPackStreams; i++)
521    {
522      (*packCRCsDefined)[i] = 0;
523      (*packCRCs)[i] = 0;
524    }
525  }
526  return SZ_OK;
527}
528 
529static SRes SzReadSwitch(CSzData *sd)
530{
531  Byte external;
532  RINOK(SzReadByte(sd, &external));
533  return (external == 0) ? SZ_OK: SZ_ERROR_UNSUPPORTED;
534}
535 
536static SRes SzGetNextFolderItem(CSzData *sd, CSzFolder *folder, ISzAlloc *alloc)
537{
538  UInt32 numCoders, numBindPairs, numPackStreams, i;
539  UInt32 numInStreams = 0, numOutStreams = 0;
540   
541  RINOK(SzReadNumber32(sd, &numCoders));
542  if (numCoders > NUM_FOLDER_CODERS_MAX)
543    return SZ_ERROR_UNSUPPORTED;
544  folder->NumCoders = numCoders;
545   
546  MY_ALLOC(CSzCoderInfo, folder->Coders, (size_t)numCoders, alloc);
547 
548  for (i = 0; i < numCoders; i++)
549    SzCoderInfo_Init(folder->Coders + i);
550 
551  for (i = 0; i < numCoders; i++)
552  {
553    Byte mainByte;
554    CSzCoderInfo *coder = folder->Coders + i;
555    {
556      unsigned idSize, j;
557      Byte longID[15];
558      RINOK(SzReadByte(sd, &mainByte));
559      idSize = (unsigned)(mainByte & 0xF);
560      RINOK(SzReadBytes(sd, longID, idSize));
561      if (idSize > sizeof(coder->MethodID))
562        return SZ_ERROR_UNSUPPORTED;
563      coder->MethodID = 0;
564      for (j = 0; j < idSize; j++)
565        coder->MethodID |= (UInt64)longID[idSize - 1 - j] << (8 * j);
566 
567      if ((mainByte & 0x10) != 0)
568      {
569        RINOK(SzReadNumber32(sd, &coder->NumInStreams));
570        RINOK(SzReadNumber32(sd, &coder->NumOutStreams));
571        if (coder->NumInStreams > NUM_CODER_STREAMS_MAX ||
572            coder->NumOutStreams > NUM_CODER_STREAMS_MAX)
573          return SZ_ERROR_UNSUPPORTED;
574      }
575      else
576      {
577        coder->NumInStreams = 1;
578        coder->NumOutStreams = 1;
579      }
580      if ((mainByte & 0x20) != 0)
581      {
582        UInt64 propertiesSize = 0;
583        RINOK(SzReadNumber(sd, &propertiesSize));
584        if (!Buf_Create(&coder->Props, (size_t)propertiesSize, alloc))
585          return SZ_ERROR_MEM;
586        RINOK(SzReadBytes(sd, coder->Props.data, (size_t)propertiesSize));
587      }
588    }
589    while ((mainByte & 0x80) != 0)
590    {
591      RINOK(SzReadByte(sd, &mainByte));
592      RINOK(SzSkeepDataSize(sd, (mainByte & 0xF)));
593      if ((mainByte & 0x10) != 0)
594      {
595        UInt32 n;
596        RINOK(SzReadNumber32(sd, &n));
597        RINOK(SzReadNumber32(sd, &n));
598      }
599      if ((mainByte & 0x20) != 0)
600      {
601        UInt64 propertiesSize = 0;
602        RINOK(SzReadNumber(sd, &propertiesSize));
603        RINOK(SzSkeepDataSize(sd, propertiesSize));
604      }
605    }
606    numInStreams += coder->NumInStreams;
607    numOutStreams += coder->NumOutStreams;
608  }
609 
610  if (numOutStreams == 0)
611    return SZ_ERROR_UNSUPPORTED;
612 
613  folder->NumBindPairs = numBindPairs = numOutStreams - 1;
614  MY_ALLOC(CSzBindPair, folder->BindPairs, (size_t)numBindPairs, alloc);
615 
616  for (i = 0; i < numBindPairs; i++)
617  {
618    CSzBindPair *bp = folder->BindPairs + i;
619    RINOK(SzReadNumber32(sd, &bp->InIndex));
620    RINOK(SzReadNumber32(sd, &bp->OutIndex));
621  }
622 
623  if (numInStreams < numBindPairs)
624    return SZ_ERROR_UNSUPPORTED;
625 
626  folder->NumPackStreams = numPackStreams = numInStreams - numBindPairs;
627  MY_ALLOC(UInt32, folder->PackStreams, (size_t)numPackStreams, alloc);
628 
629  if (numPackStreams == 1)
630  {
631    for (i = 0; i < numInStreams ; i++)
632      if (SzFolder_FindBindPairForInStream(folder, i) < 0)
633        break;
634    if (i == numInStreams)
635      return SZ_ERROR_UNSUPPORTED;
636    folder->PackStreams[0] = i;
637  }
638  else
639    for (i = 0; i < numPackStreams; i++)
640    {
641      RINOK(SzReadNumber32(sd, folder->PackStreams + i));
642    }
643  return SZ_OK;
644}
645 
646static SRes SzReadUnpackInfo(
647    CSzData *sd,
648    UInt32 *numFolders,
649    CSzFolder **folders,  /* for alloc */
650    ISzAlloc *alloc,
651    ISzAlloc *allocTemp)
652{
653  UInt32 i;
654  RINOK(SzWaitAttribute(sd, k7zIdFolder));
655  RINOK(SzReadNumber32(sd, numFolders));
656  {
657    RINOK(SzReadSwitch(sd));
658 
659    MY_ALLOC(CSzFolder, *folders, (size_t)*numFolders, alloc);
660 
661    for (i = 0; i < *numFolders; i++)
662      SzFolder_Init((*folders) + i);
663 
664    for (i = 0; i < *numFolders; i++)
665    {
666      RINOK(SzGetNextFolderItem(sd, (*folders) + i, alloc));
667    }
668  }
669 
670  RINOK(SzWaitAttribute(sd, k7zIdCodersUnpackSize));
671 
672  for (i = 0; i < *numFolders; i++)
673  {
674    UInt32 j;
675    CSzFolder *folder = (*folders) + i;
676    UInt32 numOutStreams = SzFolder_GetNumOutStreams(folder);
677 
678    MY_ALLOC(UInt64, folder->UnpackSizes, (size_t)numOutStreams, alloc);
679 
680    for (j = 0; j < numOutStreams; j++)
681    {
682      RINOK(SzReadNumber(sd, folder->UnpackSizes + j));
683    }
684  }
685 
686  for (;;)
687  {
688    UInt64 type;
689    RINOK(SzReadID(sd, &type));
690    if (type == k7zIdEnd)
691      return SZ_OK;
692    if (type == k7zIdCRC)
693    {
694      SRes res;
695      Byte *crcsDefined = 0;
696      UInt32 *crcs = 0;
697      res = SzReadHashDigests(sd, *numFolders, &crcsDefined, &crcs, allocTemp);
698      if (res == SZ_OK)
699      {
700        for (i = 0; i < *numFolders; i++)
701        {
702          CSzFolder *folder = (*folders) + i;
703          folder->UnpackCRCDefined = crcsDefined[i];
704          folder->UnpackCRC = crcs[i];
705        }
706      }
707      IAlloc_Free(allocTemp, crcs);
708      IAlloc_Free(allocTemp, crcsDefined);
709      RINOK(res);
710      continue;
711    }
712    RINOK(SzSkeepData(sd));
713  }
714}
715 
716static SRes SzReadSubStreamsInfo(
717    CSzData *sd,
718    UInt32 numFolders,
719    CSzFolder *folders,
720    UInt32 *numUnpackStreams,
721    UInt64 **unpackSizes,
722    Byte **digestsDefined,
723    UInt32 **digests,
724    ISzAlloc *allocTemp)
725{
726  UInt64 type = 0;
727  UInt32 i;
728  UInt32 si = 0;
729  UInt32 numDigests = 0;
730 
731  for (i = 0; i < numFolders; i++)
732    folders[i].NumUnpackStreams = 1;
733  *numUnpackStreams = numFolders;
734 
735  for (;;)
736  {
737    RINOK(SzReadID(sd, &type));
738    if (type == k7zIdNumUnpackStream)
739    {
740      *numUnpackStreams = 0;
741      for (i = 0; i < numFolders; i++)
742      {
743        UInt32 numStreams;
744        RINOK(SzReadNumber32(sd, &numStreams));
745        folders[i].NumUnpackStreams = numStreams;
746        *numUnpackStreams += numStreams;
747      }
748      continue;
749    }
750    if (type == k7zIdCRC || type == k7zIdSize)
751      break;
752    if (type == k7zIdEnd)
753      break;
754    RINOK(SzSkeepData(sd));
755  }
756 
757  if (*numUnpackStreams == 0)
758  {
759    *unpackSizes = 0;
760    *digestsDefined = 0;
761    *digests = 0;
762  }
763  else
764  {
765    *unpackSizes = (UInt64 *)IAlloc_Alloc(allocTemp, (size_t)*numUnpackStreams * sizeof(UInt64));
766    RINOM(*unpackSizes);
767    *digestsDefined = (Byte *)IAlloc_Alloc(allocTemp, (size_t)*numUnpackStreams * sizeof(Byte));
768    RINOM(*digestsDefined);
769    *digests = (UInt32 *)IAlloc_Alloc(allocTemp, (size_t)*numUnpackStreams * sizeof(UInt32));
770    RINOM(*digests);
771  }
772 
773  for (i = 0; i < numFolders; i++)
774  {
775    /*
776    v3.13 incorrectly worked with empty folders
777    v4.07: we check that folder is empty
778    */
779    UInt64 sum = 0;
780    UInt32 j;
781    UInt32 numSubstreams = folders[i].NumUnpackStreams;
782    if (numSubstreams == 0)
783      continue;
784    if (type == k7zIdSize)
785    for (j = 1; j < numSubstreams; j++)
786    {
787      UInt64 size;
788      RINOK(SzReadNumber(sd, &size));
789      (*unpackSizes)[si++] = size;
790      sum += size;
791    }
792    (*unpackSizes)[si++] = SzFolder_GetUnpackSize(folders + i) - sum;
793  }
794  if (type == k7zIdSize)
795  {
796    RINOK(SzReadID(sd, &type));
797  }
798 
799  for (i = 0; i < *numUnpackStreams; i++)
800  {
801    (*digestsDefined)[i] = 0;
802    (*digests)[i] = 0;
803  }
804 
805 
806  for (i = 0; i < numFolders; i++)
807  {
808    UInt32 numSubstreams = folders[i].NumUnpackStreams;
809    if (numSubstreams != 1 || !folders[i].UnpackCRCDefined)
810      numDigests += numSubstreams;
811  }
812 
813 
814  si = 0;
815  for (;;)
816  {
817    if (type == k7zIdCRC)
818    {
819      int digestIndex = 0;
820      Byte *digestsDefined2 = 0;
821      UInt32 *digests2 = 0;
822      SRes res = SzReadHashDigests(sd, numDigests, &digestsDefined2, &digests2, allocTemp);
823      if (res == SZ_OK)
824      {
825        for (i = 0; i < numFolders; i++)
826        {
827          CSzFolder *folder = folders + i;
828          UInt32 numSubstreams = folder->NumUnpackStreams;
829          if (numSubstreams == 1 && folder->UnpackCRCDefined)
830          {
831            (*digestsDefined)[si] = 1;
832            (*digests)[si] = folder->UnpackCRC;
833            si++;
834          }
835          else
836          {
837            UInt32 j;
838            for (j = 0; j < numSubstreams; j++, digestIndex++)
839            {
840              (*digestsDefined)[si] = digestsDefined2[digestIndex];
841              (*digests)[si] = digests2[digestIndex];
842              si++;
843            }
844          }
845        }
846      }
847      IAlloc_Free(allocTemp, digestsDefined2);
848      IAlloc_Free(allocTemp, digests2);
849      RINOK(res);
850    }
851    else if (type == k7zIdEnd)
852      return SZ_OK;
853    else
854    {
855      RINOK(SzSkeepData(sd));
856    }
857    RINOK(SzReadID(sd, &type));
858  }
859}
860 
861 
862static SRes SzReadStreamsInfo(
863    CSzData *sd,
864    UInt64 *dataOffset,
865    CSzAr *p,
866    UInt32 *numUnpackStreams,
867    UInt64 **unpackSizes, /* allocTemp */
868    Byte **digestsDefined,   /* allocTemp */
869    UInt32 **digests,        /* allocTemp */
870    ISzAlloc *alloc,
871    ISzAlloc *allocTemp)
872{
873  for (;;)
874  {
875    UInt64 type;
876    RINOK(SzReadID(sd, &type));
877    if ((UInt64)(int)type != type)
878      return SZ_ERROR_UNSUPPORTED;
879    switch((int)type)
880    {
881      case k7zIdEnd:
882        return SZ_OK;
883      case k7zIdPackInfo:
884      {
885        RINOK(SzReadPackInfo(sd, dataOffset, &p->NumPackStreams,
886            &p->PackSizes, &p->PackCRCsDefined, &p->PackCRCs, alloc));
887        break;
888      }
889      case k7zIdUnpackInfo:
890      {
891        RINOK(SzReadUnpackInfo(sd, &p->NumFolders, &p->Folders, alloc, allocTemp));
892        break;
893      }
894      case k7zIdSubStreamsInfo:
895      {
896        RINOK(SzReadSubStreamsInfo(sd, p->NumFolders, p->Folders,
897            numUnpackStreams, unpackSizes, digestsDefined, digests, allocTemp));
898        break;
899      }
900      default:
901        return SZ_ERROR_UNSUPPORTED;
902    }
903  }
904}
905 
906size_t SzArEx_GetFileNameUtf16(const CSzArEx *p, size_t fileIndex, UInt16 *dest)
907{
908  size_t len = p->FileNameOffsets[fileIndex + 1] - p->FileNameOffsets[fileIndex];
909  if (dest != 0)
910  {
911    size_t i;
912    const Byte *src = p->FileNames.data + (p->FileNameOffsets[fileIndex] * 2);
913    for (i = 0; i < len; i++)
914      dest[i] = GetUi16(src + i * 2);
915  }
916  return len;
917}
918 
919static SRes SzReadFileNames(const Byte *p, size_t size, UInt32 numFiles, size_t *sizes)
920{
921  UInt32 i;
922  size_t pos = 0;
923  for (i = 0; i < numFiles; i++)
924  {
925    sizes[i] = pos;
926    for (;;)
927    {
928      if (pos >= size)
929        return SZ_ERROR_ARCHIVE;
930      if (p[pos * 2] == 0 && p[pos * 2 + 1] == 0)
931        break;
932      pos++;
933    }
934    pos++;
935  }
936  sizes[i] = pos;
937  return (pos == size) ? SZ_OK : SZ_ERROR_ARCHIVE;
938}
939 
940static SRes SzReadHeader2(
941    CSzArEx *p,   /* allocMain */
942    CSzData *sd,
943    UInt64 **unpackSizes,  /* allocTemp */
944    Byte **digestsDefined,    /* allocTemp */
945    UInt32 **digests,         /* allocTemp */
946    Byte **emptyStreamVector, /* allocTemp */
947    Byte **emptyFileVector,   /* allocTemp */
948    Byte **lwtVector,         /* allocTemp */
949    ISzAlloc *allocMain,
950    ISzAlloc *allocTemp)
951{
952  UInt64 type;
953  UInt32 numUnpackStreams = 0;
954  UInt32 numFiles = 0;
955  CSzFileItem *files = 0;
956  UInt32 numEmptyStreams = 0;
957  UInt32 i;
958 
959  RINOK(SzReadID(sd, &type));
960 
961  if (type == k7zIdArchiveProperties)
962  {
963    RINOK(SzReadArchiveProperties(sd));
964    RINOK(SzReadID(sd, &type));
965  }
966 
967 
968  if (type == k7zIdMainStreamsInfo)
969  {
970    RINOK(SzReadStreamsInfo(sd,
971        &p->dataPos,
972        &p->db,
973        &numUnpackStreams,
974        unpackSizes,
975        digestsDefined,
976        digests, allocMain, allocTemp));
977    p->dataPos += p->startPosAfterHeader;
978    RINOK(SzReadID(sd, &type));
979  }
980 
981  if (type == k7zIdEnd)
982    return SZ_OK;
983  if (type != k7zIdFilesInfo)
984    return SZ_ERROR_ARCHIVE;
985   
986  RINOK(SzReadNumber32(sd, &numFiles));
987  p->db.NumFiles = numFiles;
988 
989  MY_ALLOC(CSzFileItem, files, (size_t)numFiles, allocMain);
990 
991  p->db.Files = files;
992  for (i = 0; i < numFiles; i++)
993    SzFile_Init(files + i);
994 
995  for (;;)
996  {
997    UInt64 type;
998    UInt64 size;
999    RINOK(SzReadID(sd, &type));
1000    if (type == k7zIdEnd)
1001      break;
1002    RINOK(SzReadNumber(sd, &size));
1003    if (size > sd->Size)
1004      return SZ_ERROR_ARCHIVE;
1005    if ((UInt64)(int)type != type)
1006    {
1007      RINOK(SzSkeepDataSize(sd, size));
1008    }
1009    else
1010    switch((int)type)
1011    {
1012      case k7zIdName:
1013      {
1014        size_t namesSize;
1015        RINOK(SzReadSwitch(sd));
1016        namesSize = (size_t)size - 1;
1017        if ((namesSize & 1) != 0)
1018          return SZ_ERROR_ARCHIVE;
1019        if (!Buf_Create(&p->FileNames, namesSize, allocMain))
1020          return SZ_ERROR_MEM;
1021        MY_ALLOC(size_t, p->FileNameOffsets, numFiles + 1, allocMain);
1022        memcpy(p->FileNames.data, sd->Data, namesSize);
1023        RINOK(SzReadFileNames(sd->Data, namesSize >> 1, numFiles, p->FileNameOffsets))
1024        RINOK(SzSkeepDataSize(sd, namesSize));
1025        break;
1026      }
1027      case k7zIdEmptyStream:
1028      {
1029        RINOK(SzReadBoolVector(sd, numFiles, emptyStreamVector, allocTemp));
1030        numEmptyStreams = 0;
1031        for (i = 0; i < numFiles; i++)
1032          if ((*emptyStreamVector)[i])
1033            numEmptyStreams++;
1034        break;
1035      }
1036      case k7zIdEmptyFile:
1037      {
1038        RINOK(SzReadBoolVector(sd, numEmptyStreams, emptyFileVector, allocTemp));
1039        break;
1040      }
1041      case k7zIdWinAttributes:
1042      {
1043        RINOK(SzReadBoolVector2(sd, numFiles, lwtVector, allocTemp));
1044        RINOK(SzReadSwitch(sd));
1045        for (i = 0; i < numFiles; i++)
1046        {
1047          CSzFileItem *f = &files[i];
1048          Byte defined = (*lwtVector)[i];
1049          f->AttribDefined = defined;
1050          f->Attrib = 0;
1051          if (defined)
1052          {
1053            RINOK(SzReadUInt32(sd, &f->Attrib));
1054          }
1055        }
1056        IAlloc_Free(allocTemp, *lwtVector);
1057        *lwtVector = NULL;
1058        break;
1059      }
1060      case k7zIdMTime:
1061      {
1062        RINOK(SzReadBoolVector2(sd, numFiles, lwtVector, allocTemp));
1063        RINOK(SzReadSwitch(sd));
1064        for (i = 0; i < numFiles; i++)
1065        {
1066          CSzFileItem *f = &files[i];
1067          Byte defined = (*lwtVector)[i];
1068          f->MTimeDefined = defined;
1069          f->MTime.Low = f->MTime.High = 0;
1070          if (defined)
1071          {
1072            RINOK(SzReadUInt32(sd, &f->MTime.Low));
1073            RINOK(SzReadUInt32(sd, &f->MTime.High));
1074          }
1075        }
1076        IAlloc_Free(allocTemp, *lwtVector);
1077        *lwtVector = NULL;
1078        break;
1079      }
1080      default:
1081      {
1082        RINOK(SzSkeepDataSize(sd, size));
1083      }
1084    }
1085  }
1086 
1087  {
1088    UInt32 emptyFileIndex = 0;
1089    UInt32 sizeIndex = 0;
1090    for (i = 0; i < numFiles; i++)
1091    {
1092      CSzFileItem *file = files + i;
1093      file->IsAnti = 0;
1094      if (*emptyStreamVector == 0)
1095        file->HasStream = 1;
1096      else
1097        file->HasStream = (Byte)((*emptyStreamVector)[i] ? 0 : 1);
1098      if (file->HasStream)
1099      {
1100        file->IsDir = 0;
1101        file->Size = (*unpackSizes)[sizeIndex];
1102        file->Crc = (*digests)[sizeIndex];
1103        file->CrcDefined = (Byte)(*digestsDefined)[sizeIndex];
1104        sizeIndex++;
1105      }
1106      else
1107      {
1108        if (*emptyFileVector == 0)
1109          file->IsDir = 1;
1110        else
1111          file->IsDir = (Byte)((*emptyFileVector)[emptyFileIndex] ? 0 : 1);
1112        emptyFileIndex++;
1113        file->Size = 0;
1114        file->Crc = 0;
1115        file->CrcDefined = 0;
1116      }
1117    }
1118  }
1119  return SzArEx_Fill(p, allocMain);
1120}
1121 
1122static SRes SzReadHeader(
1123    CSzArEx *p,
1124    CSzData *sd,
1125    ISzAlloc *allocMain,
1126    ISzAlloc *allocTemp)
1127{
1128  UInt64 *unpackSizes = 0;
1129  Byte *digestsDefined = 0;
1130  UInt32 *digests = 0;
1131  Byte *emptyStreamVector = 0;
1132  Byte *emptyFileVector = 0;
1133  Byte *lwtVector = 0;
1134  SRes res = SzReadHeader2(p, sd,
1135      &unpackSizes, &digestsDefined, &digests,
1136      &emptyStreamVector, &emptyFileVector, &lwtVector,
1137      allocMain, allocTemp);
1138  IAlloc_Free(allocTemp, unpackSizes);
1139  IAlloc_Free(allocTemp, digestsDefined);
1140  IAlloc_Free(allocTemp, digests);
1141  IAlloc_Free(allocTemp, emptyStreamVector);
1142  IAlloc_Free(allocTemp, emptyFileVector);
1143  IAlloc_Free(allocTemp, lwtVector);
1144  return res;
1145}
1146 
1147static SRes SzReadAndDecodePackedStreams2(
1148    ILookInStream *inStream,
1149    CSzData *sd,
1150    CBuf *outBuffer,
1151    UInt64 baseOffset,
1152    CSzAr *p,
1153    UInt64 **unpackSizes,
1154    Byte **digestsDefined,
1155    UInt32 **digests,
1156    ISzAlloc *allocTemp)
1157{
1158 
1159  UInt32 numUnpackStreams = 0;
1160  UInt64 dataStartPos;
1161  CSzFolder *folder;
1162  UInt64 unpackSize;
1163  SRes res;
1164 
1165  RINOK(SzReadStreamsInfo(sd, &dataStartPos, p,
1166      &numUnpackStreams,  unpackSizes, digestsDefined, digests,
1167      allocTemp, allocTemp));
1168   
1169  dataStartPos += baseOffset;
1170  if (p->NumFolders != 1)
1171    return SZ_ERROR_ARCHIVE;
1172 
1173  folder = p->Folders;
1174  unpackSize = SzFolder_GetUnpackSize(folder);
1175   
1176  RINOK(LookInStream_SeekTo(inStream, dataStartPos));
1177 
1178  if (!Buf_Create(outBuffer, (size_t)unpackSize, allocTemp))
1179    return SZ_ERROR_MEM;
1180   
1181  res = SzFolder_Decode(folder, p->PackSizes,
1182          inStream, dataStartPos,
1183          outBuffer->data, (size_t)unpackSize, allocTemp);
1184  RINOK(res);
1185  if (folder->UnpackCRCDefined)
1186    if (CrcCalc(outBuffer->data, (size_t)unpackSize) != folder->UnpackCRC)
1187      return SZ_ERROR_CRC;
1188  return SZ_OK;
1189}
1190 
1191static SRes SzReadAndDecodePackedStreams(
1192    ILookInStream *inStream,
1193    CSzData *sd,
1194    CBuf *outBuffer,
1195    UInt64 baseOffset,
1196    ISzAlloc *allocTemp)
1197{
1198  CSzAr p;
1199  UInt64 *unpackSizes = 0;
1200  Byte *digestsDefined = 0;
1201  UInt32 *digests = 0;
1202  SRes res;
1203  SzAr_Init(&p);
1204  res = SzReadAndDecodePackedStreams2(inStream, sd, outBuffer, baseOffset,
1205    &p, &unpackSizes, &digestsDefined, &digests,
1206    allocTemp);
1207  SzAr_Free(&p, allocTemp);
1208  IAlloc_Free(allocTemp, unpackSizes);
1209  IAlloc_Free(allocTemp, digestsDefined);
1210  IAlloc_Free(allocTemp, digests);
1211  return res;
1212}
1213 
1214static SRes SzArEx_Open2(
1215    CSzArEx *p,
1216    ILookInStream *inStream,
1217    ISzAlloc *allocMain,
1218    ISzAlloc *allocTemp)
1219{
1220  Byte header[k7zStartHeaderSize];
1221  Int64 startArcPos;
1222  UInt64 nextHeaderOffset, nextHeaderSize;
1223  size_t nextHeaderSizeT;
1224  UInt32 nextHeaderCRC;
1225  CBuf buffer;
1226  SRes res;
1227 
1228  startArcPos = 0;
1229  RINOK(inStream->Seek(inStream, &startArcPos, SZ_SEEK_CUR));
1230 
1231  RINOK(LookInStream_Read2(inStream, header, k7zStartHeaderSize, SZ_ERROR_NO_ARCHIVE));
1232 
1233  if (!TestSignatureCandidate(header))
1234    return SZ_ERROR_NO_ARCHIVE;
1235  if (header[6] != k7zMajorVersion)
1236    return SZ_ERROR_UNSUPPORTED;
1237 
1238  nextHeaderOffset = GetUi64(header + 12);
1239  nextHeaderSize = GetUi64(header + 20);
1240  nextHeaderCRC = GetUi32(header + 28);
1241 
1242  p->startPosAfterHeader = startArcPos + k7zStartHeaderSize;
1243   
1244  if (CrcCalc(header + 12, 20) != GetUi32(header + 8))
1245    return SZ_ERROR_CRC;
1246 
1247  nextHeaderSizeT = (size_t)nextHeaderSize;
1248  if (nextHeaderSizeT != nextHeaderSize)
1249    return SZ_ERROR_MEM;
1250  if (nextHeaderSizeT == 0)
1251    return SZ_OK;
1252  if (nextHeaderOffset > nextHeaderOffset + nextHeaderSize ||
1253      nextHeaderOffset > nextHeaderOffset + nextHeaderSize + k7zStartHeaderSize)
1254    return SZ_ERROR_NO_ARCHIVE;
1255 
1256  {
1257    Int64 pos = 0;
1258    RINOK(inStream->Seek(inStream, &pos, SZ_SEEK_END));
1259    if ((UInt64)pos < startArcPos + nextHeaderOffset ||
1260        (UInt64)pos < startArcPos + k7zStartHeaderSize + nextHeaderOffset ||
1261        (UInt64)pos < startArcPos + k7zStartHeaderSize + nextHeaderOffset + nextHeaderSize)
1262      return SZ_ERROR_INPUT_EOF;
1263  }
1264 
1265  RINOK(LookInStream_SeekTo(inStream, startArcPos + k7zStartHeaderSize + nextHeaderOffset));
1266 
1267  if (!Buf_Create(&buffer, nextHeaderSizeT, allocTemp))
1268    return SZ_ERROR_MEM;
1269 
1270  res = LookInStream_Read(inStream, buffer.data, nextHeaderSizeT);
1271  if (res == SZ_OK)
1272  {
1273    res = SZ_ERROR_ARCHIVE;
1274    if (CrcCalc(buffer.data, nextHeaderSizeT) == nextHeaderCRC)
1275    {
1276      CSzData sd;
1277      UInt64 type;
1278      sd.Data = buffer.data;
1279      sd.Size = buffer.size;
1280      res = SzReadID(&sd, &type);
1281      if (res == SZ_OK)
1282      {
1283        if (type == k7zIdEncodedHeader)
1284        {
1285          CBuf outBuffer;
1286          Buf_Init(&outBuffer);
1287          res = SzReadAndDecodePackedStreams(inStream, &sd, &outBuffer, p->startPosAfterHeader, allocTemp);
1288          if (res != SZ_OK)
1289            Buf_Free(&outBuffer, allocTemp);
1290          else
1291          {
1292            Buf_Free(&buffer, allocTemp);
1293            buffer.data = outBuffer.data;
1294            buffer.size = outBuffer.size;
1295            sd.Data = buffer.data;
1296            sd.Size = buffer.size;
1297            res = SzReadID(&sd, &type);
1298          }
1299        }
1300      }
1301      if (res == SZ_OK)
1302      {
1303        if (type == k7zIdHeader)
1304          res = SzReadHeader(p, &sd, allocMain, allocTemp);
1305        else
1306          res = SZ_ERROR_UNSUPPORTED;
1307      }
1308    }
1309  }
1310  Buf_Free(&buffer, allocTemp);
1311  return res;
1312}
1313 
1314SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream, ISzAlloc *allocMain, ISzAlloc *allocTemp)
1315{
1316  SRes res = SzArEx_Open2(p, inStream, allocMain, allocTemp);
1317  if (res != SZ_OK)
1318    SzArEx_Free(p, allocMain);
1319  return res;
1320}
1321 
1322SRes SzArEx_Extract(
1323    const CSzArEx *p,
1324    ILookInStream *inStream,
1325    UInt32 fileIndex,
1326    UInt32 *blockIndex,
1327    Byte **outBuffer,
1328    size_t *outBufferSize,
1329    size_t *offset,
1330    size_t *outSizeProcessed,
1331    ISzAlloc *allocMain,
1332    ISzAlloc *allocTemp)
1333{
1334  UInt32 folderIndex = p->FileIndexToFolderIndexMap[fileIndex];
1335  SRes res = SZ_OK;
1336  *offset = 0;
1337  *outSizeProcessed = 0;
1338  if (folderIndex == (UInt32)-1)
1339  {
1340    IAlloc_Free(allocMain, *outBuffer);
1341    *blockIndex = folderIndex;
1342    *outBuffer = 0;
1343    *outBufferSize = 0;
1344    return SZ_OK;
1345  }
1346 
1347  if (*outBuffer == 0 || *blockIndex != folderIndex)
1348  {
1349    CSzFolder *folder = p->db.Folders + folderIndex;
1350    UInt64 unpackSizeSpec = SzFolder_GetUnpackSize(folder);
1351    size_t unpackSize = (size_t)unpackSizeSpec;
1352    UInt64 startOffset = SzArEx_GetFolderStreamPos(p, folderIndex, 0);
1353 
1354    if (unpackSize != unpackSizeSpec)
1355      return SZ_ERROR_MEM;
1356    *blockIndex = folderIndex;
1357    IAlloc_Free(allocMain, *outBuffer);
1358    *outBuffer = 0;
1359     
1360    RINOK(LookInStream_SeekTo(inStream, startOffset));
1361     
1362    if (res == SZ_OK)
1363    {
1364      *outBufferSize = unpackSize;
1365      if (unpackSize != 0)
1366      {
1367        *outBuffer = (Byte *)IAlloc_Alloc(allocMain, unpackSize);
1368        if (*outBuffer == 0)
1369          res = SZ_ERROR_MEM;
1370      }
1371      if (res == SZ_OK)
1372      {
1373        res = SzFolder_Decode(folder,
1374          p->db.PackSizes + p->FolderStartPackStreamIndex[folderIndex],
1375          inStream, startOffset,
1376          *outBuffer, unpackSize, allocTemp);
1377        if (res == SZ_OK)
1378        {
1379          if (folder->UnpackCRCDefined)
1380          {
1381            if (CrcCalc(*outBuffer, unpackSize) != folder->UnpackCRC)
1382              res = SZ_ERROR_CRC;
1383          }
1384        }
1385      }
1386    }
1387  }
1388  if (res == SZ_OK)
1389  {
1390    UInt32 i;
1391    CSzFileItem *fileItem = p->db.Files + fileIndex;
1392    *offset = 0;
1393    for (i = p->FolderStartFileIndex[folderIndex]; i < fileIndex; i++)
1394      *offset += (UInt32)p->db.Files[i].Size;
1395    *outSizeProcessed = (size_t)fileItem->Size;
1396    if (*offset + *outSizeProcessed > *outBufferSize)
1397      return SZ_ERROR_FAIL;
1398    if (fileItem->CrcDefined && CrcCalc(*outBuffer + *offset, *outSizeProcessed) != fileItem->Crc)
1399      res = SZ_ERROR_CRC;
1400  }
1401  return res;
1402}
src/lib/lib7z/XzEnc.c
r0r14440
1/* XzEnc.c -- Xz Encode
22011-02-07 : Igor Pavlov : Public domain */
3 
4#include <stdlib.h>
5#include <string.h>
6 
7#include "7zCrc.h"
8#include "Alloc.h"
9#include "Bra.h"
10#include "CpuArch.h"
11#ifdef USE_SUBBLOCK
12#include "Bcj3Enc.c"
13#include "SbFind.c"
14#include "SbEnc.c"
15#endif
16 
17#include "XzEnc.h"
18 
19static void *SzBigAlloc(void *p, size_t size) { p = p; return BigAlloc(size); }
20static void SzBigFree(void *p, void *address) { p = p; BigFree(address); }
21static ISzAlloc g_BigAlloc = { SzBigAlloc, SzBigFree };
22 
23static void *SzAlloc(void *p, size_t size) { p = p; return MyAlloc(size); }
24static void SzFree(void *p, void *address) { p = p; MyFree(address); }
25static ISzAlloc g_Alloc = { SzAlloc, SzFree };
26 
27#define XzBlock_ClearFlags(p)       (p)->flags = 0;
28#define XzBlock_SetNumFilters(p, n) (p)->flags |= ((n) - 1);
29#define XzBlock_SetHasPackSize(p)   (p)->flags |= XZ_BF_PACK_SIZE;
30#define XzBlock_SetHasUnpackSize(p) (p)->flags |= XZ_BF_UNPACK_SIZE;
31 
32static SRes WriteBytes(ISeqOutStream *s, const void *buf, UInt32 size)
33{
34  return (s->Write(s, buf, size) == size) ? SZ_OK : SZ_ERROR_WRITE;
35}
36 
37static SRes WriteBytesAndCrc(ISeqOutStream *s, const void *buf, UInt32 size, UInt32 *crc)
38{
39  *crc = CrcUpdate(*crc, buf, size);
40  return WriteBytes(s, buf, size);
41}
42 
43SRes Xz_WriteHeader(CXzStreamFlags f, ISeqOutStream *s)
44{
45  UInt32 crc;
46  Byte header[XZ_STREAM_HEADER_SIZE];
47  memcpy(header, XZ_SIG, XZ_SIG_SIZE);
48  header[XZ_SIG_SIZE] = (Byte)(f >> 8);
49  header[XZ_SIG_SIZE + 1] = (Byte)(f & 0xFF);
50  crc = CrcCalc(header + XZ_SIG_SIZE, XZ_STREAM_FLAGS_SIZE);
51  SetUi32(header + XZ_SIG_SIZE + XZ_STREAM_FLAGS_SIZE, crc);
52  return WriteBytes(s, header, XZ_STREAM_HEADER_SIZE);
53}
54 
55SRes XzBlock_WriteHeader(const CXzBlock *p, ISeqOutStream *s)
56{
57  Byte header[XZ_BLOCK_HEADER_SIZE_MAX];
58 
59  unsigned pos = 1;
60  int numFilters, i;
61  header[pos++] = p->flags;
62 
63  if (XzBlock_HasPackSize(p)) pos += Xz_WriteVarInt(header + pos, p->packSize);
64  if (XzBlock_HasUnpackSize(p)) pos += Xz_WriteVarInt(header + pos, p->unpackSize);
65  numFilters = XzBlock_GetNumFilters(p);
66  for (i = 0; i < numFilters; i++)
67  {
68    const CXzFilter *f = &p->filters[i];
69    pos += Xz_WriteVarInt(header + pos, f->id);
70    pos += Xz_WriteVarInt(header + pos, f->propsSize);
71    memcpy(header + pos, f->props, f->propsSize);
72    pos += f->propsSize;
73  }
74  while((pos & 3) != 0)
75    header[pos++] = 0;
76  header[0] = (Byte)(pos >> 2);
77  SetUi32(header + pos, CrcCalc(header, pos));
78  return WriteBytes(s, header, pos + 4);
79}
80 
81SRes Xz_WriteFooter(CXzStream *p, ISeqOutStream *s)
82{
83  Byte buf[32];
84  UInt64 globalPos;
85  {
86    UInt32 crc = CRC_INIT_VAL;
87    unsigned pos = 1 + Xz_WriteVarInt(buf + 1, p->numBlocks);
88    size_t i;
89 
90    globalPos = pos;
91    buf[0] = 0;
92    RINOK(WriteBytesAndCrc(s, buf, pos, &crc));
93    for (i = 0; i < p->numBlocks; i++)
94    {
95      const CXzBlockSizes *block = &p->blocks[i];
96      pos = Xz_WriteVarInt(buf, block->totalSize);
97      pos += Xz_WriteVarInt(buf + pos, block->unpackSize);
98      globalPos += pos;
99      RINOK(WriteBytesAndCrc(s, buf, pos, &crc));
100    }
101    pos = ((unsigned)globalPos & 3);
102    if (pos != 0)
103    {
104      buf[0] = buf[1] = buf[2] = 0;
105      RINOK(WriteBytesAndCrc(s, buf, 4 - pos, &crc));
106      globalPos += 4 - pos;
107    }
108    {
109      SetUi32(buf, CRC_GET_DIGEST(crc));
110      RINOK(WriteBytes(s, buf, 4));
111      globalPos += 4;
112    }
113  }
114 
115  {
116    UInt32 indexSize = (UInt32)((globalPos >> 2) - 1);
117    SetUi32(buf + 4, indexSize);
118    buf[8] = (Byte)(p->flags >> 8);
119    buf[9] = (Byte)(p->flags & 0xFF);
120    SetUi32(buf, CrcCalc(buf + 4, 6));
121    memcpy(buf + 10, XZ_FOOTER_SIG, XZ_FOOTER_SIG_SIZE);
122    return WriteBytes(s, buf, 12);
123  }
124}
125 
126SRes Xz_AddIndexRecord(CXzStream *p, UInt64 unpackSize, UInt64 totalSize, ISzAlloc *alloc)
127{
128  if (p->blocks == 0 || p->numBlocksAllocated == p->numBlocks)
129  {
130    size_t num = (p->numBlocks + 1) * 2;
131    size_t newSize = sizeof(CXzBlockSizes) * num;
132    CXzBlockSizes *blocks;
133    if (newSize / sizeof(CXzBlockSizes) != num)
134      return SZ_ERROR_MEM;
135    blocks = alloc->Alloc(alloc, newSize);
136    if (blocks == 0)
137      return SZ_ERROR_MEM;
138    if (p->numBlocks != 0)
139    {
140      memcpy(blocks, p->blocks, p->numBlocks * sizeof(CXzBlockSizes));
141      Xz_Free(p, alloc);
142    }
143    p->blocks = blocks;
144    p->numBlocksAllocated = num;
145  }
146  {
147    CXzBlockSizes *block = &p->blocks[p->numBlocks++];
148    block->totalSize = totalSize;
149    block->unpackSize = unpackSize;
150  }
151  return SZ_OK;
152}
153 
154/* ---------- CSeqCheckInStream ---------- */
155 
156typedef struct
157{
158  ISeqInStream p;
159  ISeqInStream *realStream;
160  UInt64 processed;
161  CXzCheck check;
162} CSeqCheckInStream;
163 
164void SeqCheckInStream_Init(CSeqCheckInStream *p, int mode)
165{
166  p->processed = 0;
167  XzCheck_Init(&p->check, mode);
168}
169 
170void SeqCheckInStream_GetDigest(CSeqCheckInStream *p, Byte *digest)
171{
172  XzCheck_Final(&p->check, digest);
173}
174 
175static SRes SeqCheckInStream_Read(void *pp, void *data, size_t *size)
176{
177  CSeqCheckInStream *p = (CSeqCheckInStream *)pp;
178  SRes res = p->realStream->Read(p->realStream, data, size);
179  XzCheck_Update(&p->check, data, *size);
180  p->processed += *size;
181  return res;
182}
183 
184/* ---------- CSeqSizeOutStream ---------- */
185 
186typedef struct
187{
188  ISeqOutStream p;
189  ISeqOutStream *realStream;
190  UInt64 processed;
191} CSeqSizeOutStream;
192 
193static size_t MyWrite(void *pp, const void *data, size_t size)
194{
195  CSeqSizeOutStream *p = (CSeqSizeOutStream *)pp;
196  size = p->realStream->Write(p->realStream, data, size);
197  p->processed += size;
198  return size;
199}
200 
201/* ---------- CSeqInFilter ---------- */
202 
203#define FILTER_BUF_SIZE (1 << 20)
204 
205typedef struct
206{
207  ISeqInStream p;
208  ISeqInStream *realStream;
209  IStateCoder StateCoder;
210  Byte *buf;
211  size_t curPos;
212  size_t endPos;
213  int srcWasFinished;
214} CSeqInFilter;
215 
216static SRes SeqInFilter_Read(void *pp, void *data, size_t *size)
217{
218  CSeqInFilter *p = (CSeqInFilter *)pp;
219  size_t sizeOriginal = *size;
220  if (sizeOriginal == 0)
221    return S_OK;
222  *size = 0;
223  for (;;)
224  {
225    if (!p->srcWasFinished && p->curPos == p->endPos)
226    {
227      p->curPos = 0;
228      p->endPos = FILTER_BUF_SIZE;
229      RINOK(p->realStream->Read(p->realStream, p->buf, &p->endPos));
230      if (p->endPos == 0)
231        p->srcWasFinished = 1;
232    }
233    {
234      SizeT srcLen = p->endPos - p->curPos;
235      int wasFinished;
236      SRes res;
237      *size = sizeOriginal;
238      res = p->StateCoder.Code(p->StateCoder.p, data, size, p->buf + p->curPos, &srcLen,
239        p->srcWasFinished, CODER_FINISH_ANY, &wasFinished);
240      p->curPos += srcLen;
241      if (*size != 0 || srcLen == 0 || res != 0)
242        return res;
243    }
244  }
245}
246 
247static void SeqInFilter_Construct(CSeqInFilter *p)
248{
249  p->buf = NULL;
250  p->p.Read = SeqInFilter_Read;
251}
252 
253static void SeqInFilter_Free(CSeqInFilter *p)
254{
255  if (p->buf)
256  {
257    g_Alloc.Free(&g_Alloc, p->buf);
258    p->buf = NULL;
259  }
260}
261 
262SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, int encodeMode, ISzAlloc *alloc);
263 
264static SRes SeqInFilter_Init(CSeqInFilter *p, const CXzFilter *props)
265{
266  if (!p->buf)
267  {
268    p->buf = g_Alloc.Alloc(&g_Alloc, FILTER_BUF_SIZE);
269    if (!p->buf)
270      return SZ_ERROR_MEM;
271  }
272  p->curPos = p->endPos = 0;
273  p->srcWasFinished = 0;
274  RINOK(BraState_SetFromMethod(&p->StateCoder, props->id, 1, &g_Alloc));
275  RINOK(p->StateCoder.SetProps(p->StateCoder.p, props->props, props->propsSize, &g_Alloc));
276  p->StateCoder.Init(p->StateCoder.p);
277  return S_OK;
278}
279 
280/* ---------- CSbEncInStream ---------- */
281 
282#ifdef USE_SUBBLOCK
283 
284typedef struct
285{
286  ISeqInStream p;
287  ISeqInStream *inStream;
288  CSbEnc enc;
289} CSbEncInStream;
290 
291static SRes SbEncInStream_Read(void *pp, void *data, size_t *size)
292{
293  CSbEncInStream *p = (CSbEncInStream *)pp;
294  size_t sizeOriginal = *size;
295  if (sizeOriginal == 0)
296    return S_OK;
297  for (;;)
298  {
299    if (p->enc.needRead && !p->enc.readWasFinished)
300    {
301      size_t processed = p->enc.needReadSizeMax;
302      RINOK(p->inStream->Read(p->inStream, p->enc.buf + p->enc.readPos, &processed));
303      p->enc.readPos += processed;
304      if (processed == 0)
305      {
306        p->enc.readWasFinished = True;
307        p->enc.isFinalFinished = True;
308      }
309      p->enc.needRead = False;
310    }
311    *size = sizeOriginal;
312    RINOK(SbEnc_Read(&p->enc, data, size));
313    if (*size != 0 || !p->enc.needRead)
314      return S_OK;
315  }
316}
317 
318void SbEncInStream_Construct(CSbEncInStream *p, ISzAlloc *alloc)
319{
320  SbEnc_Construct(&p->enc, alloc);
321  p->p.Read = SbEncInStream_Read;
322}
323 
324SRes SbEncInStream_Init(CSbEncInStream *p)
325{
326  return SbEnc_Init(&p->enc);
327}
328 
329void SbEncInStream_Free(CSbEncInStream *p)
330{
331  SbEnc_Free(&p->enc);
332}
333 
334#endif
335 
336 
337typedef struct
338{
339  CLzma2EncHandle lzma2;
340  #ifdef USE_SUBBLOCK
341  CSbEncInStream sb;
342  #endif
343  CSeqInFilter filter;
344  ISzAlloc *alloc;
345  ISzAlloc *bigAlloc;
346} CLzma2WithFilters;
347 
348 
349static void Lzma2WithFilters_Construct(CLzma2WithFilters *p, ISzAlloc *alloc, ISzAlloc *bigAlloc)
350{
351  p->alloc = alloc;
352  p->bigAlloc = bigAlloc;
353  p->lzma2 = NULL;
354  #ifdef USE_SUBBLOCK
355  SbEncInStream_Construct(&p->sb, alloc);
356  #endif
357  SeqInFilter_Construct(&p->filter);
358}
359 
360static SRes Lzma2WithFilters_Create(CLzma2WithFilters *p)
361{
362  p->lzma2 = Lzma2Enc_Create(p->alloc, p->bigAlloc);
363  if (p->lzma2 == 0)
364    return SZ_ERROR_MEM;
365  return SZ_OK;
366}
367 
368static void Lzma2WithFilters_Free(CLzma2WithFilters *p)
369{
370  SeqInFilter_Free(&p->filter);
371  #ifdef USE_SUBBLOCK
372  SbEncInStream_Free(&p->sb);
373  #endif
374  if (p->lzma2)
375  {
376    Lzma2Enc_Destroy(p->lzma2);
377    p->lzma2 = NULL;
378  }
379}
380 
381void XzProps_Init(CXzProps *p)
382{
383  p->lzma2Props = 0;
384  p->filterProps = 0;
385  p->checkId = XZ_CHECK_CRC32;
386}
387 
388void XzFilterProps_Init(CXzFilterProps *p)
389{
390  p->id = 0;
391  p->delta = 0;
392  p->ip= 0;
393  p->ipDefined = False;
394}
395 
396static SRes Xz_Compress(CXzStream *xz, CLzma2WithFilters *lzmaf,
397    ISeqOutStream *outStream, ISeqInStream *inStream,
398    const CXzProps *props, ICompressProgress *progress)
399{
400  xz->flags = (Byte)props->checkId;
401 
402  RINOK(Lzma2Enc_SetProps(lzmaf->lzma2, props->lzma2Props));
403  RINOK(Xz_WriteHeader(xz->flags, outStream));
404 
405  {
406    CSeqCheckInStream checkInStream;
407    CSeqSizeOutStream seqSizeOutStream;
408    CXzBlock block;
409    int filterIndex = 0;
410    CXzFilter *filter = NULL;
411    const CXzFilterProps *fp = props->filterProps;
412     
413    XzBlock_ClearFlags(&block);
414    XzBlock_SetNumFilters(&block, 1 + (fp ? 1 : 0));
415     
416    if (fp)
417    {
418      filter = &block.filters[filterIndex++];
419      filter->id = fp->id;
420      filter->propsSize = 0;
421      if (fp->id == XZ_ID_Delta)
422      {
423        filter->props[0] = (Byte)(fp->delta - 1);
424        filter->propsSize = 1;
425      }
426      else if (fp->ipDefined)
427      {
428        SetUi32(filter->props, fp->ip);
429        filter->propsSize = 4;
430      }
431    }
432 
433    {
434      CXzFilter *f = &block.filters[filterIndex++];
435      f->id = XZ_ID_LZMA2;
436      f->propsSize = 1;
437      f->props[0] = Lzma2Enc_WriteProperties(lzmaf->lzma2);
438    }
439 
440    seqSizeOutStream.p.Write = MyWrite;
441    seqSizeOutStream.realStream = outStream;
442    seqSizeOutStream.processed = 0;
443     
444    RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.p));
445     
446    checkInStream.p.Read = SeqCheckInStream_Read;
447    checkInStream.realStream = inStream;
448    SeqCheckInStream_Init(&checkInStream, XzFlags_GetCheckType(xz->flags));
449     
450    if (fp)
451    {
452      #ifdef USE_SUBBLOCK
453      if (fp->id == XZ_ID_Subblock)
454      {
455        lzmaf->sb.inStream = &checkInStream.p;
456        RINOK(SbEncInStream_Init(&lzmaf->sb));
457      }
458      else
459      #endif
460      {
461        lzmaf->filter.realStream = &checkInStream.p;
462        RINOK(SeqInFilter_Init(&lzmaf->filter, filter));
463      }
464    }
465 
466    {
467      UInt64 packPos = seqSizeOutStream.processed;
468      SRes res = Lzma2Enc_Encode(lzmaf->lzma2, &seqSizeOutStream.p,
469        fp ?
470        #ifdef USE_SUBBLOCK
471        (fp->id == XZ_ID_Subblock) ? &lzmaf->sb.p:
472        #endif
473        &lzmaf->filter.p:
474        &checkInStream.p,
475        progress);
476      RINOK(res);
477      block.unpackSize = checkInStream.processed;
478      block.packSize = seqSizeOutStream.processed - packPos;
479    }
480 
481    {
482      unsigned padSize = 0;
483      Byte buf[128];
484      while((((unsigned)block.packSize + padSize) & 3) != 0)
485        buf[padSize++] = 0;
486      SeqCheckInStream_GetDigest(&checkInStream, buf + padSize);
487      RINOK(WriteBytes(&seqSizeOutStream.p, buf, padSize + XzFlags_GetCheckSize(xz->flags)));
488      RINOK(Xz_AddIndexRecord(xz, block.unpackSize, seqSizeOutStream.processed - padSize, &g_Alloc));
489    }
490  }
491  return Xz_WriteFooter(xz, outStream);
492}
493 
494SRes Xz_Encode(ISeqOutStream *outStream, ISeqInStream *inStream,
495    const CXzProps *props, ICompressProgress *progress)
496{
497  SRes res;
498  CXzStream xz;
499  CLzma2WithFilters lzmaf;
500  Xz_Construct(&xz);
501  Lzma2WithFilters_Construct(&lzmaf, &g_Alloc, &g_BigAlloc);
502  res = Lzma2WithFilters_Create(&lzmaf);
503  if (res == SZ_OK)
504    res = Xz_Compress(&xz, &lzmaf, outStream, inStream, props, progress);
505  Lzma2WithFilters_Free(&lzmaf);
506  Xz_Free(&xz, &g_Alloc);
507  return res;
508}
509 
510SRes Xz_EncodeEmpty(ISeqOutStream *outStream)
511{
512  SRes res;
513  CXzStream xz;
514  Xz_Construct(&xz);
515  res = Xz_WriteHeader(xz.flags, outStream);
516  if (res == SZ_OK)
517    res = Xz_WriteFooter(&xz, outStream);
518  Xz_Free(&xz, &g_Alloc);
519  return res;
520}
src/lib/lib7z/LzmaLib.c
r0r14440
1/* LzmaLib.c -- LZMA library wrapper
22008-08-05
3Igor Pavlov
4Public domain */
5 
6#include "LzmaEnc.h"
7#include "LzmaDec.h"
8#include "Alloc.h"
9#include "LzmaLib.h"
10 
11static void *SzAlloc(void *p, size_t size) { p = p; return MyAlloc(size); }
12static void SzFree(void *p, void *address) { p = p; MyFree(address); }
13static ISzAlloc g_Alloc = { SzAlloc, SzFree };
14 
15MY_STDAPI LzmaCompress(unsigned char *dest, size_t  *destLen, const unsigned char *src, size_t  srcLen,
16  unsigned char *outProps, size_t *outPropsSize,
17  int level, /* 0 <= level <= 9, default = 5 */
18  unsigned dictSize, /* use (1 << N) or (3 << N). 4 KB < dictSize <= 128 MB */
19  int lc, /* 0 <= lc <= 8, default = 3  */
20  int lp, /* 0 <= lp <= 4, default = 0  */
21  int pb, /* 0 <= pb <= 4, default = 2  */
22  int fb,  /* 5 <= fb <= 273, default = 32 */
23  int numThreads /* 1 or 2, default = 2 */
24)
25{
26  CLzmaEncProps props;
27  LzmaEncProps_Init(&props);
28  props.level = level;
29  props.dictSize = dictSize;
30  props.lc = lc;
31  props.lp = lp;
32  props.pb = pb;
33  props.fb = fb;
34  props.numThreads = numThreads;
35 
36  return LzmaEncode(dest, destLen, src, srcLen, &props, outProps, outPropsSize, 0,
37      NULL, &g_Alloc, &g_Alloc);
38}
39 
40 
41MY_STDAPI LzmaUncompress(unsigned char *dest, size_t  *destLen, const unsigned char *src, size_t  *srcLen,
42  const unsigned char *props, size_t propsSize)
43{
44  ELzmaStatus status;
45  return LzmaDecode(dest, destLen, src, srcLen, props, (unsigned)propsSize, LZMA_FINISH_ANY, &status, &g_Alloc);
46}
src/lib/lib7z/CpuArch.h
r0r14440
1/* CpuArch.h -- CPU specific code
22010-12-01: Igor Pavlov : Public domain */
3 
4#ifndef __CPU_ARCH_H
5#define __CPU_ARCH_H
6 
7#include "Types.h"
8 
9EXTERN_C_BEGIN
10 
11/*
12MY_CPU_LE means that CPU is LITTLE ENDIAN.
13If MY_CPU_LE is not defined, we don't know about that property of platform (it can be LITTLE ENDIAN).
14 
15MY_CPU_LE_UNALIGN means that CPU is LITTLE ENDIAN and CPU supports unaligned memory accesses.
16If MY_CPU_LE_UNALIGN is not defined, we don't know about these properties of platform.
17*/
18 
19#if defined(_M_X64) || defined(_M_AMD64) || defined(__x86_64__)
20#define MY_CPU_AMD64
21#endif
22 
23#if defined(MY_CPU_AMD64) || defined(_M_IA64)
24#define MY_CPU_64BIT
25#endif
26 
27#if defined(_M_IX86) || defined(__i386__)
28#define MY_CPU_X86
29#endif
30 
31#if defined(MY_CPU_X86) || defined(MY_CPU_AMD64)
32#define MY_CPU_X86_OR_AMD64
33#endif
34 
35#if defined(MY_CPU_X86) || defined(_M_ARM)
36#define MY_CPU_32BIT
37#endif
38 
39#if defined(_WIN32_7Z) && defined(_M_ARM)
40#define MY_CPU_ARM_LE
41#endif
42 
43#if defined(_WIN32_7Z) && defined(_M_IA64)
44#define MY_CPU_IA64_LE
45#endif
46 
47#if defined(MY_CPU_X86_OR_AMD64)
48#define MY_CPU_LE_UNALIGN
49#endif
50 
51#if defined(MY_CPU_X86_OR_AMD64) || defined(MY_CPU_ARM_LE)  || defined(MY_CPU_IA64_LE) || defined(__ARMEL__) || defined(__MIPSEL__) || defined(__LITTLE_ENDIAN__)
52#define MY_CPU_LE
53#endif
54 
55#if defined(__BIG_ENDIAN__) || defined(__m68k__) ||  defined(__ARMEB__) || defined(__MIPSEB__)
56#define MY_CPU_BE
57#endif
58 
59#if defined(MY_CPU_LE) && defined(MY_CPU_BE)
60Stop_Compiling_Bad_Endian
61#endif
62 
63#ifdef MY_CPU_LE_UNALIGN
64 
65#define GetUi16(p) (*(const UInt16 *)(p))
66#define GetUi32(p) (*(const UInt32 *)(p))
67#define GetUi64(p) (*(const UInt64 *)(p))
68#define SetUi16(p, d) *(UInt16 *)(p) = (d);
69#define SetUi32(p, d) *(UInt32 *)(p) = (d);
70#define SetUi64(p, d) *(UInt64 *)(p) = (d);
71 
72#else
73 
74#define GetUi16(p) (((const Byte *)(p))[0] | ((UInt16)((const Byte *)(p))[1] << 8))
75 
76#define GetUi32(p) ( \
77             ((const Byte *)(p))[0]        | \
78    ((UInt32)((const Byte *)(p))[1] <<  8) | \
79    ((UInt32)((const Byte *)(p))[2] << 16) | \
80    ((UInt32)((const Byte *)(p))[3] << 24))
81 
82#define GetUi64(p) (GetUi32(p) | ((UInt64)GetUi32(((const Byte *)(p)) + 4) << 32))
83 
84#define SetUi16(p, d) { UInt32 _x_ = (d); \
85    ((Byte *)(p))[0] = (Byte)_x_; \
86    ((Byte *)(p))[1] = (Byte)(_x_ >> 8); }
87 
88#define SetUi32(p, d) { UInt32 _x_ = (d); \
89    ((Byte *)(p))[0] = (Byte)_x_; \
90    ((Byte *)(p))[1] = (Byte)(_x_ >> 8); \
91    ((Byte *)(p))[2] = (Byte)(_x_ >> 16); \
92    ((Byte *)(p))[3] = (Byte)(_x_ >> 24); }
93 
94#define SetUi64(p, d) { UInt64 _x64_ = (d); \
95    SetUi32(p, (UInt32)_x64_); \
96    SetUi32(((Byte *)(p)) + 4, (UInt32)(_x64_ >> 32)); }
97 
98#endif
99 
100#if defined(MY_CPU_LE_UNALIGN) && defined(_WIN64) && (_MSC_VER >= 1300)
101 
102#pragma intrinsic(_byteswap_ulong)
103#pragma intrinsic(_byteswap_uint64)
104#define GetBe32(p) _byteswap_ulong(*(const UInt32 *)(const Byte *)(p))
105#define GetBe64(p) _byteswap_uint64(*(const UInt64 *)(const Byte *)(p))
106 
107#else
108 
109#define GetBe32(p) ( \
110    ((UInt32)((const Byte *)(p))[0] << 24) | \
111    ((UInt32)((const Byte *)(p))[1] << 16) | \
112    ((UInt32)((const Byte *)(p))[2] <<  8) | \
113             ((const Byte *)(p))[3] )
114 
115#define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4))
116 
117#endif
118 
119#define GetBe16(p) (((UInt16)((const Byte *)(p))[0] << 8) | ((const Byte *)(p))[1])
120 
121 
122#ifdef MY_CPU_X86_OR_AMD64
123 
124typedef struct
125{
126  UInt32 maxFunc;
127  UInt32 vendor[3];
128  UInt32 ver;
129  UInt32 b;
130  UInt32 c;
131  UInt32 d;
132} Cx86cpuid;
133 
134enum
135{
136  CPU_FIRM_INTEL,
137  CPU_FIRM_AMD,
138  CPU_FIRM_VIA
139};
140 
141Bool x86cpuid_CheckAndRead(Cx86cpuid *p);
142int x86cpuid_GetFirm(const Cx86cpuid *p);
143 
144#define x86cpuid_GetFamily(p) (((p)->ver >> 8) & 0xFF00F)
145#define x86cpuid_GetModel(p) (((p)->ver >> 4) & 0xF00F)
146#define x86cpuid_GetStepping(p) ((p)->ver & 0xF)
147 
148Bool CPU_Is_InOrder(void);
149Bool CPU_Is_Aes_Supported(void);
150 
151#endif
152 
153EXTERN_C_END
154 
155#endif
src/lib/lib7z/Threads.c
r0r14440
1/* Threads.c -- multithreading library
22009-09-20 : Igor Pavlov : Public domain */
3 
4#ifndef _WIN32_7Z_WCE
5#include <process.h>
6#endif
7 
8#include "Threads.h"
9 
10static WRes GetError()
11{
12  DWORD res = GetLastError();
13  return (res) ? (WRes)(res) : 1;
14}
15 
16WRes HandleToWRes(HANDLE h) { return (h != 0) ? 0 : GetError(); }
17WRes BOOLToWRes(BOOL v) { return v ? 0 : GetError(); }
18 
19WRes HandlePtr_Close(HANDLE *p)
20{
21  if (*p != NULL)
22    if (!CloseHandle(*p))
23      return GetError();
24  *p = NULL;
25  return 0;
26}
27 
28WRes Handle_WaitObject(HANDLE h) { return (WRes)WaitForSingleObject(h, INFINITE); }
29 
30WRes Thread_Create(CThread *p, THREAD_FUNC_TYPE func, LPVOID param)
31{
32  unsigned threadId; /* Windows Me/98/95: threadId parameter may not be NULL in _beginthreadex/CreateThread functions */
33  *p =
34    #ifdef UNDER_CE
35    CreateThread(0, 0, func, param, 0, &threadId);
36    #else
37    (HANDLE)_beginthreadex(NULL, 0, func, param, 0, &threadId);
38    #endif
39    /* maybe we must use errno here, but probably GetLastError() is also OK. */
40  return HandleToWRes(*p);
41}
42 
43WRes Event_Create(CEvent *p, BOOL manualReset, int signaled)
44{
45  *p = CreateEvent(NULL, manualReset, (signaled ? TRUE : FALSE), NULL);
46  return HandleToWRes(*p);
47}
48 
49WRes Event_Set(CEvent *p) { return BOOLToWRes(SetEvent(*p)); }
50WRes Event_Reset(CEvent *p) { return BOOLToWRes(ResetEvent(*p)); }
51 
52WRes ManualResetEvent_Create(CManualResetEvent *p, int signaled) { return Event_Create(p, TRUE, signaled); }
53WRes AutoResetEvent_Create(CAutoResetEvent *p, int signaled) { return Event_Create(p, FALSE, signaled); }
54WRes ManualResetEvent_CreateNotSignaled(CManualResetEvent *p) { return ManualResetEvent_Create(p, 0); }
55WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *p) { return AutoResetEvent_Create(p, 0); }
56 
57 
58WRes Semaphore_Create(CSemaphore *p, UInt32 initCount, UInt32 maxCount)
59{
60  *p = CreateSemaphore(NULL, (LONG)initCount, (LONG)maxCount, NULL);
61  return HandleToWRes(*p);
62}
63 
64static WRes Semaphore_Release(CSemaphore *p, LONG releaseCount, LONG *previousCount)
65  { return BOOLToWRes(ReleaseSemaphore(*p, releaseCount, previousCount)); }
66WRes Semaphore_ReleaseN(CSemaphore *p, UInt32 num)
67  { return Semaphore_Release(p, (LONG)num, NULL); }
68WRes Semaphore_Release1(CSemaphore *p) { return Semaphore_ReleaseN(p, 1); }
69 
70WRes CriticalSection_Init(CCriticalSection *p)
71{
72  /* InitializeCriticalSection can raise only STATUS_NO_MEMORY exception */
73  #ifdef _MSC_VER
74  __try
75  #endif
76  {
77    InitializeCriticalSection(p);
78    /* InitializeCriticalSectionAndSpinCount(p, 0); */
79  }
80  #ifdef _MSC_VER
81  __except (EXCEPTION_EXECUTE_HANDLER) { return 1; }
82  #endif
83  return 0;
84}
src/lib/lib7z/LzFindMt.h
r0r14440
1/* LzFindMt.h -- multithreaded Match finder for LZ algorithms
22009-02-07 : Igor Pavlov : Public domain */
3 
4#ifndef __LZ_FIND_MT_H
5#define __LZ_FIND_MT_H
6 
7#include "LzFind.h"
8#include "Threads.h"
9 
10#ifdef __cplusplus
11extern "C" {
12#endif
13 
14#define kMtHashBlockSize (1 << 13)
15#define kMtHashNumBlocks (1 << 3)
16#define kMtHashNumBlocksMask (kMtHashNumBlocks - 1)
17 
18#define kMtBtBlockSize (1 << 14)
19#define kMtBtNumBlocks (1 << 6)
20#define kMtBtNumBlocksMask (kMtBtNumBlocks - 1)
21 
22typedef struct _CMtSync
23{
24  Bool wasCreated;
25  Bool needStart;
26  Bool exit;
27  Bool stopWriting;
28 
29  CThread thread;
30  CAutoResetEvent canStart;
31  CAutoResetEvent wasStarted;
32  CAutoResetEvent wasStopped;
33  CSemaphore freeSemaphore;
34  CSemaphore filledSemaphore;
35  Bool csWasInitialized;
36  Bool csWasEntered;
37  CCriticalSection cs;
38  UInt32 numProcessedBlocks;
39} CMtSync;
40 
41typedef UInt32 * (*Mf_Mix_Matches)(void *p, UInt32 matchMinPos, UInt32 *distances);
42 
43/* kMtCacheLineDummy must be >= size_of_CPU_cache_line */
44#define kMtCacheLineDummy 128
45 
46typedef void (*Mf_GetHeads)(const Byte *buffer, UInt32 pos,
47  UInt32 *hash, UInt32 hashMask, UInt32 *heads, UInt32 numHeads, const UInt32 *crc);
48 
49typedef struct _CMatchFinderMt
50{
51  /* LZ */
52  const Byte *pointerToCurPos;
53  UInt32 *btBuf;
54  UInt32 btBufPos;
55  UInt32 btBufPosLimit;
56  UInt32 lzPos;
57  UInt32 btNumAvailBytes;
58 
59  UInt32 *hash;
60  UInt32 fixedHashSize;
61  UInt32 historySize;
62  const UInt32 *crc;
63 
64  Mf_Mix_Matches MixMatchesFunc;
65   
66  /* LZ + BT */
67  CMtSync btSync;
68  Byte btDummy[kMtCacheLineDummy];
69 
70  /* BT */
71  UInt32 *hashBuf;
72  UInt32 hashBufPos;
73  UInt32 hashBufPosLimit;
74  UInt32 hashNumAvail;
75 
76  CLzRef *son;
77  UInt32 matchMaxLen;
78  UInt32 numHashBytes;
79  UInt32 pos;
80  Byte *buffer;
81  UInt32 cyclicBufferPos;
82  UInt32 cyclicBufferSize; /* it must be historySize + 1 */
83  UInt32 cutValue;
84 
85  /* BT + Hash */
86  CMtSync hashSync;
87  /* Byte hashDummy[kMtCacheLineDummy]; */
88   
89  /* Hash */
90  Mf_GetHeads GetHeadsFunc;
91  CMatchFinder *MatchFinder;
92} CMatchFinderMt;
93 
94void MatchFinderMt_Construct(CMatchFinderMt *p);
95void MatchFinderMt_Destruct(CMatchFinderMt *p, ISzAlloc *alloc);
96SRes MatchFinderMt_Create(CMatchFinderMt *p, UInt32 historySize, UInt32 keepAddBufferBefore,
97    UInt32 matchMaxLen, UInt32 keepAddBufferAfter, ISzAlloc *alloc);
98void MatchFinderMt_CreateVTable(CMatchFinderMt *p, IMatchFinder *vTable);
99void MatchFinderMt_ReleaseStream(CMatchFinderMt *p);
100 
101#ifdef __cplusplus
102}
103#endif
104 
105#endif
src/lib/lib7z/XzEnc.h
r0r14440
1/* XzEnc.h -- Xz Encode
22011-02-07 : Igor Pavlov : Public domain */
3 
4#ifndef __XZ_ENC_H
5#define __XZ_ENC_H
6 
7#include "Lzma2Enc.h"
8 
9#include "Xz.h"
10 
11EXTERN_C_BEGIN
12 
13typedef struct
14{
15  UInt32 id;
16  UInt32 delta;
17  UInt32 ip;
18  int ipDefined;
19} CXzFilterProps;
20 
21void XzFilterProps_Init(CXzFilterProps *p);
22 
23typedef struct
24{
25  const CLzma2EncProps *lzma2Props;
26  const CXzFilterProps *filterProps;
27  unsigned checkId;
28} CXzProps;
29 
30void XzProps_Init(CXzProps *p);
31 
32SRes Xz_Encode(ISeqOutStream *outStream, ISeqInStream *inStream,
33    const CXzProps *props, ICompressProgress *progress);
34 
35SRes Xz_EncodeEmpty(ISeqOutStream *outStream);
36 
37EXTERN_C_END
38 
39#endif
src/lib/lib7z/MtCoder.c
r0r14440
1/* MtCoder.c -- Multi-thread Coder
22010-09-24 : Igor Pavlov : Public domain */
3 
4#include <stdio.h>
5 
6#include "MtCoder.h"
7 
8void LoopThread_Construct(CLoopThread *p)
9{
10  Thread_Construct(&p->thread);
11  Event_Construct(&p->startEvent);
12  Event_Construct(&p->finishedEvent);
13}
14 
15void LoopThread_Close(CLoopThread *p)
16{
17  Thread_Close(&p->thread);
18  Event_Close(&p->startEvent);
19  Event_Close(&p->finishedEvent);
20}
21 
22static THREAD_FUNC_RET_TYPE THREAD_FUNC_CALL_TYPE LoopThreadFunc(void *pp)
23{
24  CLoopThread *p = (CLoopThread *)pp;
25  for (;;)
26  {
27    if (Event_Wait(&p->startEvent) != 0)
28      return SZ_ERROR_THREAD;
29    if (p->stop)
30      return 0;
31    p->res = p->func(p->param);
32    if (Event_Set(&p->finishedEvent) != 0)
33      return SZ_ERROR_THREAD;
34  }
35}
36 
37WRes LoopThread_Create(CLoopThread *p)
38{
39  p->stop = 0;
40  RINOK(AutoResetEvent_CreateNotSignaled(&p->startEvent));
41  RINOK(AutoResetEvent_CreateNotSignaled(&p->finishedEvent));
42  return Thread_Create(&p->thread, LoopThreadFunc, p);
43}
44 
45WRes LoopThread_StopAndWait(CLoopThread *p)
46{
47  p->stop = 1;
48  if (Event_Set(&p->startEvent) != 0)
49    return SZ_ERROR_THREAD;
50  return Thread_Wait(&p->thread);
51}
52 
53WRes LoopThread_StartSubThread(CLoopThread *p) { return Event_Set(&p->startEvent); }
54WRes LoopThread_WaitSubThread(CLoopThread *p) { return Event_Wait(&p->finishedEvent); }
55 
56static SRes Progress(ICompressProgress *p, UInt64 inSize, UInt64 outSize)
57{
58  return (p && p->Progress(p, inSize, outSize) != SZ_OK) ? SZ_ERROR_PROGRESS : SZ_OK;
59}
60 
61static void MtProgress_Init(CMtProgress *p, ICompressProgress *progress)
62{
63  unsigned i;
64  for (i = 0; i < NUM_MT_CODER_THREADS_MAX; i++)
65    p->inSizes[i] = p->outSizes[i] = 0;
66  p->totalInSize = p->totalOutSize = 0;
67  p->progress = progress;
68  p->res = SZ_OK;
69}
70 
71static void MtProgress_Reinit(CMtProgress *p, unsigned index)
72{
73  p->inSizes[index] = 0;
74  p->outSizes[index] = 0;
75}
76 
77#define UPDATE_PROGRESS(size, prev, total) \
78  if (size != (UInt64)(Int64)-1) { total += size - prev; prev = size; }
79 
80SRes MtProgress_Set(CMtProgress *p, unsigned index, UInt64 inSize, UInt64 outSize)
81{
82  SRes res;
83  CriticalSection_Enter(&p->cs);
84  UPDATE_PROGRESS(inSize, p->inSizes[index], p->totalInSize)
85  UPDATE_PROGRESS(outSize, p->outSizes[index], p->totalOutSize)
86  if (p->res == SZ_OK)
87    p->res = Progress(p->progress, p->totalInSize, p->totalOutSize);
88  res = p->res;
89  CriticalSection_Leave(&p->cs);
90  return res;
91}
92 
93static void MtProgress_SetError(CMtProgress *p, SRes res)
94{
95  CriticalSection_Enter(&p->cs);
96  if (p->res == SZ_OK)
97    p->res = res;
98  CriticalSection_Leave(&p->cs);
99}
100 
101static void MtCoder_SetError(CMtCoder* p, SRes res)
102{
103  CriticalSection_Enter(&p->cs);
104  if (p->res == SZ_OK)
105    p->res = res;
106  CriticalSection_Leave(&p->cs);
107}
108 
109/* ---------- MtThread ---------- */
110 
111void CMtThread_Construct(CMtThread *p, CMtCoder *mtCoder)
112{
113  p->mtCoder = mtCoder;
114  p->outBuf = 0;
115  p->inBuf = 0;
116  Event_Construct(&p->canRead);
117  Event_Construct(&p->canWrite);
118  LoopThread_Construct(&p->thread);
119}
120 
121#define RINOK_THREAD(x) { if((x) != 0) return SZ_ERROR_THREAD; }
122 
123static void CMtThread_CloseEvents(CMtThread *p)
124{
125  Event_Close(&p->canRead);
126  Event_Close(&p->canWrite);
127}
128 
129static void CMtThread_Destruct(CMtThread *p)
130{
131  CMtThread_CloseEvents(p);
132 
133  if (Thread_WasCreated(&p->thread.thread))
134  {
135    LoopThread_StopAndWait(&p->thread);
136    LoopThread_Close(&p->thread);
137  }
138 
139  if (p->mtCoder->alloc)
140    IAlloc_Free(p->mtCoder->alloc, p->outBuf);
141  p->outBuf = 0;
142 
143  if (p->mtCoder->alloc)
144    IAlloc_Free(p->mtCoder->alloc, p->inBuf);
145  p->inBuf = 0;
146}
147 
148#define MY_BUF_ALLOC(buf, size, newSize) \
149  if (buf == 0 || size != newSize) \
150  { IAlloc_Free(p->mtCoder->alloc, buf); \
151    size = newSize; buf = (Byte *)IAlloc_Alloc(p->mtCoder->alloc, size); \
152    if (buf == 0) return SZ_ERROR_MEM; }
153 
154static SRes CMtThread_Prepare(CMtThread *p)
155{
156  MY_BUF_ALLOC(p->inBuf, p->inBufSize, p->mtCoder->blockSize)
157  MY_BUF_ALLOC(p->outBuf, p->outBufSize, p->mtCoder->destBlockSize)
158 
159  p->stopReading = False;
160  p->stopWriting = False;
161  RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->canRead));
162  RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->canWrite));
163 
164  return SZ_OK;
165}
166 
167static SRes FullRead(ISeqInStream *stream, Byte *data, size_t *processedSize)
168{
169  size_t size = *processedSize;
170  *processedSize = 0;
171  while (size != 0)
172  {
173    size_t curSize = size;
174    SRes res = stream->Read(stream, data, &curSize);
175    *processedSize += curSize;
176    data += curSize;
177    size -= curSize;
178    RINOK(res);
179    if (curSize == 0)
180      return SZ_OK;
181  }
182  return SZ_OK;
183}
184 
185#define GET_NEXT_THREAD(p) &p->mtCoder->threads[p->index == p->mtCoder->numThreads  - 1 ? 0 : p->index + 1]
186 
187static SRes MtThread_Process(CMtThread *p, Bool *stop)
188{
189  CMtThread *next;
190  *stop = True;
191  if (Event_Wait(&p->canRead) != 0)
192    return SZ_ERROR_THREAD;
193   
194  next = GET_NEXT_THREAD(p);
195   
196  if (p->stopReading)
197  {
198    next->stopReading = True;
199    return Event_Set(&next->canRead) == 0 ? SZ_OK : SZ_ERROR_THREAD;
200  }
201 
202  {
203    size_t size = p->mtCoder->blockSize;
204    size_t destSize = p->outBufSize;
205 
206    RINOK(FullRead(p->mtCoder->inStream, p->inBuf, &size));
207    next->stopReading = *stop = (size != p->mtCoder->blockSize);
208    if (Event_Set(&next->canRead) != 0)
209      return SZ_ERROR_THREAD;
210 
211    RINOK(p->mtCoder->mtCallback->Code(p->mtCoder->mtCallback, p->index,
212        p->outBuf, &destSize, p->inBuf, size, *stop));
213 
214    MtProgress_Reinit(&p->mtCoder->mtProgress, p->index);
215 
216    if (Event_Wait(&p->canWrite) != 0)
217      return SZ_ERROR_THREAD;
218    if (p->stopWriting)
219      return SZ_ERROR_FAIL;
220    if (p->mtCoder->outStream->Write(p->mtCoder->outStream, p->outBuf, destSize) != destSize)
221      return SZ_ERROR_WRITE;
222    return Event_Set(&next->canWrite) == 0 ? SZ_OK : SZ_ERROR_THREAD;
223  }
224}
225 
226static THREAD_FUNC_RET_TYPE THREAD_FUNC_CALL_TYPE ThreadFunc(void *pp)
227{
228  CMtThread *p = (CMtThread *)pp;
229  for (;;)
230  {
231    Bool stop;
232    CMtThread *next = GET_NEXT_THREAD(p);
233    SRes res = MtThread_Process(p, &stop);
234    if (res != SZ_OK)
235    {
236      MtCoder_SetError(p->mtCoder, res);
237      MtProgress_SetError(&p->mtCoder->mtProgress, res);
238      next->stopReading = True;
239      next->stopWriting = True;
240      Event_Set(&next->canRead);
241      Event_Set(&next->canWrite);
242      return res;
243    }
244    if (stop)
245      return 0;
246  }
247}
248 
249void MtCoder_Construct(CMtCoder* p)
250{
251  unsigned i;
252  p->alloc = 0;
253  for (i = 0; i < NUM_MT_CODER_THREADS_MAX; i++)
254  {
255    CMtThread *t = &p->threads[i];
256    t->index = i;
257    CMtThread_Construct(t, p);
258  }
259  CriticalSection_Init(&p->cs);
260  CriticalSection_Init(&p->mtProgress.cs);
261}
262 
263void MtCoder_Destruct(CMtCoder* p)
264{
265  unsigned i;
266  for (i = 0; i < NUM_MT_CODER_THREADS_MAX; i++)
267    CMtThread_Destruct(&p->threads[i]);
268  CriticalSection_Delete(&p->cs);
269  CriticalSection_Delete(&p->mtProgress.cs);
270}
271 
272SRes MtCoder_Code(CMtCoder *p)
273{
274  unsigned i, numThreads = p->numThreads;
275  SRes res = SZ_OK;
276  p->res = SZ_OK;
277 
278  MtProgress_Init(&p->mtProgress, p->progress);
279 
280  for (i = 0; i < numThreads; i++)
281  {
282    RINOK(CMtThread_Prepare(&p->threads[i]));
283  }
284 
285  for (i = 0; i < numThreads; i++)
286  {
287    CMtThread *t = &p->threads[i];
288    CLoopThread *lt = &t->thread;
289 
290    if (!Thread_WasCreated(&lt->thread))
291    {
292      lt->func = ThreadFunc;
293      lt->param = t;
294 
295      if (LoopThread_Create(lt) != SZ_OK)
296      {
297        res = SZ_ERROR_THREAD;
298        break;
299      }
300    }
301  }
302 
303  if (res == SZ_OK)
304  {
305    unsigned j;
306    for (i = 0; i < numThreads; i++)
307    {
308      CMtThread *t = &p->threads[i];
309      if (LoopThread_StartSubThread(&t->thread) != SZ_OK)
310      {
311        res = SZ_ERROR_THREAD;
312        p->threads[0].stopReading = True;
313        break;
314      }
315    }
316 
317    Event_Set(&p->threads[0].canWrite);
318    Event_Set(&p->threads[0].canRead);
319 
320    for (j = 0; j < i; j++)
321      LoopThread_WaitSubThread(&p->threads[j].thread);
322  }
323 
324  for (i = 0; i < numThreads; i++)
325    CMtThread_CloseEvents(&p->threads[i]);
326  return (res == SZ_OK) ? p->res : res;
327}
src/lib/lib7z/7zBuf.c
r0r14440
1/* 7zBuf.c -- Byte Buffer
22008-03-28
3Igor Pavlov
4Public domain */
5 
6#include "7zBuf.h"
7 
8void Buf_Init(CBuf *p)
9{
10  p->data = 0;
11  p->size = 0;
12}
13 
14int Buf_Create(CBuf *p, size_t size, ISzAlloc *alloc)
15{
16  p->size = 0;
17  if (size == 0)
18  {
19    p->data = 0;
20    return 1;
21  }
22  p->data = (Byte *)alloc->Alloc(alloc, size);
23  if (p->data != 0)
24  {
25    p->size = size;
26    return 1;
27  }
28  return 0;
29}
30 
31void Buf_Free(CBuf *p, ISzAlloc *alloc)
32{
33  alloc->Free(alloc, p->data);
34  p->data = 0;
35  p->size = 0;
36}
src/lib/lib.mak
r14439r14440
2222   $(LIBOBJ)/libjpeg \
2323   $(LIBOBJ)/libflac \
2424   $(LIBOBJ)/libflacpp \
25   $(LIBOBJ)/lib7z \
2526
2627
2728
r14439r14440
5253   $(LIBOBJ)/util/sha1.o \
5354   $(LIBOBJ)/util/unicode.o \
5455   $(LIBOBJ)/util/unzip.o \
56   $(LIBOBJ)/util/un7z.o \
5557   $(LIBOBJ)/util/vbiparse.o \
5658   $(LIBOBJ)/util/xmlfile.o \
5759   $(LIBOBJ)/util/zippath.o \
r14439r14440
184186   $(LIBOBJ)/zlib/uncompr.o \
185187   $(LIBOBJ)/zlib/zutil.o
186188
189
190
187191$(OBJ)/libz.a: $(ZLIBOBJS)
188192
189193$(LIBOBJ)/zlib/%.o: $(LIBSRC)/zlib/%.c | $(OSPREBUILD)
r14439r14440
309313# $(LIBOBJ)/libflacpp/%.o: $(LIBSRC)/libflac/libflac++/%.cpp | $(OSPREBUILD)
310314#    @echo Compiling $<...
311315#   $(CC) $(CDEFS) $(FLACOPTS) $(CPPONLYFLAGS) -I$(LIBSRC)/libflac/include -c $< -o $@
316
317
318#-------------------------------------------------
319# lib7z library objects
320#-------------------------------------------------
321
3227ZOPTS=-D_7ZIP_PPMD_SUPPPORT
323
324LIB7ZOBJS = \
325   $(LIBOBJ)/lib7z/7zBuf.o \
326   $(LIBOBJ)/lib7z/7zBuf2.o \
327   $(LIBOBJ)/lib7z/7zCrc.o \
328   $(LIBOBJ)/lib7z/7zCrcOpt.o \
329   $(LIBOBJ)/lib7z/7zDec.o \
330   $(LIBOBJ)/lib7z/7zIn.o \
331   $(LIBOBJ)/lib7z/CpuArch.o \
332   $(LIBOBJ)/lib7z/LzmaDec.o \
333   $(LIBOBJ)/lib7z/Lzma2Dec.o \
334   $(LIBOBJ)/lib7z/Bra.o \
335   $(LIBOBJ)/lib7z/Bra86.o \
336   $(LIBOBJ)/lib7z/Bcj2.o \
337   $(LIBOBJ)/lib7z/Ppmd7.o \
338   $(LIBOBJ)/lib7z/Ppmd7Dec.o \
339   $(LIBOBJ)/lib7z/7zStream.o \
340
341$(OBJ)/lib7z.a: $(LIB7ZOBJS)
342
343$(LIBOBJ)/lib7z/%.o: $(LIBSRC)/lib7z/%.c | $(OSPREBUILD)
344   @echo Compiling $<...
345   $(CC) $(CDEFS) $(7ZOPTS) $(CONLYFLAGS) -I$(LIBSRC)/lib7z/ -c $< -o $@
346
347
348
src/lib/util/un7z.c
r0r14440
1/***************************************************************************
2 
3    un7z.c
4 
5    Functions to manipulate data within 7z files.
6 
7****************************************************************************
8 
9    Copyright Aaron Giles
10    All rights reserved.
11 
12    Redistribution and use in source and binary forms, with or without
13    modification, are permitted provided that the following conditions are
14    met:
15 
16        * Redistributions of source code must retain the above copyright
17          notice, this list of conditions and the following disclaimer.
18        * Redistributions in binary form must reproduce the above copyright
19          notice, this list of conditions and the following disclaimer in
20          the documentation and/or other materials provided with the
21          distribution.
22        * Neither the name 'MAME' nor the names of its contributors may be
23          used to endorse or promote products derived from this software
24          without specific prior written permission.
25 
26    THIS SOFTWARE IS PROVIDED BY AARON GILES ''AS IS'' AND ANY EXPRESS OR
27    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
28    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
29    DISCLAIMED. IN NO EVENT SHALL AARON GILES BE LIABLE FOR ANY DIRECT,
30    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
31    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
32    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
34    STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
35    IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36    POSSIBILITY OF SUCH DAMAGE.
37 
38***************************************************************************/
39 
40// this is based on unzip.c, with modifications needed to use the 7zip library
41 
42#include "osdcore.h"
43#include "un7z.h"
44 
45#include <ctype.h>
46#include <stdlib.h>
47#include <zlib.h>
48 
49/***************************************************************************
50    7Zip Memory / File handling (adapted from 7zfile.c/.h and 7zalloc.c/.h)
51***************************************************************************/
52 
53void *SZipAlloc(void *p, size_t size)
54{
55   p = p;
56   if (size == 0)
57      return 0;
58 
59   return malloc(size);
60}
61 
62void SZipFree(void *p, void *address)
63{
64   p = p;
65   free(address);
66}
67 
68 
69 
70void File_Construct(CSzFile *p)
71{
72   p->_7z_osdfile = NULL;
73}
74 
75static WRes File_Open(CSzFile *p, const char *name, int writeMode)
76{
77   /* we handle this ourselves ... */
78   if (!p->_7z_osdfile) return 1;
79   else return 0;
80}
81 
82WRes InFile_Open(CSzFile *p, const char *name) { return File_Open(p, name, 0); }
83WRes OutFile_Open(CSzFile *p, const char *name) { return File_Open(p, name, 1); }
84 
85 
86WRes File_Close(CSzFile *p)
87{
88   /* we handle this ourselves ... */
89   return 0;
90}
91 
92WRes File_Read(CSzFile *p, void *data, size_t *size)
93{
94//   file_error err;
95   UINT32 read_length;
96 
97   if (!p->_7z_osdfile)
98   {
99      printf("un7z.c: called File_Read without file\n");
100      return 1;
101   }
102 
103   size_t originalSize = *size;
104   if (originalSize == 0)
105      return 0;
106 
107//   err = 
108    osd_read( p->_7z_osdfile, data, p->_7z_currfpos, originalSize, &read_length );
109   *size = read_length;
110   p->_7z_currfpos += read_length;
111 
112   if (*size == originalSize)
113      return 0;
114 
115   return 0;
116}
117 
118WRes File_Write(CSzFile *p, const void *data, size_t *size)
119{
120   return 0;
121}
122 
123WRes File_Seek(CSzFile *p, Int64 *pos, ESzSeek origin)
124{
125   if (origin==0) p->_7z_currfpos = *pos;
126   if (origin==1) p->_7z_currfpos = p->_7z_currfpos + *pos;
127   if (origin==2) p->_7z_currfpos = p->_7z_length - *pos;
128 
129   *pos = p->_7z_currfpos;
130   
131   return 0;
132}
133 
134WRes File_GetLength(CSzFile *p, UInt64 *length)
135{
136   *length = p->_7z_length;
137   return 0;
138}
139 
140/* ---------- FileSeqInStream ---------- */
141 
142static SRes FileSeqInStream_Read(void *pp, void *buf, size_t *size)
143{
144  CFileSeqInStream *p = (CFileSeqInStream *)pp;
145  return File_Read(&p->file, buf, size) == 0 ? SZ_OK : SZ_ERROR_READ;
146}
147 
148void FileSeqInStream_CreateVTable(CFileSeqInStream *p)
149{
150  p->s.Read = FileSeqInStream_Read;
151}
152 
153 
154/* ---------- FileInStream ---------- */
155 
156static SRes FileInStream_Read(void *pp, void *buf, size_t *size)
157{
158   CFileInStream *p = (CFileInStream *)pp;
159   return (File_Read(&p->file, buf, size) == 0) ? SZ_OK : SZ_ERROR_READ;
160}
161 
162static SRes FileInStream_Seek(void *pp, Int64 *pos, ESzSeek origin)
163{
164   CFileInStream *p = (CFileInStream *)pp;
165   return File_Seek(&p->file, pos, origin);
166}
167 
168void FileInStream_CreateVTable(CFileInStream *p)
169{
170   p->s.Read = FileInStream_Read;
171   p->s.Seek = FileInStream_Seek;
172}
173 
174/* ---------- FileOutStream ---------- */
175 
176static size_t FileOutStream_Write(void *pp, const void *data, size_t size)
177{
178  CFileOutStream *p = (CFileOutStream *)pp;
179  File_Write(&p->file, data, &size);
180  return size;
181}
182 
183void FileOutStream_CreateVTable(CFileOutStream *p)
184{
185  p->s.Write = FileOutStream_Write;
186}
187 
188/***************************************************************************
189    CONSTANTS
190***************************************************************************/
191 
192/* number of open files to cache */
193#define _7Z_CACHE_SIZE   8
194 
195 
196/***************************************************************************
197    GLOBAL VARIABLES
198***************************************************************************/
199 
200static _7z_file *_7z_cache[_7Z_CACHE_SIZE];
201 
202/***************************************************************************
203    FUNCTION PROTOTYPES
204***************************************************************************/
205 
206/* cache management */
207static void free__7z_file(_7z_file *_7z);
208 
209 
210/***************************************************************************
211    _7Z FILE ACCESS
212***************************************************************************/
213 
214/*-------------------------------------------------
215    _7z_file_open - opens a _7Z file for reading
216-------------------------------------------------*/
217 
218int _7z_search_crc_match(_7z_file *new_7z, UINT32 search_crc, const char* search_filename, int search_filename_length, bool matchcrc, bool matchname)
219{
220   UInt16 *temp = NULL;
221   size_t tempSize = 0;
222 
223   for (int i = 0; i < new_7z->db.db.NumFiles; i++)
224   {
225      const CSzFileItem *f = new_7z->db.db.Files + i;
226      size_t len;
227 
228      len = SzArEx_GetFileNameUtf16(&new_7z->db, i, NULL);
229 
230      // if it's a directory entry we don't care about it..
231      if (f->IsDir)
232         continue;
233 
234      if (len > tempSize)
235      {
236         SZipFree(NULL, temp);
237         tempSize = len;
238         temp = (UInt16 *)SZipAlloc(NULL, tempSize * sizeof(temp[0]));
239         if (temp == 0)
240         {
241            return -1; // memory error
242         }
243      }
244 
245      bool crcmatch = false;
246      bool namematch = false;
247 
248      UINT64 size = f->Size;
249      UINT32 crc = f->Crc;
250 
251      /* Check for a name match */
252      SzArEx_GetFileNameUtf16(&new_7z->db, i, temp);
253 
254      if (len == search_filename_length+1)
255      {
256         int j;
257         for (j=0;j<search_filename_length;j++)
258         {
259            UINT8 sn = search_filename[j];
260            UINT16 zn = temp[j]; // these are utf16
261 
262            // MAME filenames are always lowercase so be case insensitive
263            if ((zn>=0x41) && (zn<=0x5a)) zn+=0x20;
264 
265            if (sn != zn) break;
266         }       
267         if (j==search_filename_length) namematch = true;
268      }
269 
270       
271      /* Check for a CRC match */
272      if (crc==search_crc) crcmatch = true;
273 
274      bool found = false;
275 
276      if (matchcrc && matchname)
277      {
278         if (crcmatch && namematch)
279            found = true;
280      }
281      else if (matchcrc)
282      {
283         if (crcmatch)
284            found = true;
285      }
286      else if (matchname)
287      {
288         if (namematch)
289            found = true;
290      }
291 
292      if (found) 
293      {
294      //   printf("found %S %d %08x %08x %08x %s %d\n", temp, len, crc, search_crc, size, search_filename, search_filename_length);
295         new_7z->curr_file_idx = i;
296         new_7z->uncompressed_length = size;
297         new_7z->crc = crc;
298 
299         SZipFree(NULL, temp);
300         return i;
301      }
302   }
303 
304   SZipFree(NULL, temp);
305   return -1;
306}
307 
308 
309_7z_error _7z_file_open(const char *filename, _7z_file **_7z)
310{
311   file_error err;
312   _7z_error _7zerr = _7ZERR_NONE;
313 
314 
315   _7z_file *new_7z;
316   char *string;
317   int cachenum;
318 
319   SRes res;
320 
321   /* ensure we start with a NULL result */
322   *_7z = NULL;
323 
324   /* see if we are in the cache, and reopen if so */
325   for (cachenum = 0; cachenum < ARRAY_LENGTH(_7z_cache); cachenum++)
326   {
327      _7z_file *cached = _7z_cache[cachenum];
328 
329      /* if we have a valid entry and it matches our filename, use it and remove from the cache */
330      if (cached != NULL && cached->filename != NULL && strcmp(filename, cached->filename) == 0)
331      {
332         *_7z = cached;
333         _7z_cache[cachenum] = NULL;
334         return _7ZERR_NONE;
335      }
336   }
337 
338   /* allocate memory for the _7z_file structure */
339   new_7z = (_7z_file *)malloc(sizeof(*new_7z));
340   if (new_7z == NULL)
341      return _7ZERR_OUT_OF_MEMORY;
342   memset(new_7z, 0, sizeof(*new_7z));
343 
344   new_7z->inited = false;
345   new_7z->archiveStream.file._7z_currfpos = 0;
346   err = osd_open(filename, OPEN_FLAG_READ, &new_7z->archiveStream.file._7z_osdfile, &new_7z->archiveStream.file._7z_length);
347   if (err != FILERR_NONE)
348   {
349      _7zerr = _7ZERR_FILE_ERROR;
350      goto error;
351   }
352 
353   new_7z->allocImp.Alloc = SZipAlloc;
354   new_7z->allocImp.Free = SZipFree;
355 
356   new_7z->allocTempImp.Alloc = SZipAlloc;
357   new_7z->allocTempImp.Free = SZipFree;
358 
359   if (InFile_Open(&new_7z->archiveStream.file, filename))
360   {
361      _7zerr = _7ZERR_FILE_ERROR;
362      goto error;
363   }
364 
365   FileInStream_CreateVTable(&new_7z->archiveStream);
366   LookToRead_CreateVTable(&new_7z->lookStream, False);
367   
368   new_7z->lookStream.realStream = &new_7z->archiveStream.s;
369   LookToRead_Init(&new_7z->lookStream);
370 
371   CrcGenerateTable();
372 
373   SzArEx_Init(&new_7z->db);
374   new_7z->inited = true;
375 
376   res = SzArEx_Open(&new_7z->db, &new_7z->lookStream.s, &new_7z->allocImp, &new_7z->allocTempImp);
377   if (res != SZ_OK)
378   {
379      _7zerr = _7ZERR_FILE_ERROR;
380      goto error;
381   }
382 
383   new_7z->blockIndex = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */
384   new_7z->outBuffer = 0; /* it must be 0 before first call for each new archive. */
385   new_7z->outBufferSize = 0;  /* it can have any value before first call (if outBuffer = 0) */
386 
387   /* make a copy of the filename for caching purposes */
388   string = (char *)malloc(strlen(filename) + 1);
389   if (string == NULL)
390   {
391      _7zerr = _7ZERR_OUT_OF_MEMORY;
392      goto error;
393   }
394   strcpy(string, filename);
395   new_7z->filename = string;
396   *_7z = new_7z;
397   return _7ZERR_NONE;
398 
399error:
400   free__7z_file(new_7z);
401   return _7zerr;
402}
403 
404 
405/*-------------------------------------------------
406    _7z_file_close - close a _7Z file and add it
407    to the cache
408-------------------------------------------------*/
409 
410void _7z_file_close(_7z_file *_7z)
411{
412   int cachenum;
413 
414   /* close the open files */
415   if (_7z->archiveStream.file._7z_osdfile != NULL)
416      osd_close(_7z->archiveStream.file._7z_osdfile);
417   _7z->archiveStream.file._7z_osdfile = NULL;
418 
419   /* find the first NULL entry in the cache */
420   for (cachenum = 0; cachenum < ARRAY_LENGTH(_7z_cache); cachenum++)
421      if (_7z_cache[cachenum] == NULL)
422         break;
423 
424   /* if no room left in the cache, free the bottommost entry */
425   if (cachenum == ARRAY_LENGTH(_7z_cache))
426      free__7z_file(_7z_cache[--cachenum]);
427 
428   /* move everyone else down and place us at the top */
429   if (cachenum != 0)
430      memmove(&_7z_cache[1], &_7z_cache[0], cachenum * sizeof(_7z_cache[0]));
431   _7z_cache[0] = _7z;
432}
433 
434 
435/*-------------------------------------------------
436    _7z_file_cache_clear - clear the _7Z file
437    cache and free all memory
438-------------------------------------------------*/
439 
440void _7z_file_cache_clear(void)
441{
442   int cachenum;
443 
444   /* clear call cache entries */
445   for (cachenum = 0; cachenum < ARRAY_LENGTH(_7z_cache); cachenum++)
446      if (_7z_cache[cachenum] != NULL)
447      {
448         free__7z_file(_7z_cache[cachenum]);
449         _7z_cache[cachenum] = NULL;
450      }
451}
452 
453 
454/*-------------------------------------------------
455    _7z_file_decompress - decompress a file
456    from a _7Z into the target buffer
457-------------------------------------------------*/
458 
459_7z_error _7z_file_decompress(_7z_file *new_7z, void *buffer, UINT32 length)
460{
461   file_error err;
462   SRes res;
463   int index = new_7z->curr_file_idx;
464 
465   /* make sure the file is open.. */
466   if (new_7z->archiveStream.file._7z_osdfile==NULL)
467   {
468      new_7z->archiveStream.file._7z_currfpos = 0;
469      err = osd_open(new_7z->filename, OPEN_FLAG_READ, &new_7z->archiveStream.file._7z_osdfile, &new_7z->archiveStream.file._7z_length);
470      if (err != FILERR_NONE)
471         return _7ZERR_FILE_ERROR;
472   }
473 
474   size_t offset = 0;
475   size_t outSizeProcessed = 0;
476 
477   res = SzArEx_Extract(&new_7z->db, &new_7z->lookStream.s, index,
478      &new_7z->blockIndex, &new_7z->outBuffer, &new_7z->outBufferSize,
479      &offset, &outSizeProcessed,
480      &new_7z->allocImp, &new_7z->allocTempImp);
481         
482   if (res != SZ_OK)
483      return _7ZERR_FILE_ERROR;
484 
485   memcpy(buffer, new_7z->outBuffer + offset, length);
486 
487   return _7ZERR_NONE;
488}
489 
490 
491 
492/***************************************************************************
493    CACHE MANAGEMENT
494***************************************************************************/
495 
496/*-------------------------------------------------
497    free__7z_file - free all the data for a
498    _7z_file
499-------------------------------------------------*/
500 
501static void free__7z_file(_7z_file *_7z)
502{
503   if (_7z != NULL)
504   {
505      if (_7z->archiveStream.file._7z_osdfile != NULL)
506         osd_close(_7z->archiveStream.file._7z_osdfile);
507      if (_7z->filename != NULL)
508         free((void *)_7z->filename);
509 
510 
511      if (_7z->outBuffer) IAlloc_Free(&_7z->allocImp, _7z->outBuffer);
512      if (_7z->inited) SzArEx_Free(&_7z->db, &_7z->allocImp);
513   
514 
515      free(_7z);
516   }
517}
518 
519 
src/lib/util/un7z.h
r0r14440
1/***************************************************************************
2 
3    un7z.h
4 
5    7z file management.
6 
7****************************************************************************
8 
9    Copyright Aaron Giles
10    All rights reserved.
11 
12    Redistribution and use in source and binary forms, with or without
13    modification, are permitted provided that the following conditions are
14    met:
15 
16        * Redistributions of source code must retain the above copyright
17          notice, this list of conditions and the following disclaimer.
18        * Redistributions in binary form must reproduce the above copyright
19          notice, this list of conditions and the following disclaimer in
20          the documentation and/or other materials provided with the
21          distribution.
22        * Neither the name 'MAME' nor the names of its contributors may be
23          used to endorse or promote products derived from this software
24          without specific prior written permission.
25 
26    THIS SOFTWARE IS PROVIDED BY AARON GILES ''AS IS'' AND ANY EXPRESS OR
27    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
28    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
29    DISCLAIMED. IN NO EVENT SHALL AARON GILES BE LIABLE FOR ANY DIRECT,
30    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
31    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
32    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
34    STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
35    IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36    POSSIBILITY OF SUCH DAMAGE.
37 
38***************************************************************************/
39 
40// this is based on unzip.h, with modifications needed to use the 7zip library
41 
42#pragma once
43 
44#ifndef __UN_7Z_H__
45#define __UN_7Z_H__
46 
47#include "osdcore.h"
48 
49#include "../lib7z/7z.h"
50#include "../lib7z/7zCrc.h"
51#include "../lib7z/7zVersion.h"
52 
53 
54void *SZipAlloc(void *p, size_t size);
55void SZipFree(void *p, void *address);
56void *SZipAllocTemp(void *p, size_t size);
57void SZipFreeTemp(void *p, void *address);
58 
59typedef struct
60{
61   long _7z_currfpos;
62   UINT64         _7z_length;
63   osd_file *      _7z_osdfile;               /* OSD file handle */
64 
65} CSzFile;
66 
67 
68typedef struct
69{
70   ISeqInStream s;
71   CSzFile file;
72} CFileSeqInStream;
73 
74void FileSeqInStream_CreateVTable(CFileSeqInStream *p);
75 
76 
77typedef struct
78{
79   ISeekInStream s;
80   CSzFile file;
81} CFileInStream;
82 
83void FileInStream_CreateVTable(CFileInStream *p);
84 
85 
86typedef struct
87{
88   ISeqOutStream s;
89   CSzFile file;
90} CFileOutStream;
91 
92void FileOutStream_CreateVTable(CFileOutStream *p);
93 
94 
95 
96/***************************************************************************
97    CONSTANTS
98***************************************************************************/
99 
100 
101/* Error types */
102enum __7z_error
103{
104   _7ZERR_NONE = 0,
105   _7ZERR_OUT_OF_MEMORY,
106   _7ZERR_FILE_ERROR,
107   _7ZERR_BAD_SIGNATURE,
108   _7ZERR_DECOMPRESS_ERROR,
109   _7ZERR_FILE_TRUNCATED,
110   _7ZERR_FILE_CORRUPT,
111   _7ZERR_UNSUPPORTED,
112   _7ZERR_BUFFER_TOO_SMALL
113};
114typedef enum __7z_error _7z_error;
115 
116 
117 
118/***************************************************************************
119    TYPE DEFINITIONS
120***************************************************************************/
121 
122/* describes an open _7Z file */
123typedef struct __7z_file _7z_file;
124struct __7z_file
125{
126   const char *   filename;            /* copy of _7Z filename (for caching) */
127 
128   int   curr_file_idx;                  /* current file index */
129   UINT64 uncompressed_length;            /* current file uncompressed length */
130   UINT64 crc;                        /* current file crc */
131 
132   CFileInStream archiveStream;
133   CLookToRead lookStream;
134   CSzArEx db;
135   SRes res;
136   ISzAlloc allocImp;
137   ISzAlloc allocTempImp;
138   bool inited;
139 
140   // cached stuff for solid blocks
141   UInt32 blockIndex;// = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */
142   Byte *outBuffer;// = 0; /* it must be 0 before first call for each new archive. */
143   size_t outBufferSize;// = 0;  /* it can have any value before first call (if outBuffer = 0) */
144};
145 
146 
147 
148/***************************************************************************
149    FUNCTION PROTOTYPES
150***************************************************************************/
151 
152 
153/* ----- _7Z file access ----- */
154 
155/* open a _7Z file and parse its central directory */
156_7z_error _7z_file_open(const char *filename, _7z_file **_7z);
157 
158/* close a _7Z file (may actually be left open due to caching) */
159void _7z_file_close(_7z_file *_7z);
160 
161/* clear out all open _7Z files from the cache */
162void _7z_file_cache_clear(void);
163 
164 
165/* ----- contained file access ----- */
166 
167/* find a file index by crc, filename or both */
168int _7z_search_crc_match(_7z_file *new_7z, UINT32 crc, const char *search_filename, int search_filename_length, bool matchcrc, bool matchname);
169 
170/* decompress the most recently found file in the _7Z */
171_7z_error _7z_file_decompress(_7z_file *_7z, void *buffer, UINT32 length);
172 
173 
174#endif   /* __UN_7Z_H__ */
makefile
r14439r14440
643643# $(OBJ)/libflac++.a
644644
645645
6467Z_LIB = $(OBJ)/lib7z.a
647
646648#-------------------------------------------------
647649# defines needed by multiple make files
648650#-------------------------------------------------
r14439r14440
732734ifndef EXECUTABLE_DEFINED
733735
734736# always recompile the version string
735$(VERSIONOBJ): $(DRVLIBS) $(LIBOSD) $(LIBCPU) $(LIBEMU) $(LIBSOUND) $(LIBUTIL) $(EXPAT) $(ZLIB) $(SOFTFLOAT) $(FORMATS_LIB) $(LIBOCORE) $(RESFILE)
737$(VERSIONOBJ): $(DRVLIBS) $(LIBOSD) $(LIBCPU) $(LIBEMU) $(LIBSOUND) $(LIBUTIL) $(EXPAT) $(ZLIB) $(7Z_LIB) $(SOFTFLOAT) $(FORMATS_LIB) $(LIBOCORE) $(RESFILE)
736738
737$(EMULATOR): $(VERSIONOBJ) $(EMUINFOOBJ) $(DRIVLISTOBJ) $(DEVLISTOBJ) $(DRVLIBS) $(LIBOSD) $(LIBCPU) $(LIBEMU) $(LIBDASM) $(LIBSOUND) $(LIBUTIL) $(EXPAT) $(SOFTFLOAT) $(JPEG_LIB) $(FLAC_LIB) $(FORMATS_LIB) $(ZLIB) $(LIBOCORE) $(RESFILE)
739$(EMULATOR): $(VERSIONOBJ) $(EMUINFOOBJ) $(DRIVLISTOBJ) $(DEVLISTOBJ) $(DRVLIBS) $(LIBOSD) $(LIBCPU) $(LIBEMU) $(LIBDASM) $(LIBSOUND) $(LIBUTIL) $(EXPAT) $(SOFTFLOAT) $(JPEG_LIB) $(FLAC_LIB) $(7Z_LIB) $(FORMATS_LIB) $(ZLIB) $(LIBOCORE) $(RESFILE)
738740   @echo Linking $@...
739741   $(LD) $(LDFLAGS) $(LDFLAGSEMULATOR) $^ $(LIBS) -o $@
740742ifeq ($(TARGETOS),win32)

Previous 15994 Revisions Next


© 1998-2018 The MESS Team