Debian Codegraph @

third_party/rust/flate2/src/ffi/c.rs

raw
1 //! Implementation for C backends.
2 use std::cmp;
3 use std::fmt;
4 use std::marker;
5 use std::os::raw::{c_int, c_uint};
6 use std::ptr;
7
8 use super::*;
9 use crate::mem;
10
11 #[derive(Default)]
12 pub struct ErrorMessage(Option<&'static str>);
13
14 impl ErrorMessage {
15 pub fn get(&self) -> Option<&str> {
16 self.0
17 }
18 }
19
20 pub struct StreamWrapper {
21 // SAFETY: The field `inner` must always be accessed as a raw pointer,
22 // since it points to a cyclic structure, and it must never be copied
23 // by Rust.
24 pub inner: *mut mz_stream,
25 }
26
27 impl fmt::Debug for StreamWrapper {
28 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
29 write!(f, "StreamWrapper")
30 }
31 }
32
33 impl Default for StreamWrapper {
34 fn default() -> StreamWrapper {
35 // SAFETY: The field `state` will be initialized across the FFI to
36 // point to the opaque type `mz_internal_state`, which will contain a copy
37 // of `inner`. This cyclic structure breaks the uniqueness invariant of
38 // &mut mz_stream, so we must use a raw pointer instead of Box<mz_stream>.
39 StreamWrapper {
40 inner: Box::into_raw(Box::new(mz_stream {
41 next_in: ptr::null_mut(),
42 avail_in: 0,
43 total_in: 0,
44 next_out: ptr::null_mut(),
45 avail_out: 0,
46 total_out: 0,
47 msg: ptr::null_mut(),
48 adler: 0,
49 data_type: 0,
50 reserved: 0,
51 opaque: ptr::null_mut(),
52 state: ptr::null_mut(),
53 #[cfg(all(
54 feature = "any_zlib",
55 not(any(feature = "cloudflare-zlib-sys", feature = "libz-rs-sys"))
56 ))]
57 zalloc: allocator::zalloc,
58 #[cfg(all(
59 feature = "any_zlib",
60 not(any(feature = "cloudflare-zlib-sys", feature = "libz-rs-sys"))
61 ))]
62 zfree: allocator::zfree,
63
64 #[cfg(all(feature = "any_zlib", feature = "cloudflare-zlib-sys"))]
65 zalloc: Some(allocator::zalloc),
66 #[cfg(all(feature = "any_zlib", feature = "cloudflare-zlib-sys"))]
67 zfree: Some(allocator::zfree),
68
69 // for zlib-rs, it is most efficient to have it provide the allocator.
70 // The libz-rs-sys dependency is configured to use the rust system allocator
71 #[cfg(all(feature = "any_zlib", feature = "libz-rs-sys"))]
72 zalloc: None,
73 #[cfg(all(feature = "any_zlib", feature = "libz-rs-sys"))]
74 zfree: None,
75 })),
76 }
77 }
78 }
79
80 impl Drop for StreamWrapper {
81 fn drop(&mut self) {
82 // SAFETY: At this point, every other allocation for struct has been freed by
83 // `inflateEnd` or `deflateEnd`, and no copies of `inner` are retained by `C`,
84 // so it is safe to drop the struct as long as the user respects the invariant that
85 // `inner` must never be copied by Rust.
86 drop(unsafe { Box::from_raw(self.inner) });
87 }
88 }
89
90 #[cfg(all(feature = "any_zlib", not(feature = "libz-rs-sys")))]
91 mod allocator {
92 use super::*;
93
94 use std::alloc::{self, Layout};
95 use std::convert::TryFrom;
96 use std::os::raw::c_void;
97
98 const ALIGN: usize = std::mem::align_of::<usize>();
99
100 fn align_up(size: usize, align: usize) -> usize {
101 (size + align - 1) & !(align - 1)
102 }
103
104 pub extern "C" fn zalloc(_ptr: *mut c_void, items: uInt, item_size: uInt) -> *mut c_void {
105 // We need to multiply `items` and `item_size` to get the actual desired
106 // allocation size. Since `zfree` doesn't receive a size argument we
107 // also need to allocate space for a `usize` as a header so we can store
108 // how large the allocation is to deallocate later.
109 let size = match items
110 .checked_mul(item_size)
111 .and_then(|i| usize::try_from(i).ok())
112 .map(|size| align_up(size, ALIGN))
113 .and_then(|i| i.checked_add(std::mem::size_of::<usize>()))
114 {
115 Some(i) => i,
116 None => return ptr::null_mut(),
117 };
118
119 // Make sure the `size` isn't too big to fail `Layout`'s restrictions
120 let layout = match Layout::from_size_align(size, ALIGN) {
121 Ok(layout) => layout,
122 Err(_) => return ptr::null_mut(),
123 };
124
125 unsafe {
126 // Allocate the data, and if successful store the size we allocated
127 // at the beginning and then return an offset pointer.
128 let ptr = alloc::alloc(layout) as *mut usize;
129 if ptr.is_null() {
130 return ptr as *mut c_void;
131 }
132 *ptr = size;
133 ptr.add(1) as *mut c_void
134 }
135 }
136
137 pub extern "C" fn zfree(_ptr: *mut c_void, address: *mut c_void) {
138 unsafe {
139 // Move our address being freed back one pointer, read the size we
140 // stored in `zalloc`, and then free it using the standard Rust
141 // allocator.
142 let ptr = (address as *mut usize).offset(-1);
143 let size = *ptr;
144 let layout = Layout::from_size_align_unchecked(size, ALIGN);
145 alloc::dealloc(ptr as *mut u8, layout)
146 }
147 }
148 }
149
150 unsafe impl<D: Direction> Send for Stream<D> {}
151 unsafe impl<D: Direction> Sync for Stream<D> {}
152
153 /// Trait used to call the right destroy/end function on the inner
154 /// stream object on drop.
155 pub trait Direction {
156 unsafe fn destroy(stream: *mut mz_stream) -> c_int;
157 }
158
159 #[derive(Debug)]
160 pub enum DirCompress {}
161 #[derive(Debug)]
162 pub enum DirDecompress {}
163
164 #[derive(Debug)]
165 pub struct Stream<D: Direction> {
166 pub stream_wrapper: StreamWrapper,
167 pub total_in: u64,
168 pub total_out: u64,
169 pub _marker: marker::PhantomData<D>,
170 }
171
172 impl<D: Direction> Stream<D> {
173 pub fn msg(&self) -> ErrorMessage {
174 // SAFETY: The field `inner` must always be accessed as a raw pointer,
175 // since it points to a cyclic structure. No copies of `inner` can be
176 // retained for longer than the lifetime of `self`.
177 let msg = unsafe { (*self.stream_wrapper.inner).msg };
178 ErrorMessage(if msg.is_null() {
179 None
180 } else {
181 let s = unsafe { std::ffi::CStr::from_ptr(msg) };
182 std::str::from_utf8(s.to_bytes()).ok()
183 })
184 }
185 }
186
187 impl<D: Direction> Drop for Stream<D> {
188 fn drop(&mut self) {
189 unsafe {
190 let _ = D::destroy(self.stream_wrapper.inner);
191 }
192 }
193 }
194
195 impl Direction for DirCompress {
196 unsafe fn destroy(stream: *mut mz_stream) -> c_int {
197 mz_deflateEnd(stream)
198 }
199 }
200 impl Direction for DirDecompress {
201 unsafe fn destroy(stream: *mut mz_stream) -> c_int {
202 mz_inflateEnd(stream)
203 }
204 }
205
206 #[derive(Debug)]
207 pub struct Inflate {
208 pub inner: Stream<DirDecompress>,
209 }
210
211 impl InflateBackend for Inflate {
212 fn make(zlib_header: bool, window_bits: u8) -> Self {
213 unsafe {
214 let state = StreamWrapper::default();
215 let ret = mz_inflateInit2(
216 state.inner,
217 if zlib_header {
218 window_bits as c_int
219 } else {
220 -(window_bits as c_int)
221 },
222 );
223 assert_eq!(ret, 0);
224 Inflate {
225 inner: Stream {
226 stream_wrapper: state,
227 total_in: 0,
228 total_out: 0,
229 _marker: marker::PhantomData,
230 },
231 }
232 }
233 }
234
235 fn decompress(
236 &mut self,
237 input: &[u8],
238 output: &mut [u8],
239 flush: FlushDecompress,
240 ) -> Result<Status, DecompressError> {
241 let raw = self.inner.stream_wrapper.inner;
242 // SAFETY: The field `inner` must always be accessed as a raw pointer,
243 // since it points to a cyclic structure. No copies of `inner` can be
244 // retained for longer than the lifetime of `self`.
245 unsafe {
246 (*raw).msg = ptr::null_mut();
247 (*raw).next_in = input.as_ptr() as *mut u8;
248 (*raw).avail_in = cmp::min(input.len(), c_uint::MAX as usize) as c_uint;
249 (*raw).next_out = output.as_mut_ptr();
250 (*raw).avail_out = cmp::min(output.len(), c_uint::MAX as usize) as c_uint;
251
252 let rc = mz_inflate(raw, flush as c_int);
253
254 // Unfortunately the total counters provided by zlib might be only
255 // 32 bits wide and overflow while processing large amounts of data.
256 self.inner.total_in += ((*raw).next_in as usize - input.as_ptr() as usize) as u64;
257 self.inner.total_out += ((*raw).next_out as usize - output.as_ptr() as usize) as u64;
258
259 // reset these pointers so we don't accidentally read them later
260 (*raw).next_in = ptr::null_mut();
261 (*raw).avail_in = 0;
262 (*raw).next_out = ptr::null_mut();
263 (*raw).avail_out = 0;
264
265 match rc {
266 MZ_DATA_ERROR | MZ_STREAM_ERROR => mem::decompress_failed(self.inner.msg()),
267 MZ_OK => Ok(Status::Ok),
268 MZ_BUF_ERROR => Ok(Status::BufError),
269 MZ_STREAM_END => Ok(Status::StreamEnd),
270 MZ_NEED_DICT => mem::decompress_need_dict((*raw).adler as u32),
271 c => panic!("unknown return code: {}", c),
272 }
273 }
274 }
275
276 fn reset(&mut self, zlib_header: bool) {
277 let bits = if zlib_header {
278 MZ_DEFAULT_WINDOW_BITS
279 } else {
280 -MZ_DEFAULT_WINDOW_BITS
281 };
282 unsafe {
283 inflateReset2(self.inner.stream_wrapper.inner, bits);
284 }
285 self.inner.total_out = 0;
286 self.inner.total_in = 0;
287 }
288 }
289
290 impl Backend for Inflate {
291 #[inline]
292 fn total_in(&self) -> u64 {
293 self.inner.total_in
294 }
295
296 #[inline]
297 fn total_out(&self) -> u64 {
298 self.inner.total_out
299 }
300 }
301
302 #[derive(Debug)]
303 pub struct Deflate {
304 pub inner: Stream<DirCompress>,
305 }
306
307 impl DeflateBackend for Deflate {
308 fn make(level: Compression, zlib_header: bool, window_bits: u8) -> Self {
309 unsafe {
310 let state = StreamWrapper::default();
311 let ret = mz_deflateInit2(
312 state.inner,
313 level.0 as c_int,
314 MZ_DEFLATED,
315 if zlib_header {
316 window_bits as c_int
317 } else {
318 -(window_bits as c_int)
319 },
320 8,
321 MZ_DEFAULT_STRATEGY,
322 );
323 assert_eq!(ret, 0);
324 Deflate {
325 inner: Stream {
326 stream_wrapper: state,
327 total_in: 0,
328 total_out: 0,
329 _marker: marker::PhantomData,
330 },
331 }
332 }
333 }
334 fn compress(
335 &mut self,
336 input: &[u8],
337 output: &mut [u8],
338 flush: FlushCompress,
339 ) -> Result<Status, CompressError> {
340 let raw = self.inner.stream_wrapper.inner;
341 // SAFETY: The field `inner` must always be accessed as a raw pointer,
342 // since it points to a cyclic structure. No copies of `inner` can be
343 // retained for longer than the lifetime of `self`.
344 unsafe {
345 (*raw).msg = ptr::null_mut();
346 (*raw).next_in = input.as_ptr() as *mut _;
347 (*raw).avail_in = cmp::min(input.len(), c_uint::MAX as usize) as c_uint;
348 (*raw).next_out = output.as_mut_ptr();
349 (*raw).avail_out = cmp::min(output.len(), c_uint::MAX as usize) as c_uint;
350
351 let rc = mz_deflate(raw, flush as c_int);
352
353 // Unfortunately the total counters provided by zlib might be only
354 // 32 bits wide and overflow while processing large amounts of data.
355
356 self.inner.total_in += ((*raw).next_in as usize - input.as_ptr() as usize) as u64;
357 self.inner.total_out += ((*raw).next_out as usize - output.as_ptr() as usize) as u64;
358 // reset these pointers so we don't accidentally read them later
359 (*raw).next_in = ptr::null_mut();
360 (*raw).avail_in = 0;
361 (*raw).next_out = ptr::null_mut();
362 (*raw).avail_out = 0;
363
364 match rc {
365 MZ_OK => Ok(Status::Ok),
366 MZ_BUF_ERROR => Ok(Status::BufError),
367 MZ_STREAM_END => Ok(Status::StreamEnd),
368 MZ_STREAM_ERROR => mem::compress_failed(self.inner.msg()),
369 c => panic!("unknown return code: {}", c),
370 }
371 }
372 }
373
374 fn reset(&mut self) {
375 self.inner.total_in = 0;
376 self.inner.total_out = 0;
377 let rc = unsafe { mz_deflateReset(self.inner.stream_wrapper.inner) };
378 assert_eq!(rc, MZ_OK);
379 }
380 }
381
382 impl Backend for Deflate {
383 #[inline]
384 fn total_in(&self) -> u64 {
385 self.inner.total_in
386 }
387
388 #[inline]
389 fn total_out(&self) -> u64 {
390 self.inner.total_out
391 }
392 }
393
394 pub use self::c_backend::*;
395
396 /// For backwards compatibility, we provide symbols as `mz_` to mimic the miniz API
397 #[allow(bad_style)]
398 #[allow(unused_imports)]
399 mod c_backend {
400 use std::mem;
401 use std::os::raw::{c_char, c_int};
402
403 #[cfg(feature = "zlib-ng")]
404 use libz_ng_sys as libz;
405
406 #[cfg(all(not(feature = "zlib-ng"), feature = "zlib-rs"))]
407 use libz_rs_sys as libz;
408
409 #[cfg(all(not(feature = "zlib-ng"), feature = "cloudflare_zlib"))]
410 use cloudflare_zlib_sys as libz;
411
412 #[cfg(all(
413 not(feature = "cloudflare_zlib"),
414 not(feature = "zlib-ng"),
415 not(feature = "zlib-rs")
416 ))]
417 use libz_sys as libz;
418
419 pub use libz::deflate as mz_deflate;
420 pub use libz::deflateEnd as mz_deflateEnd;
421 pub use libz::deflateReset as mz_deflateReset;
422 pub use libz::inflate as mz_inflate;
423 pub use libz::inflateEnd as mz_inflateEnd;
424 pub use libz::z_stream as mz_stream;
425 pub use libz::*;
426
427 pub use libz::Z_BLOCK as MZ_BLOCK;
428 pub use libz::Z_BUF_ERROR as MZ_BUF_ERROR;
429 pub use libz::Z_DATA_ERROR as MZ_DATA_ERROR;
430 pub use libz::Z_DEFAULT_STRATEGY as MZ_DEFAULT_STRATEGY;
431 pub use libz::Z_DEFLATED as MZ_DEFLATED;
432 pub use libz::Z_FINISH as MZ_FINISH;
433 pub use libz::Z_FULL_FLUSH as MZ_FULL_FLUSH;
434 pub use libz::Z_NEED_DICT as MZ_NEED_DICT;
435 pub use libz::Z_NO_FLUSH as MZ_NO_FLUSH;
436 pub use libz::Z_OK as MZ_OK;
437 pub use libz::Z_PARTIAL_FLUSH as MZ_PARTIAL_FLUSH;
438 pub use libz::Z_STREAM_END as MZ_STREAM_END;
439 pub use libz::Z_STREAM_ERROR as MZ_STREAM_ERROR;
440 pub use libz::Z_SYNC_FLUSH as MZ_SYNC_FLUSH;
441
442 pub const MZ_DEFAULT_WINDOW_BITS: c_int = 15;
443
444 #[cfg(feature = "zlib-ng")]
445 const ZLIB_VERSION: &'static str = "2.1.0.devel\0";
446 #[cfg(all(not(feature = "zlib-ng"), feature = "zlib-rs"))]
447 const ZLIB_VERSION: &'static str = "0.1.0\0";
448 #[cfg(not(any(feature = "zlib-ng", feature = "zlib-rs")))]
449 const ZLIB_VERSION: &'static str = "1.2.8\0";
450
451 pub unsafe extern "C" fn mz_deflateInit2(
452 stream: *mut mz_stream,
453 level: c_int,
454 method: c_int,
455 window_bits: c_int,
456 mem_level: c_int,
457 strategy: c_int,
458 ) -> c_int {
459 libz::deflateInit2_(
460 stream,
461 level,
462 method,
463 window_bits,
464 mem_level,
465 strategy,
466 ZLIB_VERSION.as_ptr() as *const c_char,
467 mem::size_of::<mz_stream>() as c_int,
468 )
469 }
470 pub unsafe extern "C" fn mz_inflateInit2(stream: *mut mz_stream, window_bits: c_int) -> c_int {
471 libz::inflateInit2_(
472 stream,
473 window_bits,
474 ZLIB_VERSION.as_ptr() as *const c_char,
475 mem::size_of::<mz_stream>() as c_int,
476 )
477 }
478 }