Debian Codegraph @

debian/missing-sources/flate2/src/ffi/c.rs

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