Lucas Smith
Lucas Smith

Reputation: 25

Zlib inflate works differently to C?

I am trying to zlib inflate a byte array in java, however I am not getting the Z_STREAM_END returned when I inflate it. I have the code exactly the same as some C code I viewed which worked with the same data, sliding window and other parameters (I think?). I am using JZlib. Here is my Java code (dgboff is just the offset of this zlib byte array in a file):

private byte[] z_decompress(byte[] in,int insize,byte[] out,int outsize) {
    ZStream zlib = new ZStream();
    zlib.inflateInit(15);//32k window (2^15)
    zlib.next_in=in;
    zlib.avail_in=insize;
    zlib.next_out=out;
    zlib.avail_out=outsize;
    if(zlib.inflate(JZlib.Z_FINISH)!=JZlib.Z_STREAM_END) {
        System.out.println("Incomplete zlib input at offset "+dgboff+". Compressed size: "+insize+", uncompressed size: "+outsize);
        System.exit(1);
    }
    zlib.inflateEnd();
    return zlib.next_out;
}

and here is the C code, which works (ignore the messy spacing):

 z = calloc(1, sizeof(z_stream)); 
    if(!z) std_err(); 
    z->zalloc = (alloc_func)0; 
    z->zfree  = (free_func)0; 
    z->opaque = (voidpf)0; 
if(inflateInit2(z, 15)) { 
        printf("\nError: initialization error\n"); 
        exit(1); 
 } 
inflateReset(z);

z->next_in   = in;
z->avail_in  = insz;
z->next_out  = out;
z->avail_out = outsz;
if(inflate(z, Z_FINISH) != Z_STREAM_END) {
    printf("\nError: the compressed zlib/deflate input at offset 0x%08x (%d -> %d) is wrong or incomplete\n", (int)g_dbg_offset, (int)insz, (int)outsz);
    exit(1);
}
//gets to here in C

If there is anything I am missing please tell me!

The zlib header for the data I am testing is 0x649d.

Upvotes: 0

Views: 451

Answers (1)

Mark Adler
Mark Adler

Reputation: 112284

Your data is not a zlib stream, and does not have a zlib header. It is a raw deflate stream. Neither of your code examples as shown could have worked. Your "here is the C code, which works" must have been some other C code.

To decompress raw inflate data, you need to use -15 (instead of 15) as the second argument of inflateInit2().

By the way, the deflate compressed data you provided a link for is incomplete. It is correct as far as it goes, but it does not terminate.

Upvotes: 1

Related Questions