Debian Codegraph @

debian/rust-vendor/flate2/src/ffi/c.rs

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