Ignore:
Timestamp:
Nov 4, 2007, 3:16:40 AM (16 years ago)
Author:
Bruno Cornec
Message:

Update to busybox 1.7.2

Location:
branches/2.2.5/mindi-busybox/archival/libunarchive
Files:
2 added
4 deleted
29 edited

Legend:

Unmodified
Added
Removed
  • branches/2.2.5/mindi-busybox/archival/libunarchive/archive_xread_all_eof.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/*
    2  *  This program is free software; you can redistribute it and/or modify
    3  *  it under the terms of the GNU General Public License as published by
    4  *  the Free Software Foundation; either version 2 of the License, or
    5  *  (at your option) any later version.
    6  *
    7  *  This program is distributed in the hope that it will be useful,
    8  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
    9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    10  *  GNU Library General Public License for more details.
    11  *
    12  *  You should have received a copy of the GNU General Public License
    13  *  along with this program; if not, write to the Free Software
    14  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
     3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
    154 */
    165
    17 #include <stdio.h>
    18 #include <stdlib.h>
    19 #include <string.h>
     6#include "libbb.h"
    207#include "unarchive.h"
    21 #include "libbb.h"
    228
    23 ssize_t archive_xread_all_eof(archive_handle_t *archive_handle, unsigned char *buf, size_t count)
     9ssize_t archive_xread_all_eof(archive_handle_t *archive_handle,
     10            unsigned char *buf, size_t count)
    2411{
    2512    ssize_t size;
    2613
    27     size = bb_full_read(archive_handle->src_fd, buf, count);
    28     if ((size != 0) && (size != count)) {
    29         bb_perror_msg_and_die("Short read, read %ld of %ld", (long)size, (long)count);
     14    size = full_read(archive_handle->src_fd, buf, count);
     15    if (size != 0 && size != count) {
     16        bb_error_msg_and_die("short read: %u of %u",
     17                (unsigned)size, (unsigned)count);
    3018    }
    31     return(size);
     19    return size;
    3220}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/check_header_gzip.c

    r821 r1765  
    1 #include <stdlib.h>
    2 #include <unistd.h>
     1/* vi: set sw=4 ts=4: */
     2/*
     3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
     4 */
     5
    36#include "libbb.h"
    4 #include "unarchive.h" /* for external decl of check_header_gzip */
     7#include "unarchive.h" /* for external decl of check_header_gzip_or_die */
    58
    6 void check_header_gzip(int src_fd)
     9void check_header_gzip_or_die(int src_fd)
    710{
    811    union {
     
    1417            unsigned char xtra_flags;
    1518            unsigned char os_flags;
    16         } formated;
     19        } formatted;
    1720    } header;
    1821
    19     bb_xread_all(src_fd, header.raw, 8);
     22    xread(src_fd, header.raw, 8);
    2023
    2124    /* Check the compression method */
    22     if (header.formated.method != 8) {
    23         bb_error_msg_and_die("Unknown compression method %d",
    24                           header.formated.method);
     25    if (header.formatted.method != 8) {
     26        bb_error_msg_and_die("unknown compression method %d",
     27                          header.formatted.method);
    2528    }
    2629
    27     if (header.formated.flags & 0x04) {
     30    if (header.formatted.flags & 0x04) {
    2831        /* bit 2 set: extra field present */
    29         unsigned char extra_short;
     32        unsigned extra_short;
    3033
    31         extra_short = bb_xread_char(src_fd) + (bb_xread_char(src_fd) << 8);
     34        extra_short = xread_char(src_fd) + (xread_char(src_fd) << 8);
    3235        while (extra_short > 0) {
    3336            /* Ignore extra field */
    34             bb_xread_char(src_fd);
     37            xread_char(src_fd);
    3538            extra_short--;
    3639        }
     
    3841
    3942    /* Discard original name if any */
    40     if (header.formated.flags & 0x08) {
     43    if (header.formatted.flags & 0x08) {
    4144        /* bit 3 set: original file name present */
    42         while(bb_xread_char(src_fd) != 0);
     45        while (xread_char(src_fd) != 0);
    4346    }
    4447
    4548    /* Discard file comment if any */
    46     if (header.formated.flags & 0x10) {
     49    if (header.formatted.flags & 0x10) {
    4750        /* bit 4 set: file comment present */
    48         while(bb_xread_char(src_fd) != 0);
     51        while (xread_char(src_fd) != 0);
    4952    }
    5053
    5154    /* Read the header checksum */
    52     if (header.formated.flags & 0x02) {
    53         bb_xread_char(src_fd);
    54         bb_xread_char(src_fd);
     55    if (header.formatted.flags & 0x02) {
     56        xread_char(src_fd);
     57        xread_char(src_fd);
    5558    }
    56 
    57     return;
    5859}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/data_align.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/*
    2  *  This program is free software; you can redistribute it and/or modify
    3  *  it under the terms of the GNU General Public License as published by
    4  *  the Free Software Foundation; either version 2 of the License, or
    5  *  (at your option) any later version.
    6  *
    7  *  This program is distributed in the hope that it will be useful,
    8  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
    9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    10  *  GNU General Public License for more details.
    11  *
    12  *  You should have received a copy of the GNU General Public License
    13  *  along with this program; if not, write to the Free Software
    14  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
     3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
    154 */
    165
    17 #include <sys/types.h>
    18 
    19 #include <errno.h>
    20 #include <unistd.h>
     6//#include <sys/types.h>
    217
    228#include "libbb.h"
     
    2915    archive_handle->seek(archive_handle, skip_amount);
    3016    archive_handle->offset += skip_amount;
    31 
    32     return;
    3317}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/data_extract_all.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/*
    2  *  This program is free software; you can redistribute it and/or modify
    3  *  it under the terms of the GNU General Public License as published by
    4  *  the Free Software Foundation; either version 2 of the License, or
    5  *  (at your option) any later version.
    6  *
    7  *  This program is distributed in the hope that it will be useful,
    8  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
    9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    10  *  GNU General Public License for more details.
    11  *
    12  *  You should have received a copy of the GNU General Public License
    13  *  along with this program; if not, write to the Free Software
    14  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
     3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
    154 */
    16 
    17 #include <sys/types.h>
    18 
    19 #include <errno.h>
    20 #include <fcntl.h>
    21 #include <stdlib.h>
    22 #include <string.h>
    23 #include <utime.h>
    24 #include <unistd.h>
    25 #include <stdlib.h>
    265
    276#include "libbb.h"
     
    3514
    3615    if (archive_handle->flags & ARCHIVE_CREATE_LEADING_DIRS) {
    37         char *name = bb_xstrdup(file_header->name);
    38         bb_make_directory (dirname(name), -1, FILEUTILS_RECUR);
     16        char *name = xstrdup(file_header->name);
     17        bb_make_directory(dirname(name), -1, FILEUTILS_RECUR);
    3918        free(name);
    4019    }
     
    4322    if (archive_handle->flags & ARCHIVE_EXTRACT_UNCONDITIONAL) {
    4423        /* Remove the existing entry if it exists */
    45         if (((file_header->mode & S_IFMT) != S_IFDIR) && (unlink(file_header->name) == -1) && (errno != ENOENT)) {
    46             bb_perror_msg_and_die("Couldnt remove old file");
     24        if (((file_header->mode & S_IFMT) != S_IFDIR)
     25         && (unlink(file_header->name) == -1)
     26         && (errno != ENOENT)
     27        ) {
     28            bb_perror_msg_and_die("cannot remove old file %s",
     29                    file_header->name);
    4730        }
    4831    }
     
    5235        if (lstat(file_header->name, &statbuf) == -1) {
    5336            if (errno != ENOENT) {
    54                 bb_perror_msg_and_die("Couldnt stat old file");
     37                bb_perror_msg_and_die("cannot stat old file");
    5538            }
    5639        }
    5740        else if (statbuf.st_mtime <= file_header->mtime) {
    5841            if (!(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
    59                 bb_error_msg("%s not created: newer or same age file exists", file_header->name);
     42                bb_error_msg("%s not created: newer or "
     43                    "same age file exists", file_header->name);
    6044            }
    6145            data_skip(archive_handle);
     
    6347        }
    6448        else if ((unlink(file_header->name) == -1) && (errno != EISDIR)) {
    65             bb_perror_msg_and_die("Couldnt remove old file %s", file_header->name);
     49            bb_perror_msg_and_die("cannot remove old file %s",
     50                    file_header->name);
    6651        }
    6752    }
     
    6954    /* Handle hard links separately
    7055     * We identified hard links as regular files of size 0 with a symlink */
    71     if (S_ISREG(file_header->mode) && (file_header->link_name) && (file_header->size == 0)) {
     56    if (S_ISREG(file_header->mode) && (file_header->link_target)
     57     && (file_header->size == 0)
     58    ) {
    7259        /* hard link */
    73         res = link(file_header->link_name, file_header->name);
     60        res = link(file_header->link_target, file_header->name);
    7461        if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
    75             bb_perror_msg("Couldnt create hard link");
     62            bb_perror_msg("cannot create %slink "
     63                    "from %s to %s", "hard",
     64                    file_header->name,
     65                    file_header->link_target);
    7666        }
    7767    } else {
    7868        /* Create the filesystem entry */
    79         switch(file_header->mode & S_IFMT) {
    80             case S_IFREG: {
    81                 /* Regular file */
    82                 dst_fd = bb_xopen(file_header->name, O_WRONLY | O_CREAT | O_EXCL);
    83                 bb_copyfd_size(archive_handle->src_fd, dst_fd, file_header->size);
    84                 close(dst_fd);
    85                 break;
    86                 }
    87             case S_IFDIR:
    88                 res = mkdir(file_header->name, file_header->mode);
    89                 if ((errno != EISDIR) && (res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
    90                     bb_perror_msg("extract_archive: %s", file_header->name);
    91                 }
    92                 break;
    93             case S_IFLNK:
    94                 /* Symlink */
    95                 res = symlink(file_header->link_name, file_header->name);
    96                 if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
    97                     bb_perror_msg("Cannot create symlink from %s to '%s'", file_header->name, file_header->link_name);
    98                 }
    99                 break;
    100             case S_IFSOCK:
    101             case S_IFBLK:
    102             case S_IFCHR:
    103             case S_IFIFO:
    104                 res = mknod(file_header->name, file_header->mode, file_header->device);
    105                 if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
    106                     bb_perror_msg("Cannot create node %s", file_header->name);
    107                 }
    108                 break;
    109             default:
    110                 bb_error_msg_and_die("Unrecognised file type");
     69        switch (file_header->mode & S_IFMT) {
     70        case S_IFREG: {
     71            /* Regular file */
     72            dst_fd = xopen3(file_header->name, O_WRONLY | O_CREAT | O_EXCL,
     73                            file_header->mode);
     74            bb_copyfd_exact_size(archive_handle->src_fd, dst_fd, file_header->size);
     75            close(dst_fd);
     76            break;
     77        }
     78        case S_IFDIR:
     79            res = mkdir(file_header->name, file_header->mode);
     80            if ((res == -1) && (errno != EISDIR)
     81             && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)
     82            ) {
     83                bb_perror_msg("cannot make dir %s", file_header->name);
     84            }
     85            break;
     86        case S_IFLNK:
     87            /* Symlink */
     88            res = symlink(file_header->link_target, file_header->name);
     89            if ((res == -1)
     90             && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)
     91            ) {
     92                bb_perror_msg("cannot create %slink "
     93                    "from %s to %s", "sym",
     94                    file_header->name,
     95                    file_header->link_target);
     96            }
     97            break;
     98        case S_IFSOCK:
     99        case S_IFBLK:
     100        case S_IFCHR:
     101        case S_IFIFO:
     102            res = mknod(file_header->name, file_header->mode, file_header->device);
     103            if ((res == -1)
     104             && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)
     105            ) {
     106                bb_perror_msg("cannot create node %s", file_header->name);
     107            }
     108            break;
     109        default:
     110            bb_error_msg_and_die("unrecognized file type");
    111111        }
    112112    }
     
    115115        lchown(file_header->name, file_header->uid, file_header->gid);
    116116    }
    117     if (!(archive_handle->flags & ARCHIVE_NOPRESERVE_PERM) &&
    118          (file_header->mode & S_IFMT) != S_IFLNK)
    119     {
    120         chmod(file_header->name, file_header->mode);
    121     }
    122 
    123     if (archive_handle->flags & ARCHIVE_PRESERVE_DATE) {
    124         struct utimbuf t;
    125         t.actime = t.modtime = file_header->mtime;
    126         utime(file_header->name, &t);
     117    if ((file_header->mode & S_IFMT) != S_IFLNK) {
     118        /* uclibc has no lchmod, glibc is even stranger -
     119         * it has lchmod which seems to do nothing!
     120         * so we use chmod... */
     121        if (!(archive_handle->flags & ARCHIVE_NOPRESERVE_PERM)) {
     122            chmod(file_header->name, file_header->mode);
     123        }
     124        /* same for utime */
     125        if (archive_handle->flags & ARCHIVE_PRESERVE_DATE) {
     126            struct utimbuf t;
     127            t.actime = t.modtime = file_header->mtime;
     128            utime(file_header->name, &t);
     129        }
    127130    }
    128131}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/data_extract_to_buffer.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/*
    23 * Copyright 2002 Glenn McGrath
     
    1011void data_extract_to_buffer(archive_handle_t *archive_handle)
    1112{
    12     const unsigned int size = archive_handle->file_header->size;
     13    unsigned int size = archive_handle->file_header->size;
    1314
    1415    archive_handle->buffer = xzalloc(size + 1);
    15 
    16     archive_xread_all(archive_handle, archive_handle->buffer, size);
     16    xread(archive_handle->src_fd, archive_handle->buffer, size);
    1717}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/data_extract_to_stdout.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/*
    2  *  This program is free software; you can redistribute it and/or modify
    3  *  it under the terms of the GNU General Public License as published by
    4  *  the Free Software Foundation; either version 2 of the License, or
    5  *  (at your option) any later version.
    6  *
    7  *  This program is distributed in the hope that it will be useful,
    8  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
    9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    10  *  GNU General Public License for more details.
    11  *
    12  *  You should have received a copy of the GNU General Public License
    13  *  along with this program; if not, write to the Free Software
    14  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
     3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
    154 */
    165
     6#include "libbb.h"
    177#include "unarchive.h"
    18 #include <unistd.h>
    198
    209void data_extract_to_stdout(archive_handle_t *archive_handle)
    2110{
    22     bb_copyfd_size(archive_handle->src_fd, STDOUT_FILENO, archive_handle->file_header->size);
     11    bb_copyfd_exact_size(archive_handle->src_fd,
     12            STDOUT_FILENO,
     13            archive_handle->file_header->size);
    2314}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/data_skip.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/*
    2  *  This program is free software; you can redistribute it and/or modify
    3  *  it under the terms of the GNU General Public License as published by
    4  *  the Free Software Foundation; either version 2 of the License, or
    5  *  (at your option) any later version.
    6  *
    7  *  This program is distributed in the hope that it will be useful,
    8  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
    9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    10  *  GNU General Public License for more details.
    11  *
    12  *  You should have received a copy of the GNU General Public License
    13  *  along with this program; if not, write to the Free Software
    14  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
     3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
    154 */
    165
    17 #include <sys/types.h>
    18 #include <errno.h>
    19 #include <unistd.h>
    20 #include <stdlib.h>
     6#include "libbb.h"
    217#include "unarchive.h"
    22 #include "libbb.h"
    238
    249void data_skip(archive_handle_t *archive_handle)
  • branches/2.2.5/mindi-busybox/archival/libunarchive/decompress_bunzip2.c

    r821 r1765  
    2929 */
    3030
    31 #include <setjmp.h>
    32 #include <stdio.h>
    33 #include <stdlib.h>
    34 #include <string.h>
    35 #include <unistd.h>
    36 #include <limits.h>
    37 
    3831#include "libbb.h"
    39 
    4032#include "unarchive.h"
    4133
    4234/* Constants for Huffman coding */
    43 #define MAX_GROUPS          6
    44 #define GROUP_SIZE          50      /* 64 would have been more efficient */
    45 #define MAX_HUFCODE_BITS    20      /* Longest Huffman code allowed */
    46 #define MAX_SYMBOLS         258     /* 256 literals + RUNA + RUNB */
    47 #define SYMBOL_RUNA         0
    48 #define SYMBOL_RUNB         1
     35#define MAX_GROUPS          6
     36#define GROUP_SIZE          50      /* 64 would have been more efficient */
     37#define MAX_HUFCODE_BITS    20      /* Longest Huffman code allowed */
     38#define MAX_SYMBOLS         258     /* 256 literals + RUNA + RUNB */
     39#define SYMBOL_RUNA         0
     40#define SYMBOL_RUNB         1
    4941
    5042/* Status return values */
    51 #define RETVAL_OK                       0
    52 #define RETVAL_LAST_BLOCK               (-1)
    53 #define RETVAL_NOT_BZIP_DATA            (-2)
    54 #define RETVAL_UNEXPECTED_INPUT_EOF     (-3)
    55 #define RETVAL_UNEXPECTED_OUTPUT_EOF    (-4)
    56 #define RETVAL_DATA_ERROR               (-5)
    57 #define RETVAL_OUT_OF_MEMORY            (-6)
    58 #define RETVAL_OBSOLETE_INPUT           (-7)
     43#define RETVAL_OK                       0
     44#define RETVAL_LAST_BLOCK               (-1)
     45#define RETVAL_NOT_BZIP_DATA            (-2)
     46#define RETVAL_UNEXPECTED_INPUT_EOF     (-3)
     47#define RETVAL_UNEXPECTED_OUTPUT_EOF    (-4)
     48#define RETVAL_DATA_ERROR               (-5)
     49#define RETVAL_OUT_OF_MEMORY            (-6)
     50#define RETVAL_OBSOLETE_INPUT           (-7)
    5951
    6052/* Other housekeeping constants */
    61 #define IOBUF_SIZE          4096
     53#define IOBUF_SIZE          4096
    6254
    6355/* This is what we know about each Huffman coding group */
    6456struct group_data {
    6557    /* We have an extra slot at the end of limit[] for a sentinal value. */
    66     int limit[MAX_HUFCODE_BITS+1],base[MAX_HUFCODE_BITS],permute[MAX_SYMBOLS];
     58    int limit[MAX_HUFCODE_BITS+1], base[MAX_HUFCODE_BITS], permute[MAX_SYMBOLS];
    6759    int minLen, maxLen;
    6860};
     
    7163   memory that persists between calls to bunzip */
    7264
    73 typedef struct {
     65struct bunzip_data {
    7466    /* State for interrupting output loop */
    75 
    76     int writeCopies,writePos,writeRunCountdown,writeCount,writeCurrent;
     67    int writeCopies, writePos, writeRunCountdown, writeCount, writeCurrent;
    7768
    7869    /* I/O tracking data (file handles, buffers, positions, etc.) */
    79 
    80     int in_fd,out_fd,inbufCount,inbufPos /*,outbufPos*/;
     70    int in_fd, out_fd, inbufCount, inbufPos /*, outbufPos*/;
    8171    unsigned char *inbuf /*,*outbuf*/;
    82     unsigned int inbufBitCount, inbufBits;
     72    unsigned inbufBitCount, inbufBits;
    8373
    8474    /* The CRC values stored in the block header and calculated from the data */
    85 
    8675    uint32_t headerCRC, totalCRC, writeCRC;
    87     uint32_t *crc32Table;
     76
    8877    /* Intermediate buffer and its size (in bytes) */
    89 
    90     unsigned int *dbuf, dbufSize;
    91 
    92     /* These things are a bit too big to go on the stack */
    93 
     78    unsigned *dbuf, dbufSize;
     79
     80    /* For I/O error handling */
     81    jmp_buf jmpbuf;
     82
     83    /* Big things go last (register-relative addressing can be larger for big offsets */
     84    uint32_t crc32Table[256];
    9485    unsigned char selectors[32768];         /* nSelectors=15 bits */
    9586    struct group_data groups[MAX_GROUPS];   /* Huffman coding tables */
    96 
    97     /* For I/O error handling */
    98 
    99     jmp_buf jmpbuf;
    100 } bunzip_data;
     87};
     88/* typedef struct bunzip_data bunzip_data; -- done in .h file */
     89
    10190
    10291/* Return the next nnn bits of input.  All reads from the compressed input
    10392   are done through this function.  All reads are big endian */
    10493
    105 static unsigned int get_bits(bunzip_data *bd, char bits_wanted)
     94static unsigned get_bits(bunzip_data *bd, char bits_wanted)
    10695{
    107     unsigned int bits=0;
     96    unsigned bits = 0;
    10897
    10998    /* If we need to get more data from the byte buffer, do so.  (Loop getting
    11099       one byte at a time to enforce endianness and avoid unaligned access.) */
    111100
    112     while (bd->inbufBitCount<bits_wanted) {
     101    while (bd->inbufBitCount < bits_wanted) {
    113102
    114103        /* If we need to read more data from file into byte buffer, do so */
    115104
    116         if(bd->inbufPos==bd->inbufCount) {
    117             if((bd->inbufCount = read(bd->in_fd, bd->inbuf, IOBUF_SIZE)) <= 0)
    118                 longjmp(bd->jmpbuf,RETVAL_UNEXPECTED_INPUT_EOF);
    119             bd->inbufPos=0;
     105        if (bd->inbufPos == bd->inbufCount) {
     106            /* if "no input fd" case: in_fd == -1, read fails, we jump */
     107            bd->inbufCount = read(bd->in_fd, bd->inbuf, IOBUF_SIZE);
     108            if (bd->inbufCount <= 0)
     109                longjmp(bd->jmpbuf, RETVAL_UNEXPECTED_INPUT_EOF);
     110            bd->inbufPos = 0;
    120111        }
    121112
    122113        /* Avoid 32-bit overflow (dump bit buffer to top of output) */
    123114
    124         if(bd->inbufBitCount>=24) {
    125             bits=bd->inbufBits&((1<<bd->inbufBitCount)-1);
    126             bits_wanted-=bd->inbufBitCount;
    127             bits<<=bits_wanted;
    128             bd->inbufBitCount=0;
     115        if (bd->inbufBitCount >= 24) {
     116            bits = bd->inbufBits & ((1 << bd->inbufBitCount) - 1);
     117            bits_wanted -= bd->inbufBitCount;
     118            bits <<= bits_wanted;
     119            bd->inbufBitCount = 0;
    129120        }
    130121
    131122        /* Grab next 8 bits of input from buffer. */
    132123
    133         bd->inbufBits=(bd->inbufBits<<8)|bd->inbuf[bd->inbufPos++];
    134         bd->inbufBitCount+=8;
     124        bd->inbufBits = (bd->inbufBits<<8) | bd->inbuf[bd->inbufPos++];
     125        bd->inbufBitCount += 8;
    135126    }
    136127
    137128    /* Calculate result */
    138129
    139     bd->inbufBitCount-=bits_wanted;
    140     bits|=(bd->inbufBits>>bd->inbufBitCount)&((1<<bits_wanted)-1);
     130    bd->inbufBitCount -= bits_wanted;
     131    bits |= (bd->inbufBits >> bd->inbufBitCount) & ((1 << bits_wanted) - 1);
    141132
    142133    return bits;
     
    148139{
    149140    struct group_data *hufGroup;
    150     int dbufCount,nextSym,dbufSize,groupCount,*base,*limit,selector,
    151         i,j,k,t,runPos,symCount,symTotal,nSelectors,byteCount[256];
     141    int dbufCount, nextSym, dbufSize, groupCount, *base, *limit, selector,
     142        i, j, k, t, runPos, symCount, symTotal, nSelectors, byteCount[256];
    152143    unsigned char uc, symToByte[256], mtfSymbol[256], *selectors;
    153     unsigned int *dbuf,origPtr;
    154 
    155     dbuf=bd->dbuf;
    156     dbufSize=bd->dbufSize;
    157     selectors=bd->selectors;
     144    unsigned *dbuf, origPtr;
     145
     146    dbuf = bd->dbuf;
     147    dbufSize = bd->dbufSize;
     148    selectors = bd->selectors;
    158149
    159150    /* Reset longjmp I/O error handling */
    160151
    161     i=setjmp(bd->jmpbuf);
    162     if(i) return i;
     152    i = setjmp(bd->jmpbuf);
     153    if (i) return i;
    163154
    164155    /* Read in header signature and CRC, then validate signature.
    165156       (last block signature means CRC is for whole file, return now) */
    166157
    167     i = get_bits(bd,24);
    168     j = get_bits(bd,24);
    169     bd->headerCRC=get_bits(bd,32);
     158    i = get_bits(bd, 24);
     159    j = get_bits(bd, 24);
     160    bd->headerCRC = get_bits(bd, 32);
    170161    if ((i == 0x177245) && (j == 0x385090)) return RETVAL_LAST_BLOCK;
    171162    if ((i != 0x314159) || (j != 0x265359)) return RETVAL_NOT_BZIP_DATA;
     
    175166       it didn't actually work. */
    176167
    177     if(get_bits(bd,1)) return RETVAL_OBSOLETE_INPUT;
    178     if((origPtr=get_bits(bd,24)) > dbufSize) return RETVAL_DATA_ERROR;
     168    if (get_bits(bd, 1)) return RETVAL_OBSOLETE_INPUT;
     169    origPtr = get_bits(bd, 24);
     170    if (origPtr > dbufSize) return RETVAL_DATA_ERROR;
    179171
    180172    /* mapping table: if some byte values are never used (encoding things
     
    184176       back to the corresponding bytes. */
    185177
    186     t=get_bits(bd, 16);
    187     symTotal=0;
    188     for (i=0;i<16;i++) {
    189         if(t&(1<<(15-i))) {
    190             k=get_bits(bd,16);
    191             for(j=0;j<16;j++)
    192                 if(k&(1<<(15-j))) symToByte[symTotal++]=(16*i)+j;
     178    t = get_bits(bd, 16);
     179    symTotal = 0;
     180    for (i = 0; i < 16; i++) {
     181        if (t & (1 << (15-i))) {
     182            k = get_bits(bd, 16);
     183            for (j = 0; j < 16; j++)
     184                if (k & (1 << (15-j)))
     185                    symToByte[symTotal++] = (16*i) + j;
    193186        }
    194187    }
     
    196189    /* How many different Huffman coding groups does this block use? */
    197190
    198     groupCount=get_bits(bd,3);
    199     if (groupCount<2 || groupCount>MAX_GROUPS) return RETVAL_DATA_ERROR;
     191    groupCount = get_bits(bd, 3);
     192    if (groupCount < 2 || groupCount > MAX_GROUPS)
     193        return RETVAL_DATA_ERROR;
    200194
    201195    /* nSelectors: Every GROUP_SIZE many symbols we select a new Huffman coding
     
    204198       start of the list.) */
    205199
    206     if(!(nSelectors=get_bits(bd, 15))) return RETVAL_DATA_ERROR;
    207     for(i=0; i<groupCount; i++) mtfSymbol[i] = i;
    208     for(i=0; i<nSelectors; i++) {
     200    nSelectors = get_bits(bd, 15);
     201    if (!nSelectors) return RETVAL_DATA_ERROR;
     202    for (i = 0; i < groupCount; i++) mtfSymbol[i] = i;
     203    for (i = 0; i < nSelectors; i++) {
    209204
    210205        /* Get next value */
    211206
    212         for(j=0;get_bits(bd,1);j++) if (j>=groupCount) return RETVAL_DATA_ERROR;
     207        for (j = 0; get_bits(bd, 1); j++)
     208            if (j>=groupCount) return RETVAL_DATA_ERROR;
    213209
    214210        /* Decode MTF to get the next selector */
    215211
    216212        uc = mtfSymbol[j];
    217         for(;j;j--) mtfSymbol[j] = mtfSymbol[j-1];
    218         mtfSymbol[0]=selectors[i]=uc;
     213        for (;j;j--) mtfSymbol[j] = mtfSymbol[j-1];
     214        mtfSymbol[0] = selectors[i] = uc;
    219215    }
    220216
     
    222218       literal symbols, plus two run symbols (RUNA, RUNB) */
    223219
    224     symCount=symTotal+2;
    225     for (j=0; j<groupCount; j++) {
    226         unsigned char length[MAX_SYMBOLS],temp[MAX_HUFCODE_BITS+1];
    227         int minLen, maxLen, pp;
     220    symCount = symTotal + 2;
     221    for (j = 0; j < groupCount; j++) {
     222        unsigned char length[MAX_SYMBOLS], temp[MAX_HUFCODE_BITS+1];
     223        int minLen, maxLen, pp;
    228224
    229225        /* Read Huffman code lengths for each symbol.  They're stored in
     
    234230           length 0 becomes negative, so an unsigned inequality catches it.) */
    235231
    236         t=get_bits(bd, 5)-1;
     232        t = get_bits(bd, 5) - 1;
    237233        for (i = 0; i < symCount; i++) {
    238             for(;;) {
    239                 if (((unsigned)t) > (MAX_HUFCODE_BITS-1))
     234            for (;;) {
     235                if ((unsigned)t > (MAX_HUFCODE_BITS-1))
    240236                    return RETVAL_DATA_ERROR;
    241237
     
    244240                   bits and unget the second if the first was 0. */
    245241
    246                 k = get_bits(bd,2);
     242                k = get_bits(bd, 2);
    247243                if (k < 2) {
    248244                    bd->inbufBitCount++;
     
    252248                /* Add one if second bit 1, else subtract 1.  Avoids if/else */
    253249
    254                 t+=(((k+1)&2)-1);
     250                t += (((k+1) & 2) - 1);
    255251            }
    256252
    257253            /* Correct for the initial -1, to get the final symbol length */
    258254
    259             length[i]=t+1;
     255            length[i] = t + 1;
    260256        }
    261257
    262258        /* Find largest and smallest lengths in this group */
    263259
    264         minLen=maxLen=length[0];
    265         for(i = 1; i < symCount; i++) {
    266             if(length[i] > maxLen) maxLen = length[i];
    267             else if(length[i] < minLen) minLen = length[i];
     260        minLen = maxLen = length[0];
     261        for (i = 1; i < symCount; i++) {
     262            if (length[i] > maxLen) maxLen = length[i];
     263            else if (length[i] < minLen) minLen = length[i];
    268264        }
    269265
     
    279275         */
    280276
    281         hufGroup=bd->groups+j;
     277        hufGroup = bd->groups + j;
    282278        hufGroup->minLen = minLen;
    283279        hufGroup->maxLen = maxLen;
     
    287283           entry.  We do this again when using them (during symbol decoding).*/
    288284
    289         base=hufGroup->base-1;
    290         limit=hufGroup->limit-1;
     285        base = hufGroup->base - 1;
     286        limit = hufGroup->limit - 1;
    291287
    292288        /* Calculate permute[].  Concurently, initialize temp[] and limit[]. */
    293289
    294         pp=0;
    295         for(i=minLen;i<=maxLen;i++) {
    296             temp[i]=limit[i]=0;
    297             for(t=0;t<symCount;t++)
    298                 if(length[t]==i) hufGroup->permute[pp++] = t;
     290        pp = 0;
     291        for (i = minLen; i <= maxLen; i++) {
     292            temp[i] = limit[i] = 0;
     293            for (t = 0; t < symCount; t++)
     294                if (length[t] == i)
     295                    hufGroup->permute[pp++] = t;
    299296        }
    300297
    301298        /* Count symbols coded for at each bit length */
    302299
    303         for (i=0;i<symCount;i++) temp[length[i]]++;
     300        for (i = 0; i < symCount; i++) temp[length[i]]++;
    304301
    305302        /* Calculate limit[] (the largest symbol-coding value at each bit
     
    308305         * limit minus the cumulative count of symbols coded for already). */
    309306
    310         pp=t=0;
    311         for (i=minLen; i<maxLen; i++) {
    312             pp+=temp[i];
     307        pp = t = 0;
     308        for (i = minLen; i < maxLen; i++) {
     309            pp += temp[i];
    313310
    314311            /* We read the largest possible symbol size and then unget bits
     
    319316               don't affect the value>limit[length] comparison. */
    320317
    321             limit[i]= (pp << (maxLen - i)) - 1;
    322             pp<<=1;
    323             base[i+1]=pp-(t+=temp[i]);
     318            limit[i] = (pp << (maxLen - i)) - 1;
     319            pp <<= 1;
     320            t += temp[i];
     321            base[i+1] = pp - t;
    324322        }
    325323        limit[maxLen+1] = INT_MAX; /* Sentinal value for reading next sym. */
    326         limit[maxLen]=pp+temp[maxLen]-1;
    327         base[minLen]=0;
     324        limit[maxLen] = pp + temp[maxLen] - 1;
     325        base[minLen] = 0;
    328326    }
    329327
     
    334332    /* Initialize symbol occurrence counters and symbol Move To Front table */
    335333
    336     for(i=0;i<256;i++) {
     334    for (i = 0; i < 256; i++) {
    337335        byteCount[i] = 0;
    338         mtfSymbol[i]=(unsigned char)i;
     336        mtfSymbol[i] = (unsigned char)i;
    339337    }
    340338
    341339    /* Loop through compressed symbols. */
    342340
    343     runPos=dbufCount=selector=0;
    344     for(;;) {
     341    runPos = dbufCount = selector = 0;
     342    for (;;) {
    345343
    346344        /* fetch next Huffman coding group from list. */
    347345
    348         symCount=GROUP_SIZE-1;
    349         if(selector>=nSelectors) return RETVAL_DATA_ERROR;
    350         hufGroup=bd->groups+selectors[selector++];
    351         base=hufGroup->base-1;
    352         limit=hufGroup->limit-1;
    353 continue_this_group:
     346        symCount = GROUP_SIZE - 1;
     347        if (selector >= nSelectors) return RETVAL_DATA_ERROR;
     348        hufGroup = bd->groups + selectors[selector++];
     349        base = hufGroup->base - 1;
     350        limit = hufGroup->limit - 1;
     351 continue_this_group:
    354352
    355353        /* Read next Huffman-coded symbol. */
     
    362360           inline (falling back to a call to get_bits if the buffer runs
    363361           dry).  The following (up to got_huff_bits:) is equivalent to
    364            j=get_bits(bd,hufGroup->maxLen);
     362           j = get_bits(bd, hufGroup->maxLen);
    365363         */
    366364
    367         while (bd->inbufBitCount<hufGroup->maxLen) {
    368             if(bd->inbufPos==bd->inbufCount) {
    369                 j = get_bits(bd,hufGroup->maxLen);
     365        while (bd->inbufBitCount < hufGroup->maxLen) {
     366            if (bd->inbufPos == bd->inbufCount) {
     367                j = get_bits(bd, hufGroup->maxLen);
    370368                goto got_huff_bits;
    371369            }
    372             bd->inbufBits=(bd->inbufBits<<8)|bd->inbuf[bd->inbufPos++];
    373             bd->inbufBitCount+=8;
     370            bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++];
     371            bd->inbufBitCount += 8;
    374372        };
    375         bd->inbufBitCount-=hufGroup->maxLen;
    376         j = (bd->inbufBits>>bd->inbufBitCount)&((1<<hufGroup->maxLen)-1);
    377 
    378 got_huff_bits:
     373        bd->inbufBitCount -= hufGroup->maxLen;
     374        j = (bd->inbufBits >> bd->inbufBitCount) & ((1 << hufGroup->maxLen) - 1);
     375
     376 got_huff_bits:
    379377
    380378        /* Figure how how many bits are in next symbol and unget extras */
    381379
    382         i=hufGroup->minLen;
    383         while(j>limit[i]) ++i;
     380        i = hufGroup->minLen;
     381        while (j > limit[i]) ++i;
    384382        bd->inbufBitCount += (hufGroup->maxLen - i);
    385383
    386384        /* Huffman decode value to get nextSym (with bounds checking) */
    387385
    388         if ((i > hufGroup->maxLen)
    389             || (((unsigned)(j=(j>>(hufGroup->maxLen-i))-base[i]))
    390                 >= MAX_SYMBOLS))
     386        if (i > hufGroup->maxLen)
     387            return RETVAL_DATA_ERROR;
     388        j = (j >> (hufGroup->maxLen - i)) - base[i];
     389        if ((unsigned)j >= MAX_SYMBOLS)
    391390            return RETVAL_DATA_ERROR;
    392391        nextSym = hufGroup->permute[j];
     
    397396           how many times to repeat the last literal. */
    398397
    399         if (((unsigned)nextSym) <= SYMBOL_RUNB) { /* RUNA or RUNB */
     398        if ((unsigned)nextSym <= SYMBOL_RUNB) { /* RUNA or RUNB */
    400399
    401400            /* If this is the start of a new run, zero out counter */
    402401
    403             if(!runPos) {
     402            if (!runPos) {
    404403                runPos = 1;
    405404                t = 0;
     
    415414
    416415            t += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */
    417             if(runPos < dbufSize) runPos <<= 1;
     416            if (runPos < dbufSize) runPos <<= 1;
    418417            goto end_of_huffman_loop;
    419418        }
     
    424423           literal used is the one at the head of the mtfSymbol array.) */
    425424
    426         if(runPos) {
    427             runPos=0;
    428             if(dbufCount+t>=dbufSize) return RETVAL_DATA_ERROR;
     425        if (runPos) {
     426            runPos = 0;
     427            if (dbufCount + t >= dbufSize) return RETVAL_DATA_ERROR;
    429428
    430429            uc = symToByte[mtfSymbol[0]];
    431430            byteCount[uc] += t;
    432             while(t--) dbuf[dbufCount++]=uc;
     431            while (t--) dbuf[dbufCount++] = uc;
    433432        }
    434433
    435434        /* Is this the terminating symbol? */
    436435
    437         if(nextSym>symTotal) break;
     436        if (nextSym > symTotal) break;
    438437
    439438        /* At this point, nextSym indicates a new literal character.  Subtract
     
    445444           2 non-literal nextSym values equals -1.) */
    446445
    447         if(dbufCount>=dbufSize) return RETVAL_DATA_ERROR;
     446        if (dbufCount >= dbufSize) return RETVAL_DATA_ERROR;
    448447        i = nextSym - 1;
    449448        uc = mtfSymbol[i];
     
    458457        } while (--i);
    459458        mtfSymbol[0] = uc;
    460         uc=symToByte[uc];
     459        uc = symToByte[uc];
    461460
    462461        /* We have our literal byte.  Save it into dbuf. */
    463462
    464463        byteCount[uc]++;
    465         dbuf[dbufCount++] = (unsigned int)uc;
     464        dbuf[dbufCount++] = (unsigned)uc;
    466465
    467466        /* Skip group initialization if we're not done with this group.  Done
    468467         * this way to avoid compiler warning. */
    469468
    470 end_of_huffman_loop:
    471         if(symCount--) goto continue_this_group;
     469 end_of_huffman_loop:
     470        if (symCount--) goto continue_this_group;
    472471    }
    473472
    474473    /* At this point, we've read all the Huffman-coded symbols (and repeated
    475        runs) for this block from the input stream, and decoded them into the
     474       runs) for this block from the input stream, and decoded them into the
    476475       intermediate buffer.  There are dbufCount many decoded bytes in dbuf[].
    477476       Now undo the Burrows-Wheeler transform on dbuf.
     
    481480    /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
    482481
    483     j=0;
    484     for(i=0;i<256;i++) {
    485         k=j+byteCount[i];
     482    j = 0;
     483    for (i = 0; i < 256; i++) {
     484        k = j + byteCount[i];
    486485        byteCount[i] = j;
    487         j=k;
     486        j = k;
    488487    }
    489488
    490489    /* Figure out what order dbuf would be in if we sorted it. */
    491490
    492     for (i=0;i<dbufCount;i++) {
    493         uc=(unsigned char)(dbuf[i] & 0xff);
     491    for (i = 0; i < dbufCount; i++) {
     492        uc = (unsigned char)(dbuf[i] & 0xff);
    494493        dbuf[byteCount[uc]] |= (i << 8);
    495494        byteCount[uc]++;
     
    500499       it doesn't qualify as a run (hence writeRunCountdown=5). */
    501500
    502     if(dbufCount) {
    503         if(origPtr>=dbufCount) return RETVAL_DATA_ERROR;
    504         bd->writePos=dbuf[origPtr];
    505         bd->writeCurrent=(unsigned char)(bd->writePos&0xff);
    506         bd->writePos>>=8;
    507         bd->writeRunCountdown=5;
    508     }
    509     bd->writeCount=dbufCount;
     501    if (dbufCount) {
     502        if (origPtr >= dbufCount) return RETVAL_DATA_ERROR;
     503        bd->writePos = dbuf[origPtr];
     504        bd->writeCurrent = (unsigned char)(bd->writePos & 0xff);
     505        bd->writePos >>= 8;
     506        bd->writeRunCountdown = 5;
     507    }
     508    bd->writeCount = dbufCount;
    510509
    511510    return RETVAL_OK;
     
    519518*/
    520519
    521 static int read_bunzip(bunzip_data *bd, char *outbuf, int len)
     520int read_bunzip(bunzip_data *bd, char *outbuf, int len)
    522521{
    523     const unsigned int *dbuf;
    524     int pos,current,previous,gotcount;
     522    const unsigned *dbuf;
     523    int pos, current, previous, gotcount;
    525524
    526525    /* If last read was short due to end of file, return last block now */
    527     if(bd->writeCount<0) return bd->writeCount;
     526    if (bd->writeCount < 0) return bd->writeCount;
    528527
    529528    gotcount = 0;
    530     dbuf=bd->dbuf;
    531     pos=bd->writePos;
    532     current=bd->writeCurrent;
     529    dbuf = bd->dbuf;
     530    pos = bd->writePos;
     531    current = bd->writeCurrent;
    533532
    534533    /* We will always have pending decoded data to write into the output
     
    544543        /* Loop outputting bytes */
    545544
    546         for(;;) {
     545        for (;;) {
    547546
    548547            /* If the output buffer is full, snapshot state and return */
    549548
    550             if(gotcount >= len) {
    551                 bd->writePos=pos;
    552                 bd->writeCurrent=current;
     549            if (gotcount >= len) {
     550                bd->writePos  =pos;
     551                bd->writeCurrent = current;
    553552                bd->writeCopies++;
    554553                return len;
     
    558557
    559558            outbuf[gotcount++] = current;
    560             bd->writeCRC=(((bd->writeCRC)<<8)
    561                           ^bd->crc32Table[((bd->writeCRC)>>24)^current]);
     559            bd->writeCRC = (bd->writeCRC << 8)
     560                          ^ bd->crc32Table[(bd->writeCRC >> 24) ^ current];
    562561
    563562            /* Loop now if we're outputting multiple copies of this byte */
     
    567566                continue;
    568567            }
    569 decode_next_byte:
     568 decode_next_byte:
    570569            if (!bd->writeCount--) break;
    571570            /* Follow sequence vector to undo Burrows-Wheeler transform */
    572             previous=current;
    573             pos=dbuf[pos];
    574             current=pos&0xff;
    575             pos>>=8;
     571            previous = current;
     572            pos = dbuf[pos];
     573            current = pos & 0xff;
     574            pos >>= 8;
    576575
    577576            /* After 3 consecutive copies of the same byte, the 4th is a repeat
     
    579578             * of counting up because testing for non-zero is faster */
    580579
    581             if(--bd->writeRunCountdown) {
    582                 if(current!=previous) bd->writeRunCountdown=4;
     580            if (--bd->writeRunCountdown) {
     581                if (current != previous)
     582                    bd->writeRunCountdown = 4;
    583583            } else {
    584584
    585585                /* We have a repeated run, this byte indicates the count */
    586586
    587                 bd->writeCopies=current;
    588                 current=previous;
    589                 bd->writeRunCountdown=5;
     587                bd->writeCopies = current;
     588                current = previous;
     589                bd->writeRunCountdown = 5;
    590590
    591591                /* Sometimes there are just 3 bytes (run length 0) */
    592592
    593                 if(!bd->writeCopies) goto decode_next_byte;
     593                if (!bd->writeCopies) goto decode_next_byte;
    594594
    595595                /* Subtract the 1 copy we'd output anyway to get extras */
     
    601601        /* Decompression of this block completed successfully */
    602602
    603         bd->writeCRC=~bd->writeCRC;
    604         bd->totalCRC=((bd->totalCRC<<1) | (bd->totalCRC>>31)) ^ bd->writeCRC;
     603        bd->writeCRC = ~bd->writeCRC;
     604        bd->totalCRC = ((bd->totalCRC << 1) | (bd->totalCRC >> 31)) ^ bd->writeCRC;
    605605
    606606        /* If this block had a CRC error, force file level CRC error. */
    607607
    608         if(bd->writeCRC!=bd->headerCRC) {
    609             bd->totalCRC=bd->headerCRC+1;
     608        if (bd->writeCRC != bd->headerCRC) {
     609            bd->totalCRC = bd->headerCRC+1;
    610610            return RETVAL_LAST_BLOCK;
    611611        }
     
    615615    /* (previous is just a convenient unused temp variable here) */
    616616
    617     previous=get_next_block(bd);
    618     if(previous) {
    619         bd->writeCount=previous;
    620         return (previous!=RETVAL_LAST_BLOCK) ? previous : gotcount;
    621     }
    622     bd->writeCRC=~0;
    623     pos=bd->writePos;
    624     current=bd->writeCurrent;
     617    previous = get_next_block(bd);
     618    if (previous) {
     619        bd->writeCount = previous;
     620        return (previous != RETVAL_LAST_BLOCK) ? previous : gotcount;
     621    }
     622    bd->writeCRC = ~0;
     623    pos = bd->writePos;
     624    current = bd->writeCurrent;
    625625    goto decode_next_byte;
    626626}
     627
    627628
    628629/* Allocate the structure, read file header.  If in_fd==-1, inbuf must contain
     
    630631   ignored, and data is read from file handle into temporary buffer. */
    631632
    632 static int start_bunzip(bunzip_data **bdp, int in_fd, unsigned char *inbuf,
     633/* Because bunzip2 is used for help text unpacking, and because bb_show_usage()
     634   should work for NOFORK applets too, we must be extremely careful to not leak
     635   any allocations! */
     636
     637int start_bunzip(bunzip_data **bdp, int in_fd, const unsigned char *inbuf,
    633638                        int len)
    634639{
    635640    bunzip_data *bd;
    636     unsigned int i;
    637     const unsigned int BZh0=(((unsigned int)'B')<<24)+(((unsigned int)'Z')<<16)
    638                             +(((unsigned int)'h')<<8)+(unsigned int)'0';
     641    unsigned i;
     642    enum {
     643        BZh0 = ('B' << 24) + ('Z' << 16) + ('h' << 8) + '0'
     644    };
    639645
    640646    /* Figure out how much data to allocate */
    641647
    642     i=sizeof(bunzip_data);
    643     if(in_fd!=-1) i+=IOBUF_SIZE;
     648    i = sizeof(bunzip_data);
     649    if (in_fd != -1) i += IOBUF_SIZE;
    644650
    645651    /* Allocate bunzip_data.  Most fields initialize to zero. */
    646652
    647     bd=*bdp=xzalloc(i);
     653    bd = *bdp = xzalloc(i);
    648654
    649655    /* Setup input buffer */
    650656
    651     if(-1==(bd->in_fd=in_fd)) {
    652         bd->inbuf=inbuf;
    653         bd->inbufCount=len;
    654     } else bd->inbuf=(unsigned char *)(bd+1);
     657    bd->in_fd = in_fd;
     658    if (-1 == in_fd) {
     659        /* in this case, bd->inbuf is read-only */
     660        bd->inbuf = (void*)inbuf; /* cast away const-ness */
     661        bd->inbufCount = len;
     662    } else
     663        bd->inbuf = (unsigned char *)(bd + 1);
    655664
    656665    /* Init the CRC32 table (big endian) */
    657666
    658     bd->crc32Table = bb_crc32_filltable(1);
     667    crc32_filltable(bd->crc32Table, 1);
    659668
    660669    /* Setup for I/O error handling via longjmp */
    661670
    662     i=setjmp(bd->jmpbuf);
    663     if(i) return i;
     671    i = setjmp(bd->jmpbuf);
     672    if (i) return i;
    664673
    665674    /* Ensure that file starts with "BZh['1'-'9']." */
    666675
    667     i = get_bits(bd,32);
    668     if (((unsigned int)(i-BZh0-1)) >= 9) return RETVAL_NOT_BZIP_DATA;
     676    i = get_bits(bd, 32);
     677    if ((unsigned)(i - BZh0 - 1) >= 9) return RETVAL_NOT_BZIP_DATA;
    669678
    670679    /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of
    671680       uncompressed data.  Allocate intermediate buffer for block. */
    672681
    673     bd->dbufSize=100000*(i-BZh0);
    674 
    675     bd->dbuf=xmalloc(bd->dbufSize * sizeof(int));
     682    bd->dbufSize = 100000 * (i - BZh0);
     683
     684    /* Cannot use xmalloc - may leak bd in NOFORK case! */
     685    bd->dbuf = malloc_or_warn(bd->dbufSize * sizeof(int));
     686    if (!bd->dbuf) {
     687        free(bd);
     688        xfunc_die();
     689    }
    676690    return RETVAL_OK;
    677691}
    678692
    679 /* Example usage: decompress src_fd to dst_fd.  (Stops at end of bzip data,
    680    not end of file.) */
    681 
    682 int uncompressStream(int src_fd, int dst_fd)
     693void dealloc_bunzip(bunzip_data *bd)
    683694{
     695    free(bd->dbuf);
     696    free(bd);
     697}
     698
     699
     700/* Decompress src_fd to dst_fd.  Stops at end of bzip data, not end of file. */
     701
     702USE_DESKTOP(long long) int
     703unpack_bz2_stream(int src_fd, int dst_fd)
     704{
     705    USE_DESKTOP(long long total_written = 0;)
    684706    char *outbuf;
    685707    bunzip_data *bd;
    686708    int i;
    687709
    688     outbuf=xmalloc(IOBUF_SIZE);
    689     if(!(i=start_bunzip(&bd,src_fd,0,0))) {
    690         for(;;) {
    691             if((i=read_bunzip(bd,outbuf,IOBUF_SIZE)) <= 0) break;
    692             if(i!=write(dst_fd,outbuf,i)) {
    693                 i=RETVAL_UNEXPECTED_OUTPUT_EOF;
     710    outbuf = xmalloc(IOBUF_SIZE);
     711    i = start_bunzip(&bd, src_fd, NULL, 0);
     712    if (!i) {
     713        for (;;) {
     714            i = read_bunzip(bd, outbuf, IOBUF_SIZE);
     715            if (i <= 0) break;
     716            if (i != safe_write(dst_fd, outbuf, i)) {
     717                i = RETVAL_UNEXPECTED_OUTPUT_EOF;
    694718                break;
    695719            }
     720            USE_DESKTOP(total_written += i;)
    696721        }
    697722    }
     
    699724    /* Check CRC and release memory */
    700725
    701     if(i==RETVAL_LAST_BLOCK) {
    702         if (bd->headerCRC!=bd->totalCRC) {
    703             bb_error_msg("Data integrity error when decompressing.");
     726    if (i == RETVAL_LAST_BLOCK) {
     727        if (bd->headerCRC != bd->totalCRC) {
     728            bb_error_msg("data integrity error when decompressing");
    704729        } else {
    705             i=RETVAL_OK;
    706         }
    707     } else if (i==RETVAL_UNEXPECTED_OUTPUT_EOF) {
    708         bb_error_msg("Compressed file ends unexpectedly");
     730            i = RETVAL_OK;
     731        }
     732    } else if (i == RETVAL_UNEXPECTED_OUTPUT_EOF) {
     733        bb_error_msg("compressed file ends unexpectedly");
    709734    } else {
    710         bb_error_msg("Decompression failed");
    711     }
    712     free(bd->dbuf);
    713     free(bd);
     735        bb_error_msg("decompression failed");
     736    }
     737    dealloc_bunzip(bd);
    714738    free(outbuf);
    715739
    716     return i;
     740    return i ? i : USE_DESKTOP(total_written) + 0;
    717741}
    718742
    719743#ifdef TESTING
    720744
    721 static char * const bunzip_errors[]={NULL,"Bad file checksum","Not bzip data",
    722         "Unexpected input EOF","Unexpected output EOF","Data error",
    723          "Out of memory","Obsolete (pre 0.9.5) bzip format not supported."};
     745static char *const bunzip_errors[] = {
     746    NULL, "Bad file checksum", "Not bzip data",
     747    "Unexpected input EOF", "Unexpected output EOF", "Data error",
     748    "Out of memory", "Obsolete (pre 0.9.5) bzip format not supported"
     749};
    724750
    725751/* Dumb little test thing, decompress stdin to stdout */
    726 int main(int argc, char *argv[])
     752int main(int argc, char **argv)
    727753{
    728     int i=uncompressStream(0,1);
     754    int i = unpack_bz2_stream(0, 1);
    729755    char c;
    730756
    731     if(i) fprintf(stderr,"%s\n", bunzip_errors[-i]);
    732     else if(read(0,&c,1)) fprintf(stderr,"Trailing garbage ignored\n");
     757    if (i < 0)
     758        fprintf(stderr,"%s\n", bunzip_errors[-i]);
     759    else if (read(0, &c, 1))
     760        fprintf(stderr,"Trailing garbage ignored\n");
    733761    return -i;
    734762}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/decompress_uncompress.c

    r902 r1765  
     1/* vi: set sw=4 ts=4: */
    12#include "libbb.h"
    23
     
    67 * (see disclaimer below)
    78 */
    8 
    99
    1010/* (N)compress42.c - File compression ala IEEE Computer, Mar 1992.
     
    2626 *
    2727 */
    28 #include <stdio.h>
    29 #include <string.h>
    30 #include <unistd.h>
    3128
    3229/* Default input buffer size */
     
    3734
    3835/* Defines for third byte of header */
    39 #define MAGIC_1     (char_type)'\037'   /* First byte of compressed file               */
    40 #define MAGIC_2     (char_type)'\235'   /* Second byte of compressed file              */
    41 #define BIT_MASK    0x1f    /* Mask for 'number of compresssion bits'       */
    42                             /* Masks 0x20 and 0x40 are free.                */
    43                             /* I think 0x20 should mean that there is       */
    44                             /* a fourth header byte (for expansion).        */
    45 #define BLOCK_MODE  0x80    /* Block compresssion if table is full and      */
    46             /* compression rate is dropping flush tables    */
    47             /* the next two codes should not be changed lightly, as they must not   */
    48             /* lie within the contiguous general code space.                        */
    49 #define FIRST   257     /* first free entry                             */
    50 #define CLEAR   256     /* table clear output code                      */
    51 
    52 #define INIT_BITS 9     /* initial number of bits/code */
     36#define BIT_MASK        0x1f    /* Mask for 'number of compresssion bits'       */
     37                                /* Masks 0x20 and 0x40 are free.                */
     38                                /* I think 0x20 should mean that there is       */
     39                                /* a fourth header byte (for expansion).        */
     40#define BLOCK_MODE      0x80    /* Block compression if table is full and       */
     41                                /* compression rate is dropping flush tables    */
     42                                /* the next two codes should not be changed lightly, as they must not   */
     43                                /* lie within the contiguous general code space.                        */
     44#define FIRST   257     /* first free entry */
     45#define CLEAR   256     /* table clear output code */
     46
     47#define INIT_BITS 9     /* initial number of bits/code */
    5348
    5449
    5550/* machine variants which require cc -Dmachine:  pdp11, z8000, DOS */
    56 #define FAST
    57 
    58 #define HBITS       17  /* 50% occupancy */
    59 #define HSIZE      (1<<HBITS)
    60 #define HMASK      (HSIZE-1)
    61 #define HPRIME       9941
    62 #define BITS           16
    63 #undef  MAXSEG_64K
    64 #define MAXCODE(n)  (1L << (n))
    65 
    66 /* Block compress mode -C compatible with 2.0 */
    67 static int block_mode = BLOCK_MODE;
    68 
    69 /* user settable max # bits/code */
    70 static int maxbits = BITS;
    71 
    72 #define htabof(i)               htab[i]
    73 #define codetabof(i)            codetab[i]
    74 #define tab_prefixof(i)         codetabof(i)
    75 #define tab_suffixof(i)         ((unsigned char *)(htab))[i]
    76 #define de_stack                ((unsigned char *)&(htab[HSIZE-1]))
    77 #define clear_htab()            memset(htab, -1, HSIZE)
    78 #define clear_tab_prefixof()    memset(codetab, 0, 256);
    79 
     51#define HBITS      17   /* 50% occupancy */
     52#define HSIZE      (1<<HBITS)
     53#define HMASK      (HSIZE-1)    /* unused */
     54#define HPRIME     9941         /* unused */
     55#define BITS       16
     56#define BITS_STR   "16"
     57#undef  MAXSEG_64K              /* unused */
     58#define MAXCODE(n) (1L << (n))
     59
     60#define htabof(i)               htab[i]
     61#define codetabof(i)            codetab[i]
     62#define tab_prefixof(i)         codetabof(i)
     63#define tab_suffixof(i)         ((unsigned char *)(htab))[i]
     64#define de_stack                ((unsigned char *)&(htab[HSIZE-1]))
     65#define clear_tab_prefixof()    memset(codetab, 0, 256)
    8066
    8167/*
    8268 * Decompress stdin to stdout.  This routine adapts to the codes in the
    8369 * file building the "string" table on-the-fly; requiring no table to
    84  * be stored in the compressed file.  The tables used herein are shared
    85  * with those of the compress() routine.  See the definitions above.
     70 * be stored in the compressed file.
    8671 */
    8772
    88 int uncompress(int fd_in, int fd_out)
     73USE_DESKTOP(long long) int
     74uncompress(int fd_in, int fd_out)
    8975{
     76    USE_DESKTOP(long long total_written = 0;)
     77    USE_DESKTOP(long long) int retval = -1;
    9078    unsigned char *stackp;
    91     long int code;
     79    long code;
    9280    int finchar;
    93     long int oldcode;
    94     long int incode;
     81    long oldcode;
     82    long incode;
    9583    int inbits;
    9684    int posbits;
     
    9886    int insize;
    9987    int bitmask;
    100     long int free_ent;
    101     long int maxcode;
    102     long int maxmaxcode;
     88    long free_ent;
     89    long maxcode;
     90    long maxmaxcode;
    10391    int n_bits;
    10492    int rsize = 0;
    105     RESERVE_CONFIG_UBUFFER(inbuf, IBUFSIZ + 64);
    106     RESERVE_CONFIG_UBUFFER(outbuf, OBUFSIZ + 2048);
    107     unsigned char htab[HSIZE];
    108     unsigned short codetab[HSIZE];
    109     memset(inbuf, 0, IBUFSIZ + 64);
    110     memset(outbuf, 0, OBUFSIZ + 2048);
     93    unsigned char *inbuf; /* were eating insane amounts of stack - */
     94    unsigned char *outbuf; /* bad for some embedded targets */
     95    unsigned char *htab;
     96    unsigned short *codetab;
     97
     98    /* Hmm, these were statics - why?! */
     99    /* user settable max # bits/code */
     100    int maxbits; /* = BITS; */
     101    /* block compress mode -C compatible with 2.0 */
     102    int block_mode; /* = BLOCK_MODE; */
     103
     104    inbuf = xzalloc(IBUFSIZ + 64);
     105    outbuf = xzalloc(OBUFSIZ + 2048);
     106    htab = xzalloc(HSIZE);  /* wsn't zeroed out before, maybe can xmalloc? */
     107    codetab = xzalloc(HSIZE * sizeof(codetab[0]));
    111108
    112109    insize = 0;
    113110
    114     inbuf[0] = bb_xread_char(fd_in);
     111    /* xread isn't good here, we have to return - caller may want
     112     * to do some cleanup (e.g. delete incomplete unpacked file etc) */
     113    if (full_read(fd_in, inbuf, 1) != 1) {
     114        bb_error_msg("short read");
     115        goto err;
     116    }
    115117
    116118    maxbits = inbuf[0] & BIT_MASK;
     
    119121
    120122    if (maxbits > BITS) {
    121         bb_error_msg("compressed with %d bits, can only handle %d bits", maxbits,
    122                   BITS);
    123         return -1;
     123        bb_error_msg("compressed with %d bits, can only handle "
     124                BITS_STR" bits", maxbits);
     125        goto err;
    124126    }
    125127
    126     maxcode = MAXCODE(n_bits = INIT_BITS) - 1;
    127     bitmask = (1 << n_bits) - 1;
     128    n_bits = INIT_BITS;
     129    maxcode = MAXCODE(INIT_BITS) - 1;
     130    bitmask = (1 << INIT_BITS) - 1;
    128131    oldcode = -1;
    129132    finchar = 0;
     
    134137
    135138    /* As above, initialize the first 256 entries in the table. */
    136     clear_tab_prefixof();
     139    /*clear_tab_prefixof(); - done by xzalloc */
    137140
    138141    for (code = 255; code >= 0; --code) {
     
    141144
    142145    do {
    143       resetbuf:;
     146 resetbuf:
    144147        {
    145148            int i;
     
    147150            int o;
    148151
    149             e = insize - (o = (posbits >> 3));
     152            o = posbits >> 3;
     153            e = insize - o;
    150154
    151155            for (i = 0; i < e; ++i)
     
    158162        if (insize < (int) (IBUFSIZ + 64) - IBUFSIZ) {
    159163            rsize = safe_read(fd_in, inbuf + insize, IBUFSIZ);
     164//error check??
    160165            insize += rsize;
    161166        }
     
    182187                unsigned char *p = &inbuf[posbits >> 3];
    183188
    184                 code =
    185                     ((((long) (p[0])) | ((long) (p[1]) << 8) |
    186                       ((long) (p[2]) << 16)) >> (posbits & 0x7)) & bitmask;
     189                code = ((((long) (p[0])) | ((long) (p[1]) << 8) |
     190                         ((long) (p[2]) << 16)) >> (posbits & 0x7)) & bitmask;
    187191            }
    188192            posbits += n_bits;
     
    190194
    191195            if (oldcode == -1) {
    192                 outbuf[outpos++] = (unsigned char) (finchar =
    193                                                 (int) (oldcode = code));
     196                oldcode = code;
     197                finchar = (int) oldcode;
     198                outbuf[outpos++] = (unsigned char) finchar;
    194199                continue;
    195200            }
     
    202207                     ((n_bits << 3) -
    203208                      (posbits - 1 + (n_bits << 3)) % (n_bits << 3)));
    204                 maxcode = MAXCODE(n_bits = INIT_BITS) - 1;
    205                 bitmask = (1 << n_bits) - 1;
     209                n_bits = INIT_BITS;
     210                maxcode = MAXCODE(INIT_BITS) - 1;
     211                bitmask = (1 << INIT_BITS) - 1;
    206212                goto resetbuf;
    207213            }
     
    223229                         (posbits & 07));
    224230                    bb_error_msg("uncompress: corrupt input");
    225                     return -1;
     231                    goto err;
    226232                }
    227233
     
    231237
    232238            /* Generate output characters in reverse order */
    233             while ((long int) code >= (long int) 256) {
     239            while ((long) code >= (long) 256) {
    234240                *--stackp = tab_suffixof(code);
    235241                code = tab_prefixof(code);
    236242            }
    237243
    238             *--stackp = (unsigned char) (finchar = tab_suffixof(code));
     244            finchar = tab_suffixof(code);
     245            *--stackp = (unsigned char) finchar;
    239246
    240247            /* And put them out in forward order */
     
    242249                int i;
    243250
    244                 if (outpos + (i = (de_stack - stackp)) >= OBUFSIZ) {
     251                i = de_stack - stackp;
     252                if (outpos + i >= OBUFSIZ) {
    245253                    do {
    246254                        if (i > OBUFSIZ - outpos) {
     
    254262
    255263                        if (outpos >= OBUFSIZ) {
    256                             write(fd_out, outbuf, outpos);
     264                            full_write(fd_out, outbuf, outpos);
     265//error check??
     266                            USE_DESKTOP(total_written += outpos;)
    257267                            outpos = 0;
    258268                        }
    259269                        stackp += i;
    260                     } while ((i = (de_stack - stackp)) > 0);
     270                        i = de_stack - stackp;
     271                    } while (i > 0);
    261272                } else {
    262273                    memcpy(outbuf + outpos, stackp, i);
     
    266277
    267278            /* Generate the new entry. */
    268             if ((code = free_ent) < maxmaxcode) {
     279            code = free_ent;
     280            if (code < maxmaxcode) {
    269281                tab_prefixof(code) = (unsigned short) oldcode;
    270282                tab_suffixof(code) = (unsigned char) finchar;
     
    279291
    280292    if (outpos > 0) {
    281         write(fd_out, outbuf, outpos);
     293        full_write(fd_out, outbuf, outpos);
     294//error check??
     295        USE_DESKTOP(total_written += outpos;)
    282296    }
    283297
    284     RELEASE_CONFIG_BUFFER(inbuf);
    285     RELEASE_CONFIG_BUFFER(outbuf);
    286     return 0;
     298    retval = USE_DESKTOP(total_written) + 0;
     299 err:
     300    free(inbuf);
     301    free(outbuf);
     302    free(htab);
     303    free(codetab);
     304    return retval;
    287305}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/decompress_unlzma.c

    r821 r1765  
    1 /* vi:set ts=4: */
     1/* vi: set sw=4 ts=4: */
    22/*
    33 * Small lzma deflate implementation.
     
    1313#include "unarchive.h"
    1414
    15 #ifdef CONFIG_FEATURE_LZMA_FAST
    16 #  define speed_inline ATTRIBUTE_ALWAYS_INLINE
     15#if ENABLE_FEATURE_LZMA_FAST
     16#  define speed_inline ALWAYS_INLINE
    1717#else
    1818#  define speed_inline
     
    2323    int fd;
    2424    uint8_t *ptr;
    25     uint8_t *buffer;
     25
     26/* Was keeping rc on stack in unlzma and separately allocating buffer,
     27 * but with "buffer 'attached to' allocated rc" code is smaller: */
     28    /* uint8_t *buffer; */
     29#define RC_BUFFER ((uint8_t*)(rc+1))
     30
    2631    uint8_t *buffer_end;
    27     int buffer_size;
     32
     33/* Had provisions for variable buffer, but we don't need it here */
     34    /* int buffer_size; */
     35#define RC_BUFFER_SIZE 0x10000
     36
    2837    uint32_t code;
    2938    uint32_t range;
     
    3140} rc_t;
    3241
    33 
    3442#define RC_TOP_BITS 24
    3543#define RC_MOVE_BITS 5
     
    4048static void rc_read(rc_t * rc)
    4149{
    42     rc->buffer_size = read(rc->fd, rc->buffer, rc->buffer_size);
    43     if (rc->buffer_size <= 0)
     50    int buffer_size = safe_read(rc->fd, RC_BUFFER, RC_BUFFER_SIZE);
     51    if (buffer_size <= 0)
    4452        bb_error_msg_and_die("unexpected EOF");
    45     rc->ptr = rc->buffer;
    46     rc->buffer_end = rc->buffer + rc->buffer_size;
     53    rc->ptr = RC_BUFFER;
     54    rc->buffer_end = RC_BUFFER + buffer_size;
    4755}
    4856
    4957/* Called once */
    50 static void rc_init(rc_t * rc, int fd, int buffer_size)
     58static rc_t* rc_init(int fd) /*, int buffer_size) */
    5159{
    5260    int i;
     61    rc_t* rc;
     62
     63    rc = xmalloc(sizeof(rc_t) + RC_BUFFER_SIZE);
    5364
    5465    rc->fd = fd;
    55     rc->buffer = xmalloc(buffer_size);
    56     rc->buffer_size = buffer_size;
    57     rc->buffer_end = rc->buffer + rc->buffer_size;
     66    /* rc->buffer_size = buffer_size; */
     67    rc->buffer_end = RC_BUFFER + RC_BUFFER_SIZE;
    5868    rc->ptr = rc->buffer_end;
    5969
     
    6575        rc->code = (rc->code << 8) | *rc->ptr++;
    6676    }
    67 }
    68 
    69 /* Called once. TODO: bb_maybe_free() */
    70 static ATTRIBUTE_ALWAYS_INLINE void rc_free(rc_t * rc)
     77    return rc;
     78}
     79
     80/* Called once  */
     81static ALWAYS_INLINE void rc_free(rc_t * rc)
    7182{
    7283    if (ENABLE_FEATURE_CLEAN_UP)
    73         free(rc->buffer);
     84        free(rc);
    7485}
    7586
     
    8293    rc->code = (rc->code << 8) | *rc->ptr++;
    8394}
    84 static ATTRIBUTE_ALWAYS_INLINE void rc_normalize(rc_t * rc)
     95static ALWAYS_INLINE void rc_normalize(rc_t * rc)
    8596{
    8697    if (rc->range < (1 << RC_TOP_BITS)) {
     
    89100}
    90101
    91 /* Called 9 times */
     102/* rc_is_bit_0 is called 9 times */
    92103/* Why rc_is_bit_0_helper exists?
    93  * Because we want to always expose (rc->code < rc->bound) to optimizer
     104 * Because we want to always expose (rc->code < rc->bound) to optimizer.
     105 * Thus rc_is_bit_0 is always inlined, and rc_is_bit_0_helper is inlined
     106 * only if we compile for speed.
    94107 */
    95108static speed_inline uint32_t rc_is_bit_0_helper(rc_t * rc, uint16_t * p)
     
    99112    return rc->bound;
    100113}
    101 static ATTRIBUTE_ALWAYS_INLINE int rc_is_bit_0(rc_t * rc, uint16_t * p)
     114static ALWAYS_INLINE int rc_is_bit_0(rc_t * rc, uint16_t * p)
    102115{
    103116    uint32_t t = rc_is_bit_0_helper(rc, p);
     
    133146
    134147/* Called once */
    135 static ATTRIBUTE_ALWAYS_INLINE int rc_direct_bit(rc_t * rc)
     148static ALWAYS_INLINE int rc_direct_bit(rc_t * rc)
    136149{
    137150    rc_normalize(rc);
     
    164177
    165178
    166 #define LZMA_BASE_SIZE 1846
    167 #define LZMA_LIT_SIZE 768
    168 
    169 #define LZMA_NUM_POS_BITS_MAX 4
    170 
    171 #define LZMA_LEN_NUM_LOW_BITS 3
    172 #define LZMA_LEN_NUM_MID_BITS 3
    173 #define LZMA_LEN_NUM_HIGH_BITS 8
    174 
    175 #define LZMA_LEN_CHOICE 0
    176 #define LZMA_LEN_CHOICE_2 (LZMA_LEN_CHOICE + 1)
    177 #define LZMA_LEN_LOW (LZMA_LEN_CHOICE_2 + 1)
    178 #define LZMA_LEN_MID (LZMA_LEN_LOW \
    179               + (1 << (LZMA_NUM_POS_BITS_MAX + LZMA_LEN_NUM_LOW_BITS)))
    180 #define LZMA_LEN_HIGH (LZMA_LEN_MID \
    181                +(1 << (LZMA_NUM_POS_BITS_MAX + LZMA_LEN_NUM_MID_BITS)))
    182 #define LZMA_NUM_LEN_PROBS (LZMA_LEN_HIGH + (1 << LZMA_LEN_NUM_HIGH_BITS))
    183 
    184 #define LZMA_NUM_STATES 12
    185 #define LZMA_NUM_LIT_STATES 7
    186 
    187 #define LZMA_START_POS_MODEL_INDEX 4
    188 #define LZMA_END_POS_MODEL_INDEX 14
    189 #define LZMA_NUM_FULL_DISTANCES (1 << (LZMA_END_POS_MODEL_INDEX >> 1))
    190 
    191 #define LZMA_NUM_POS_SLOT_BITS 6
    192 #define LZMA_NUM_LEN_TO_POS_STATES 4
    193 
    194 #define LZMA_NUM_ALIGN_BITS 4
    195 
    196 #define LZMA_MATCH_MIN_LEN 2
    197 
    198 #define LZMA_IS_MATCH 0
    199 #define LZMA_IS_REP (LZMA_IS_MATCH + (LZMA_NUM_STATES <<LZMA_NUM_POS_BITS_MAX))
    200 #define LZMA_IS_REP_G0 (LZMA_IS_REP + LZMA_NUM_STATES)
    201 #define LZMA_IS_REP_G1 (LZMA_IS_REP_G0 + LZMA_NUM_STATES)
    202 #define LZMA_IS_REP_G2 (LZMA_IS_REP_G1 + LZMA_NUM_STATES)
    203 #define LZMA_IS_REP_0_LONG (LZMA_IS_REP_G2 + LZMA_NUM_STATES)
    204 #define LZMA_POS_SLOT (LZMA_IS_REP_0_LONG \
    205                + (LZMA_NUM_STATES << LZMA_NUM_POS_BITS_MAX))
    206 #define LZMA_SPEC_POS (LZMA_POS_SLOT \
    207                +(LZMA_NUM_LEN_TO_POS_STATES << LZMA_NUM_POS_SLOT_BITS))
    208 #define LZMA_ALIGN (LZMA_SPEC_POS \
    209             + LZMA_NUM_FULL_DISTANCES - LZMA_END_POS_MODEL_INDEX)
    210 #define LZMA_LEN_CODER (LZMA_ALIGN + (1 << LZMA_NUM_ALIGN_BITS))
    211 #define LZMA_REP_LEN_CODER (LZMA_LEN_CODER + LZMA_NUM_LEN_PROBS)
    212 #define LZMA_LITERAL (LZMA_REP_LEN_CODER + LZMA_NUM_LEN_PROBS)
    213 
    214 
    215 int unlzma(int src_fd, int dst_fd)
    216 {
     179/* #defines will force compiler to compute/optimize each one with each usage.
     180 * Have heart and use enum instead. */
     181enum {
     182    LZMA_BASE_SIZE = 1846,
     183    LZMA_LIT_SIZE  = 768,
     184
     185    LZMA_NUM_POS_BITS_MAX = 4,
     186
     187    LZMA_LEN_NUM_LOW_BITS  = 3,
     188    LZMA_LEN_NUM_MID_BITS  = 3,
     189    LZMA_LEN_NUM_HIGH_BITS = 8,
     190
     191    LZMA_LEN_CHOICE     = 0,
     192    LZMA_LEN_CHOICE_2   = (LZMA_LEN_CHOICE + 1),
     193    LZMA_LEN_LOW        = (LZMA_LEN_CHOICE_2 + 1),
     194    LZMA_LEN_MID        = (LZMA_LEN_LOW \
     195                          + (1 << (LZMA_NUM_POS_BITS_MAX + LZMA_LEN_NUM_LOW_BITS))),
     196    LZMA_LEN_HIGH       = (LZMA_LEN_MID \
     197                          + (1 << (LZMA_NUM_POS_BITS_MAX + LZMA_LEN_NUM_MID_BITS))),
     198    LZMA_NUM_LEN_PROBS  = (LZMA_LEN_HIGH + (1 << LZMA_LEN_NUM_HIGH_BITS)),
     199
     200    LZMA_NUM_STATES     = 12,
     201    LZMA_NUM_LIT_STATES = 7,
     202
     203    LZMA_START_POS_MODEL_INDEX = 4,
     204    LZMA_END_POS_MODEL_INDEX   = 14,
     205    LZMA_NUM_FULL_DISTANCES    = (1 << (LZMA_END_POS_MODEL_INDEX >> 1)),
     206
     207    LZMA_NUM_POS_SLOT_BITS = 6,
     208    LZMA_NUM_LEN_TO_POS_STATES = 4,
     209
     210    LZMA_NUM_ALIGN_BITS = 4,
     211
     212    LZMA_MATCH_MIN_LEN  = 2,
     213
     214    LZMA_IS_MATCH       = 0,
     215    LZMA_IS_REP         = (LZMA_IS_MATCH + (LZMA_NUM_STATES << LZMA_NUM_POS_BITS_MAX)),
     216    LZMA_IS_REP_G0      = (LZMA_IS_REP + LZMA_NUM_STATES),
     217    LZMA_IS_REP_G1      = (LZMA_IS_REP_G0 + LZMA_NUM_STATES),
     218    LZMA_IS_REP_G2      = (LZMA_IS_REP_G1 + LZMA_NUM_STATES),
     219    LZMA_IS_REP_0_LONG  = (LZMA_IS_REP_G2 + LZMA_NUM_STATES),
     220    LZMA_POS_SLOT       = (LZMA_IS_REP_0_LONG \
     221                          + (LZMA_NUM_STATES << LZMA_NUM_POS_BITS_MAX)),
     222    LZMA_SPEC_POS       = (LZMA_POS_SLOT \
     223                          + (LZMA_NUM_LEN_TO_POS_STATES << LZMA_NUM_POS_SLOT_BITS)),
     224    LZMA_ALIGN          = (LZMA_SPEC_POS \
     225                          + LZMA_NUM_FULL_DISTANCES - LZMA_END_POS_MODEL_INDEX),
     226    LZMA_LEN_CODER      = (LZMA_ALIGN + (1 << LZMA_NUM_ALIGN_BITS)),
     227    LZMA_REP_LEN_CODER  = (LZMA_LEN_CODER + LZMA_NUM_LEN_PROBS),
     228    LZMA_LITERAL        = (LZMA_REP_LEN_CODER + LZMA_NUM_LEN_PROBS),
     229};
     230
     231
     232USE_DESKTOP(long long) int
     233unpack_lzma_stream(int src_fd, int dst_fd)
     234{
     235    USE_DESKTOP(long long total_written = 0;)
    217236    lzma_header_t header;
    218237    int lc, pb, lp;
     
    225244    int num_bits;
    226245    int num_probs;
    227     rc_t rc;
     246    rc_t *rc;
    228247    int i, mi;
    229248    uint8_t *buffer;
     
    234253    uint32_t rep0 = 1, rep1 = 1, rep2 = 1, rep3 = 1;
    235254
    236     if (read(src_fd, &header, sizeof(header)) != sizeof(header))
    237         bb_error_msg_and_die("can't read header");
     255    xread(src_fd, &header, sizeof(header));
    238256
    239257    if (header.pos >= (9 * 5 * 5))
     
    260278        p[i] = (1 << RC_MODEL_TOTAL_BITS) >> 1;
    261279
    262     rc_init(&rc, src_fd, 0x10000);
     280    rc = rc_init(src_fd); /*, RC_BUFFER_SIZE); */
    263281
    264282    while (global_pos + buffer_pos < header.dst_size) {
     
    267285        prob =
    268286            p + LZMA_IS_MATCH + (state << LZMA_NUM_POS_BITS_MAX) + pos_state;
    269         if (rc_is_bit_0(&rc, prob)) {
     287        if (rc_is_bit_0(rc, prob)) {
    270288            mi = 1;
    271             rc_update_bit_0(&rc, prob);
     289            rc_update_bit_0(rc, prob);
    272290            prob = (p + LZMA_LITERAL + (LZMA_LIT_SIZE
    273291                    * ((((buffer_pos + global_pos) & literal_pos_mask) << lc)
     
    287305                    bit = match_byte & 0x100;
    288306                    prob_lit = prob + 0x100 + bit + mi;
    289                     if (rc_get_bit(&rc, prob_lit, &mi)) {
     307                    if (rc_get_bit(rc, prob_lit, &mi)) {
    290308                        if (!bit)
    291309                            break;
     
    298316            while (mi < 0x100) {
    299317                prob_lit = prob + mi;
    300                 rc_get_bit(&rc, prob_lit, &mi);
     318                rc_get_bit(rc, prob_lit, &mi);
    301319            }
    302320            previous_byte = (uint8_t) mi;
     
    306324                buffer_pos = 0;
    307325                global_pos += header.dict_size;
    308                 write(dst_fd, buffer, header.dict_size);
     326                if (full_write(dst_fd, buffer, header.dict_size) != header.dict_size)
     327                    goto bad;
     328                USE_DESKTOP(total_written += header.dict_size;)
    309329            }
    310330            if (state < 4)
     
    318338            uint16_t *prob_len;
    319339
    320             rc_update_bit_1(&rc, prob);
     340            rc_update_bit_1(rc, prob);
    321341            prob = p + LZMA_IS_REP + state;
    322             if (rc_is_bit_0(&rc, prob)) {
    323                 rc_update_bit_0(&rc, prob);
     342            if (rc_is_bit_0(rc, prob)) {
     343                rc_update_bit_0(rc, prob);
    324344                rep3 = rep2;
    325345                rep2 = rep1;
     
    328348                prob = p + LZMA_LEN_CODER;
    329349            } else {
    330                 rc_update_bit_1(&rc, prob);
     350                rc_update_bit_1(rc, prob);
    331351                prob = p + LZMA_IS_REP_G0 + state;
    332                 if (rc_is_bit_0(&rc, prob)) {
    333                     rc_update_bit_0(&rc, prob);
     352                if (rc_is_bit_0(rc, prob)) {
     353                    rc_update_bit_0(rc, prob);
    334354                    prob = (p + LZMA_IS_REP_0_LONG
    335355                            + (state << LZMA_NUM_POS_BITS_MAX) + pos_state);
    336                     if (rc_is_bit_0(&rc, prob)) {
    337                         rc_update_bit_0(&rc, prob);
     356                    if (rc_is_bit_0(rc, prob)) {
     357                        rc_update_bit_0(rc, prob);
    338358
    339359                        state = state < LZMA_NUM_LIT_STATES ? 9 : 11;
     
    346366                            buffer_pos = 0;
    347367                            global_pos += header.dict_size;
    348                             write(dst_fd, buffer, header.dict_size);
     368                            if (full_write(dst_fd, buffer, header.dict_size) != header.dict_size)
     369                                goto bad;
     370                            USE_DESKTOP(total_written += header.dict_size;)
    349371                        }
    350372                        continue;
    351373                    } else {
    352                         rc_update_bit_1(&rc, prob);
     374                        rc_update_bit_1(rc, prob);
    353375                    }
    354376                } else {
    355377                    uint32_t distance;
    356378
    357                     rc_update_bit_1(&rc, prob);
     379                    rc_update_bit_1(rc, prob);
    358380                    prob = p + LZMA_IS_REP_G1 + state;
    359                     if (rc_is_bit_0(&rc, prob)) {
    360                         rc_update_bit_0(&rc, prob);
     381                    if (rc_is_bit_0(rc, prob)) {
     382                        rc_update_bit_0(rc, prob);
    361383                        distance = rep1;
    362384                    } else {
    363                         rc_update_bit_1(&rc, prob);
     385                        rc_update_bit_1(rc, prob);
    364386                        prob = p + LZMA_IS_REP_G2 + state;
    365                         if (rc_is_bit_0(&rc, prob)) {
    366                             rc_update_bit_0(&rc, prob);
     387                        if (rc_is_bit_0(rc, prob)) {
     388                            rc_update_bit_0(rc, prob);
    367389                            distance = rep2;
    368390                        } else {
    369                             rc_update_bit_1(&rc, prob);
     391                            rc_update_bit_1(rc, prob);
    370392                            distance = rep3;
    371393                            rep3 = rep2;
     
    381403
    382404            prob_len = prob + LZMA_LEN_CHOICE;
    383             if (rc_is_bit_0(&rc, prob_len)) {
    384                 rc_update_bit_0(&rc, prob_len);
     405            if (rc_is_bit_0(rc, prob_len)) {
     406                rc_update_bit_0(rc, prob_len);
    385407                prob_len = (prob + LZMA_LEN_LOW
    386408                            + (pos_state << LZMA_LEN_NUM_LOW_BITS));
     
    388410                num_bits = LZMA_LEN_NUM_LOW_BITS;
    389411            } else {
    390                 rc_update_bit_1(&rc, prob_len);
     412                rc_update_bit_1(rc, prob_len);
    391413                prob_len = prob + LZMA_LEN_CHOICE_2;
    392                 if (rc_is_bit_0(&rc, prob_len)) {
    393                     rc_update_bit_0(&rc, prob_len);
     414                if (rc_is_bit_0(rc, prob_len)) {
     415                    rc_update_bit_0(rc, prob_len);
    394416                    prob_len = (prob + LZMA_LEN_MID
    395417                                + (pos_state << LZMA_LEN_NUM_MID_BITS));
     
    397419                    num_bits = LZMA_LEN_NUM_MID_BITS;
    398420                } else {
    399                     rc_update_bit_1(&rc, prob_len);
     421                    rc_update_bit_1(rc, prob_len);
    400422                    prob_len = prob + LZMA_LEN_HIGH;
    401423                    offset = ((1 << LZMA_LEN_NUM_LOW_BITS)
     
    404426                }
    405427            }
    406             rc_bit_tree_decode(&rc, prob_len, num_bits, &len);
     428            rc_bit_tree_decode(rc, prob_len, num_bits, &len);
    407429            len += offset;
    408430
     
    417439                      LZMA_NUM_LEN_TO_POS_STATES - 1)
    418440                     << LZMA_NUM_POS_SLOT_BITS);
    419                 rc_bit_tree_decode(&rc, prob, LZMA_NUM_POS_SLOT_BITS,
     441                rc_bit_tree_decode(rc, prob, LZMA_NUM_POS_SLOT_BITS,
    420442                                   &pos_slot);
    421443                if (pos_slot >= LZMA_START_POS_MODEL_INDEX) {
     
    428450                        num_bits -= LZMA_NUM_ALIGN_BITS;
    429451                        while (num_bits--)
    430                             rep0 = (rep0 << 1) | rc_direct_bit(&rc);
     452                            rep0 = (rep0 << 1) | rc_direct_bit(rc);
    431453                        prob = p + LZMA_ALIGN;
    432454                        rep0 <<= LZMA_NUM_ALIGN_BITS;
     
    436458                    mi = 1;
    437459                    while (num_bits--) {
    438                         if (rc_get_bit(&rc, prob + mi, &mi))
     460                        if (rc_get_bit(rc, prob + mi, &mi))
    439461                            rep0 |= i;
    440462                        i <<= 1;
     
    457479                    buffer_pos = 0;
    458480                    global_pos += header.dict_size;
    459                     write(dst_fd, buffer, header.dict_size);
     481                    if (full_write(dst_fd, buffer, header.dict_size) != header.dict_size)
     482                        goto bad;
     483                    USE_DESKTOP(total_written += header.dict_size;)
    460484                }
    461485                len--;
     
    464488    }
    465489
    466     write(dst_fd, buffer, buffer_pos);
    467     rc_free(&rc);
    468     return 0;
    469 }
    470 
    471 /* vi:set ts=4: */
     490
     491    if (full_write(dst_fd, buffer, buffer_pos) != buffer_pos) {
     492 bad:
     493        rc_free(rc);
     494        return -1;
     495    }
     496    rc_free(rc);
     497    USE_DESKTOP(total_written += buffer_pos;)
     498    return USE_DESKTOP(total_written) + 0;
     499}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/decompress_unzip.c

    r821 r1765  
    3030 *
    3131 * See the file algorithm.doc for the compression algorithms and file formats.
    32  * 
     32 *
    3333 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
    3434 */
    3535
    3636#include "libbb.h"
    37 #include <sys/wait.h>
    38 #include <signal.h>
    3937#include "unarchive.h"
    4038
     
    4846} huft_t;
    4947
    50 static int gunzip_src_fd;
    51 unsigned int gunzip_bytes_out;  /* number of output bytes */
    52 static unsigned int gunzip_outbuf_count;    /* bytes in output buffer */
    53 
    54 /* gunzip_window size--must be a power of two, and
    55  *  at least 32K for zip's deflate method */
    56 enum { gunzip_wsize = 0x8000 };
    57 static unsigned char *gunzip_window;
    58 
    59 static uint32_t *gunzip_crc_table;
    60 uint32_t gunzip_crc;
    61 
    62 /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
    63 #define BMAX 16 /* maximum bit length of any code (16 for explode) */
    64 #define N_MAX 288   /* maximum number of codes in any set */
    65 
    66 /* bitbuffer */
    67 static unsigned int gunzip_bb;  /* bit buffer */
    68 static unsigned char gunzip_bk; /* bits in bit buffer */
    69 
    70 /* These control the size of the bytebuffer */
    71 static unsigned int bytebuffer_max = 0x8000;
    72 static unsigned char *bytebuffer = NULL;
    73 static unsigned int bytebuffer_offset = 0;
    74 static unsigned int bytebuffer_size = 0;
    75 
    76 static const unsigned short mask_bits[] = {
     48enum {
     49    /* gunzip_window size--must be a power of two, and
     50     *  at least 32K for zip's deflate method */
     51    GUNZIP_WSIZE = 0x8000,
     52    /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
     53    BMAX = 16,  /* maximum bit length of any code (16 for explode) */
     54    N_MAX = 288,    /* maximum number of codes in any set */
     55};
     56
     57
     58/* This is somewhat complex-looking arrangement, but it allows
     59 * to place decompressor state either in bss or in
     60 * malloc'ed space simply by changing #defines below.
     61 * Sizes on i386:
     62 * text    data     bss     dec     hex
     63 * 5256       0     108    5364    14f4 - bss
     64 * 4915       0       0    4915    1333 - malloc
     65 */
     66#define STATE_IN_BSS 0
     67#define STATE_IN_MALLOC 1
     68
     69
     70typedef struct state_t {
     71    off_t gunzip_bytes_out; /* number of output bytes */
     72    uint32_t gunzip_crc;
     73
     74    int gunzip_src_fd;
     75    unsigned gunzip_outbuf_count; /* bytes in output buffer */
     76
     77    unsigned char *gunzip_window;
     78
     79    uint32_t *gunzip_crc_table;
     80
     81    /* bitbuffer */
     82    unsigned gunzip_bb; /* bit buffer */
     83    unsigned char gunzip_bk; /* bits in bit buffer */
     84
     85    /* These control the size of the STATE()bytebuffer */
     86    unsigned bytebuffer_max;
     87    unsigned char *bytebuffer;
     88    unsigned bytebuffer_offset;
     89    unsigned bytebuffer_size;
     90
     91    /* private data of inflate_codes() */
     92    unsigned inflate_codes_ml; /* masks for bl and bd bits */
     93    unsigned inflate_codes_md; /* masks for bl and bd bits */
     94    unsigned inflate_codes_bb; /* bit buffer */
     95    unsigned inflate_codes_k; /* number of bits in bit buffer */
     96    unsigned inflate_codes_w; /* current gunzip_window position */
     97    huft_t *inflate_codes_tl;
     98    huft_t *inflate_codes_td;
     99    unsigned inflate_codes_bl;
     100    unsigned inflate_codes_bd;
     101    unsigned inflate_codes_nn; /* length and index for copy */
     102    unsigned inflate_codes_dd;
     103    smallint resume_copy;
     104
     105    /* private data of inflate_get_next_window() */
     106    smallint method; /* Method == -1 for stored, -2 for codes */
     107    smallint need_another_block;
     108    smallint end_reached;
     109
     110    /* private data of inflate_stored() */
     111    unsigned inflate_stored_n;
     112    unsigned inflate_stored_b;
     113    unsigned inflate_stored_k;
     114    unsigned inflate_stored_w;
     115} state_t;
     116#define gunzip_bytes_out    (S()gunzip_bytes_out   )
     117#define gunzip_crc          (S()gunzip_crc         )
     118#define gunzip_src_fd       (S()gunzip_src_fd      )
     119#define gunzip_outbuf_count (S()gunzip_outbuf_count)
     120#define gunzip_window       (S()gunzip_window      )
     121#define gunzip_crc_table    (S()gunzip_crc_table   )
     122#define gunzip_bb           (S()gunzip_bb          )
     123#define gunzip_bk           (S()gunzip_bk          )
     124#define bytebuffer_max      (S()bytebuffer_max     )
     125#define bytebuffer          (S()bytebuffer         )
     126#define bytebuffer_offset   (S()bytebuffer_offset  )
     127#define bytebuffer_size     (S()bytebuffer_size    )
     128#define inflate_codes_ml    (S()inflate_codes_ml   )
     129#define inflate_codes_md    (S()inflate_codes_md   )
     130#define inflate_codes_bb    (S()inflate_codes_bb   )
     131#define inflate_codes_k     (S()inflate_codes_k    )
     132#define inflate_codes_w     (S()inflate_codes_w    )
     133#define inflate_codes_tl    (S()inflate_codes_tl   )
     134#define inflate_codes_td    (S()inflate_codes_td   )
     135#define inflate_codes_bl    (S()inflate_codes_bl   )
     136#define inflate_codes_bd    (S()inflate_codes_bd   )
     137#define inflate_codes_nn    (S()inflate_codes_nn   )
     138#define inflate_codes_dd    (S()inflate_codes_dd   )
     139#define resume_copy         (S()resume_copy        )
     140#define method              (S()method             )
     141#define need_another_block  (S()need_another_block )
     142#define end_reached         (S()end_reached        )
     143#define inflate_stored_n    (S()inflate_stored_n   )
     144#define inflate_stored_b    (S()inflate_stored_b   )
     145#define inflate_stored_k    (S()inflate_stored_k   )
     146#define inflate_stored_w    (S()inflate_stored_w   )
     147#define INIT_STATE ({ bytebuffer_size = 0; method = -1; need_another_block = 1; })
     148
     149
     150/* This is generic part */
     151#if STATE_IN_BSS /* Use global data segment */
     152#define DECLARE_STATE /*nothing*/
     153#define ALLOC_STATE (init_state())
     154#define DEALLOC_STATE ((void)0)
     155#define S() state.
     156#define PASS_STATE /*nothing*/
     157#define PASS_STATE_ONLY /*nothing*/
     158#define STATE_PARAM /*nothing*/
     159#define STATE_PARAM_ONLY void
     160static state_t state;
     161static void init_state(void)
     162{
     163    INIT_STATE;
     164}
     165#endif
     166
     167#if STATE_IN_MALLOC /* Use malloc space */
     168#define DECLARE_STATE state_t *state
     169#define ALLOC_STATE (state = alloc_state())
     170#define DEALLOC_STATE free(state)
     171#define S() state->
     172#define PASS_STATE state,
     173#define PASS_STATE_ONLY state
     174#define STATE_PARAM state_t *state,
     175#define STATE_PARAM_ONLY state_t *state
     176static state_t* alloc_state(void)
     177{
     178    state_t* state = xzalloc(sizeof(*state));
     179    INIT_STATE;
     180    return state;
     181}
     182#endif
     183
     184
     185static const unsigned short mask_bits[] ALIGN2 = {
    77186    0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
    78187    0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
     
    80189
    81190/* Copy lengths for literal codes 257..285 */
    82 static const unsigned short cplens[] = {
     191static const unsigned short cplens[] ALIGN2 = {
    83192    3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
    84193    67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
     
    87196/* note: see note #13 above about the 258 in this list. */
    88197/* Extra bits for literal codes 257..285 */
    89 static const unsigned char cplext[] = {
     198static const unsigned char cplext[] ALIGN1 = {
    90199    0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5,
    91200    5, 5, 5, 0, 99, 99
    92 };                      /* 99==invalid */
     201}; /* 99 == invalid */
    93202
    94203/* Copy offsets for distance codes 0..29 */
    95 static const unsigned short cpdist[] = {
     204static const unsigned short cpdist[] ALIGN2 = {
    96205    1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
    97206    769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577
     
    99208
    100209/* Extra bits for distance codes */
    101 static const unsigned char cpdext[] = {
     210static const unsigned char cpdext[] ALIGN1 = {
    102211    0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10,
    103212    11, 11, 12, 12, 13, 13
     
    106215/* Tables for deflate from PKZIP's appnote.txt. */
    107216/* Order of the bit length code lengths */
    108 static const unsigned char border[] = {
     217static const unsigned char border[] ALIGN1 = {
    109218    16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
    110219};
    111220
    112 static unsigned int fill_bitbuffer(unsigned int bitbuffer, unsigned int *current, const unsigned int required)
     221static unsigned fill_bitbuffer(STATE_PARAM unsigned bitbuffer, unsigned *current, const unsigned required)
    113222{
    114223    while (*current < required) {
     
    117226             * to the front of the bytebuffer, leave 4 bytes free at end of tail
    118227             * so we can easily top up buffer in check_trailer_gzip() */
    119             if (!(bytebuffer_size = bb_xread(gunzip_src_fd, &bytebuffer[4], bytebuffer_max - 8))) {
     228            bytebuffer_size = safe_read(gunzip_src_fd, &bytebuffer[4], bytebuffer_max - 8);
     229            if (1 > bytebuffer_size)
     230//shouldn't we propagate error?
    120231                bb_error_msg_and_die("unexpected end of file");
    121             }
    122232            bytebuffer_size += 4;
    123233            bytebuffer_offset = 4;
    124234        }
    125         bitbuffer |= ((unsigned int) bytebuffer[bytebuffer_offset]) << *current;
     235        bitbuffer |= ((unsigned) bytebuffer[bytebuffer_offset]) << *current;
    126236        bytebuffer_offset++;
    127237        *current += 8;
    128238    }
    129     return(bitbuffer);
     239    return bitbuffer;
    130240}
    131241
     
    136246 * t: table to free
    137247 */
    138 static int huft_free(huft_t * t)
    139 {
    140     huft_t *p;
     248static void huft_free(huft_t * p)
     249{
    141250    huft_t *q;
    142251
    143252    /* Go through linked list, freeing from the malloced (t[-1]) address. */
    144     p = t;
    145     while (p != (huft_t *) NULL) {
     253    while (p) {
    146254        q = (--p)->v.t;
    147         free((char *) p);
     255        free(p);
    148256        p = q;
    149257    }
    150     return 0;
    151258}
    152259
     
    165272 * m:   maximum lookup bits, returns actual
    166273 */
    167 static
    168 int huft_build(unsigned int *b, const unsigned int n,
    169                const unsigned int s, const unsigned short *d,
    170                const unsigned char *e, huft_t ** t, unsigned int *m)
     274static int huft_build(unsigned *b, const unsigned n,
     275               const unsigned s, const unsigned short *d,
     276               const unsigned char *e, huft_t ** t, unsigned *m)
    171277{
    172278    unsigned a;             /* counter for codes of length k */
     
    195301
    196302    /* Generate counts for each bit length */
    197     memset((void *)c, 0, sizeof(c));
     303    memset(c, 0, sizeof(c));
    198304    p = b;
    199305    i = n;
     
    203309    } while (--i);
    204310    if (c[0] == n) { /* null input--all zero length codes */
    205         *t = (huft_t *) NULL;
     311        *t = NULL;
    206312        *m = 0;
    207313        return 2;
     
    217323    /* Adjust last length count to fill out codes, if needed */
    218324    for (y = 1 << j; j < i; j++, y <<= 1) {
    219         if ((y -= c[j]) < 0) {
     325        y -= c[j];
     326        if (y < 0) {
    220327            return 2; /* bad input: more codes than bits */
    221328        }
    222329    }
    223     if ((y -= c[i]) < 0) {
     330    y -= c[i];
     331    if (y < 0) {
    224332        return 2;
    225333    }
     
    231339    xp = x + 2;
    232340    while (--i) { /* note that i == g from above */
    233         *xp++ = (j += *p++);
     341        j += *p++;
     342        *xp++ = j;
    234343    }
    235344
     
    238347    i = 0;
    239348    do {
    240         if ((j = *p++) != 0) {
     349        j = *p++;
     350        if (j != 0) {
    241351            v[x[j]++] = i;
    242352        }
     
    248358    htl = -1;               /* no tables yet--level -1 */
    249359    w = ws[0] = 0;          /* bits decoded */
    250     u[0] = (huft_t *) NULL; /* just to keep compilers happy */
    251     q = (huft_t *) NULL;    /* ditto */
     360    u[0] = NULL;    /* just to keep compilers happy */
     361    q = NULL;   /* ditto */
    252362    z = 0;                  /* ditto */
    253363
     
    262372
    263373                /* compute minimum size table less than or equal to *m bits */
    264                 z = (z = g - w) > *m ? *m : z; /* upper limit on table size */
    265                 if ((f = 1 << (j = k - w)) > a + 1) { /* try a k-w bit table */
     374                z = g - w;
     375                z = z > *m ? *m : z; /* upper limit on table size */
     376                j = k - w;
     377                f = 1 << j;
     378                if (f > a + 1) { /* try a k-w bit table */
    266379                    /* too few codes for k-w bit table */
    267380                    f -= a + 1; /* deduct codes from patterns left */
    268381                    xp = c + k;
    269382                    while (++j < z) { /* try smaller tables up to z bits */
    270                         if ((f <<= 1) <= *++xp) {
     383                        f <<= 1;
     384                        if (f <= *++xp) {
    271385                            break; /* enough codes to use up j bits */
    272386                        }
     
    279393
    280394                /* allocate and link in new table */
    281                 q = (huft_t *) xzalloc((z + 1) * sizeof(huft_t));
     395                q = xzalloc((z + 1) * sizeof(huft_t));
    282396                *t = q + 1; /* link to list for huft_free() */
    283397                t = &(q->v.t);
     
    333447}
    334448
     449
    335450/*
    336451 * inflate (decompress) the codes in a deflated (compressed) block.
     
    340455 * bl, bd: number of bits decoded by tl[] and td[]
    341456 */
    342 static int inflate_codes(huft_t * my_tl, huft_t * my_td, const unsigned int my_bl, const unsigned int my_bd, int setup)
    343 {
    344     static unsigned int e;  /* table entry flag/number of extra bits */
    345     static unsigned int n, d;   /* length and index for copy */
    346     static unsigned int w;  /* current gunzip_window position */
    347     static huft_t *t;           /* pointer to table entry */
    348     static unsigned int ml, md; /* masks for bl and bd bits */
    349     static unsigned int b;  /* bit buffer */
    350     static unsigned int k;          /* number of bits in bit buffer */
    351     static huft_t *tl, *td;
    352     static unsigned int bl, bd;
    353     static int resumeCopy = 0;
    354 
    355     if (setup) { // 1st time we are called, copy in variables
    356         tl = my_tl;
    357         td = my_td;
    358         bl = my_bl;
    359         bd = my_bd;
    360         /* make local copies of globals */
    361         b = gunzip_bb;              /* initialize bit buffer */
    362         k = gunzip_bk;
    363         w = gunzip_outbuf_count;            /* initialize gunzip_window position */
    364 
    365         /* inflate the coded data */
    366         ml = mask_bits[bl]; /* precompute masks for speed */
    367         md = mask_bits[bd];
    368         return 0; // Don't actually do anything the first time
    369     }
    370 
    371     if (resumeCopy) goto do_copy;
     457/* called once from inflate_block */
     458
     459/* map formerly local static variables to globals */
     460#define ml inflate_codes_ml
     461#define md inflate_codes_md
     462#define bb inflate_codes_bb
     463#define k  inflate_codes_k
     464#define w  inflate_codes_w
     465#define tl inflate_codes_tl
     466#define td inflate_codes_td
     467#define bl inflate_codes_bl
     468#define bd inflate_codes_bd
     469#define nn inflate_codes_nn
     470#define dd inflate_codes_dd
     471static void inflate_codes_setup(STATE_PARAM huft_t * my_tl, huft_t * my_td, const unsigned my_bl, const unsigned my_bd)
     472{
     473    tl = my_tl;
     474    td = my_td;
     475    bl = my_bl;
     476    bd = my_bd;
     477    /* make local copies of globals */
     478    bb = gunzip_bb;         /* initialize bit buffer */
     479    k = gunzip_bk;
     480    w = gunzip_outbuf_count;    /* initialize gunzip_window position */
     481    /* inflate the coded data */
     482    ml = mask_bits[bl];     /* precompute masks for speed */
     483    md = mask_bits[bd];
     484}
     485/* called once from inflate_get_next_window */
     486static int inflate_codes(STATE_PARAM_ONLY)
     487{
     488    unsigned e; /* table entry flag/number of extra bits */
     489    huft_t *t;  /* pointer to table entry */
     490
     491    if (resume_copy) goto do_copy;
    372492
    373493    while (1) {         /* do until end of block */
    374         b = fill_bitbuffer(b, &k, bl);
    375         if ((e = (t = tl + ((unsigned) b & ml))->e) > 16)
     494        bb = fill_bitbuffer(PASS_STATE bb, &k, bl);
     495        t = tl + ((unsigned) bb & ml);
     496        e = t->e;
     497        if (e > 16)
    376498            do {
    377499                if (e == 99) {
     500//shouldn't we propagate error?
    378501                    bb_error_msg_and_die("inflate_codes error 1");
    379502                }
    380                 b >>= t->b;
     503                bb >>= t->b;
    381504                k -= t->b;
    382505                e -= 16;
    383                 b = fill_bitbuffer(b, &k, e);
    384             } while ((e =
    385                       (t = t->v.t + ((unsigned) b & mask_bits[e]))->e) > 16);
    386         b >>= t->b;
     506                bb = fill_bitbuffer(PASS_STATE bb, &k, e);
     507                t = t->v.t + ((unsigned) bb & mask_bits[e]);
     508                e = t->e;
     509            } while (e > 16);
     510        bb >>= t->b;
    387511        k -= t->b;
    388512        if (e == 16) {  /* then it's a literal */
    389513            gunzip_window[w++] = (unsigned char) t->v.n;
    390             if (w == gunzip_wsize) {
    391                 gunzip_outbuf_count = (w);
     514            if (w == GUNZIP_WSIZE) {
     515                gunzip_outbuf_count = w;
    392516                //flush_gunzip_window();
    393517                w = 0;
     
    395519            }
    396520        } else {        /* it's an EOB or a length */
    397 
    398521            /* exit if end of block */
    399522            if (e == 15) {
     
    402525
    403526            /* get length of block to copy */
    404             b = fill_bitbuffer(b, &k, e);
    405             n = t->v.n + ((unsigned) b & mask_bits[e]);
    406             b >>= e;
     527            bb = fill_bitbuffer(PASS_STATE bb, &k, e);
     528            nn = t->v.n + ((unsigned) bb & mask_bits[e]);
     529            bb >>= e;
    407530            k -= e;
    408531
    409532            /* decode distance of block to copy */
    410             b = fill_bitbuffer(b, &k, bd);
    411             if ((e = (t = td + ((unsigned) b & md))->e) > 16)
     533            bb = fill_bitbuffer(PASS_STATE bb, &k, bd);
     534            t = td + ((unsigned) bb & md);
     535            e = t->e;
     536            if (e > 16)
    412537                do {
    413538                    if (e == 99)
     539//shouldn't we propagate error?
    414540                        bb_error_msg_and_die("inflate_codes error 2");
    415                     b >>= t->b;
     541                    bb >>= t->b;
    416542                    k -= t->b;
    417543                    e -= 16;
    418                     b = fill_bitbuffer(b, &k, e);
    419                 } while ((e =
    420                           (t =
    421                            t->v.t + ((unsigned) b & mask_bits[e]))->e) > 16);
    422             b >>= t->b;
     544                    bb = fill_bitbuffer(PASS_STATE bb, &k, e);
     545                    t = t->v.t + ((unsigned) bb & mask_bits[e]);
     546                    e = t->e;
     547                } while (e > 16);
     548            bb >>= t->b;
    423549            k -= t->b;
    424             b = fill_bitbuffer(b, &k, e);
    425             d = w - t->v.n - ((unsigned) b & mask_bits[e]);
    426             b >>= e;
     550            bb = fill_bitbuffer(PASS_STATE bb, &k, e);
     551            dd = w - t->v.n - ((unsigned) bb & mask_bits[e]);
     552            bb >>= e;
    427553            k -= e;
    428554
    429555            /* do the copy */
    430 do_copy:        do {
    431                 n -= (e =
    432                       (e =
    433                        gunzip_wsize - ((d &= gunzip_wsize - 1) > w ? d : w)) > n ? n : e);
    434                /* copy to new buffer to prevent possible overwrite */
    435                 if (w - d >= e) {   /* (this test assumes unsigned comparison) */
    436                     memcpy(gunzip_window + w, gunzip_window + d, e);
     556 do_copy:
     557            do {
     558                /* Was: nn -= (e = (e = GUNZIP_WSIZE - ((dd &= GUNZIP_WSIZE - 1) > w ? dd : w)) > nn ? nn : e); */
     559                /* Who wrote THAT?? rewritten as: */
     560                dd &= GUNZIP_WSIZE - 1;
     561                e = GUNZIP_WSIZE - (dd > w ? dd : w);
     562                if (e > nn) e = nn;
     563                nn -= e;
     564
     565                /* copy to new buffer to prevent possible overwrite */
     566                if (w - dd >= e) {  /* (this test assumes unsigned comparison) */
     567                    memcpy(gunzip_window + w, gunzip_window + dd, e);
    437568                    w += e;
    438                     d += e;
     569                    dd += e;
    439570                } else {
    440                    /* do it slow to avoid memcpy() overlap */
    441                    /* !NOMEMCPY */
     571                    /* do it slow to avoid memcpy() overlap */
     572                    /* !NOMEMCPY */
    442573                    do {
    443                         gunzip_window[w++] = gunzip_window[d++];
     574                        gunzip_window[w++] = gunzip_window[dd++];
    444575                    } while (--e);
    445576                }
    446                 if (w == gunzip_wsize) {
    447                     gunzip_outbuf_count = (w);
    448                     if (n) resumeCopy = 1;
    449                     else resumeCopy = 0;
     577                if (w == GUNZIP_WSIZE) {
     578                    gunzip_outbuf_count = w;
     579                    resume_copy = (nn != 0);
    450580                    //flush_gunzip_window();
    451581                    w = 0;
    452582                    return 1;
    453583                }
    454             } while (n);
    455             resumeCopy = 0;
     584            } while (nn);
     585            resume_copy = 0;
    456586        }
    457587    }
    458588
    459589    /* restore the globals from the locals */
    460     gunzip_outbuf_count = w;            /* restore global gunzip_window pointer */
    461     gunzip_bb = b            /* restore global bit buffer */
     590    gunzip_outbuf_count = w;    /* restore global gunzip_window pointer */
     591    gunzip_bb = bb;         /* restore global bit buffer */
    462592    gunzip_bk = k;
    463593
     
    470600    return 0;
    471601}
    472 
    473 static int inflate_stored(int my_n, int my_b_stored, int my_k_stored, int setup)
    474 {
    475     static unsigned int n, b_stored, k_stored, w;
    476     if (setup) {
    477         n = my_n;
    478         b_stored = my_b_stored;
    479         k_stored = my_k_stored;
    480         w = gunzip_outbuf_count;        /* initialize gunzip_window position */
    481         return 0; // Don't do anything first time
    482     }
    483 
     602#undef ml
     603#undef md
     604#undef bb
     605#undef k
     606#undef w
     607#undef tl
     608#undef td
     609#undef bl
     610#undef bd
     611#undef nn
     612#undef dd
     613
     614
     615/* called once from inflate_block */
     616static void inflate_stored_setup(STATE_PARAM int my_n, int my_b, int my_k)
     617{
     618    inflate_stored_n = my_n;
     619    inflate_stored_b = my_b;
     620    inflate_stored_k = my_k;
     621    /* initialize gunzip_window position */
     622    inflate_stored_w = gunzip_outbuf_count;
     623}
     624/* called once from inflate_get_next_window */
     625static int inflate_stored(STATE_PARAM_ONLY)
     626{
    484627    /* read and output the compressed data */
    485     while (n--) {
    486         b_stored = fill_bitbuffer(b_stored, &k_stored, 8);
    487         gunzip_window[w++] = (unsigned char) b_stored;
    488         if (w == gunzip_wsize) {
    489             gunzip_outbuf_count = (w);
     628    while (inflate_stored_n--) {
     629        inflate_stored_b = fill_bitbuffer(PASS_STATE inflate_stored_b, &inflate_stored_k, 8);
     630        gunzip_window[inflate_stored_w++] = (unsigned char) inflate_stored_b;
     631        if (inflate_stored_w == GUNZIP_WSIZE) {
     632            gunzip_outbuf_count = inflate_stored_w;
    490633            //flush_gunzip_window();
    491             w = 0;
    492             b_stored >>= 8;
    493             k_stored -= 8;
     634            inflate_stored_w = 0;
     635            inflate_stored_b >>= 8;
     636            inflate_stored_k -= 8;
    494637            return 1; // We have a block
    495638        }
    496         b_stored >>= 8;
    497         k_stored -= 8;
     639        inflate_stored_b >>= 8;
     640        inflate_stored_k -= 8;
    498641    }
    499642
    500643    /* restore the globals from the locals */
    501     gunzip_outbuf_count = w;        /* restore global gunzip_window pointer */
    502     gunzip_bb = b_stored;   /* restore global bit buffer */
    503     gunzip_bk = k_stored;
     644    gunzip_outbuf_count = inflate_stored_w;     /* restore global gunzip_window pointer */
     645    gunzip_bb = inflate_stored_b;   /* restore global bit buffer */
     646    gunzip_bk = inflate_stored_k;
    504647    return 0; // Finished
    505648}
     649
    506650
    507651/*
     
    511655 * GLOBAL VARIABLES: bb, kk,
    512656 */
    513  // Return values: -1 = inflate_stored, -2 = inflate_codes
    514 static int inflate_block(int *e)
     657/* Return values: -1 = inflate_stored, -2 = inflate_codes */
     658/* One callsite in inflate_get_next_window */
     659static int inflate_block(STATE_PARAM smallint *e)
    515660{
    516661    unsigned t;         /* block type */
    517     register unsigned int b;    /* bit buffer */
    518     unsigned int k; /* number of bits in bit buffer */
     662    unsigned b; /* bit buffer */
     663    unsigned k; /* number of bits in bit buffer */
    519664
    520665    /* make local bit buffer */
     
    524669
    525670    /* read in last block bit */
    526     b = fill_bitbuffer(b, &k, 1);
    527     *e = (int) b & 1;
     671    b = fill_bitbuffer(PASS_STATE b, &k, 1);
     672    *e = b & 1;
    528673    b >>= 1;
    529674    k -= 1;
    530675
    531676    /* read in block type */
    532     b = fill_bitbuffer(b, &k, 2);
     677    b = fill_bitbuffer(PASS_STATE b, &k, 2);
    533678    t = (unsigned) b & 3;
    534679    b >>= 2;
     
    543688    case 0:         /* Inflate stored */
    544689    {
    545         unsigned int n; /* number of bytes in block */
    546         unsigned int b_stored;  /* bit buffer */
    547         unsigned int k_stored;  /* number of bits in bit buffer */
     690        unsigned n; /* number of bytes in block */
     691        unsigned b_stored;  /* bit buffer */
     692        unsigned k_stored;  /* number of bits in bit buffer */
    548693
    549694        /* make local copies of globals */
     
    557702
    558703        /* get the length and its complement */
    559         b_stored = fill_bitbuffer(b_stored, &k_stored, 16);
     704        b_stored = fill_bitbuffer(PASS_STATE b_stored, &k_stored, 16);
    560705        n = ((unsigned) b_stored & 0xffff);
    561706        b_stored >>= 16;
    562707        k_stored -= 16;
    563708
    564         b_stored = fill_bitbuffer(b_stored, &k_stored, 16);
     709        b_stored = fill_bitbuffer(PASS_STATE b_stored, &k_stored, 16);
    565710        if (n != (unsigned) ((~b_stored) & 0xffff)) {
    566711            return 1;   /* error in compressed data */
     
    569714        k_stored -= 16;
    570715
    571         inflate_stored(n, b_stored, k_stored, 1); // Setup inflate_stored
     716        inflate_stored_setup(PASS_STATE n, b_stored, k_stored); // Setup inflate_stored
     717
    572718        return -1;
    573719    }
    574     case 1:         /* Inflate fixed
    575                            * decompress an inflated type 1 (fixed Huffman codes) block.  We should
    576                            * either replace this with a custom decoder, or at least precompute the
    577                            * Huffman tables.
    578                         */
     720    case 1:
     721    /* Inflate fixed
     722     * decompress an inflated type 1 (fixed Huffman codes) block.  We should
     723     * either replace this with a custom decoder, or at least precompute the
     724     * Huffman tables. */
    579725    {
    580726        int i;          /* temporary variable */
    581727        huft_t *tl;     /* literal/length code table */
    582728        huft_t *td;     /* distance code table */
    583         unsigned int bl;            /* lookup bits for tl */
    584         unsigned int bd;            /* lookup bits for td */
    585         unsigned int l[288];    /* length list for huft_build */
     729        unsigned bl;            /* lookup bits for tl */
     730        unsigned bd;            /* lookup bits for td */
     731        unsigned l[288];    /* length list for huft_build */
    586732
    587733        /* set up literal table */
     
    599745        }
    600746        bl = 7;
    601         if ((i = huft_build(l, 288, 257, cplens, cplext, &tl, &bl)) != 0) {
     747        i = huft_build(l, 288, 257, cplens, cplext, &tl, &bl);
     748        if (i != 0) {
    602749            return i;
    603750        }
     
    608755        }
    609756        bd = 5;
    610         if ((i = huft_build(l, 30, 0, cpdist, cpdext, &td, &bd)) > 1) {
     757        i = huft_build(l, 30, 0, cpdist, cpdext, &td, &bd);
     758        if (i > 1) {
    611759            huft_free(tl);
    612760            return i;
     
    614762
    615763        /* decompress until an end-of-block code */
    616         inflate_codes(tl, td, bl, bd, 1); // Setup inflate_codes
     764        inflate_codes_setup(PASS_STATE tl, td, bl, bd); // Setup inflate_codes
    617765
    618766        /* huft_free code moved into inflate_codes */
     
    627775        huft_t *tl;     /* literal/length code table */
    628776        huft_t *td;     /* distance code table */
    629         unsigned int i;         /* temporary variables */
    630         unsigned int j;
    631         unsigned int l;     /* last length */
    632         unsigned int m;     /* mask for bit lengths table */
    633         unsigned int n;     /* number of lengths to get */
    634         unsigned int bl;            /* lookup bits for tl */
    635         unsigned int bd;            /* lookup bits for td */
    636         unsigned int nb;    /* number of bit length codes */
    637         unsigned int nl;    /* number of literal/length codes */
    638         unsigned int nd;    /* number of distance codes */
    639 
    640         unsigned int ll[286 + 30];  /* literal/length and distance code lengths */
    641         unsigned int b_dynamic; /* bit buffer */
    642         unsigned int k_dynamic; /* number of bits in bit buffer */
     777        unsigned i;         /* temporary variables */
     778        unsigned j;
     779        unsigned l;     /* last length */
     780        unsigned m;     /* mask for bit lengths table */
     781        unsigned n;     /* number of lengths to get */
     782        unsigned bl;            /* lookup bits for tl */
     783        unsigned bd;            /* lookup bits for td */
     784        unsigned nb;    /* number of bit length codes */
     785        unsigned nl;    /* number of literal/length codes */
     786        unsigned nd;    /* number of distance codes */
     787
     788        unsigned ll[286 + 30];  /* literal/length and distance code lengths */
     789        unsigned b_dynamic; /* bit buffer */
     790        unsigned k_dynamic; /* number of bits in bit buffer */
    643791
    644792        /* make local bit buffer */
     
    647795
    648796        /* read in table lengths */
    649         b_dynamic = fill_bitbuffer(b_dynamic, &k_dynamic, 5);
    650         nl = 257 + ((unsigned int) b_dynamic & 0x1f);   /* number of literal/length codes */
     797        b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, 5);
     798        nl = 257 + ((unsigned) b_dynamic & 0x1f);   /* number of literal/length codes */
    651799
    652800        b_dynamic >>= 5;
    653801        k_dynamic -= 5;
    654         b_dynamic = fill_bitbuffer(b_dynamic, &k_dynamic, 5);
    655         nd = 1 + ((unsigned int) b_dynamic & 0x1f); /* number of distance codes */
     802        b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, 5);
     803        nd = 1 + ((unsigned) b_dynamic & 0x1f); /* number of distance codes */
    656804
    657805        b_dynamic >>= 5;
    658806        k_dynamic -= 5;
    659         b_dynamic = fill_bitbuffer(b_dynamic, &k_dynamic, 4);
    660         nb = 4 + ((unsigned int) b_dynamic & 0xf);  /* number of bit length codes */
     807        b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, 4);
     808        nb = 4 + ((unsigned) b_dynamic & 0xf);  /* number of bit length codes */
    661809
    662810        b_dynamic >>= 4;
     
    668816        /* read in bit-length-code lengths */
    669817        for (j = 0; j < nb; j++) {
    670             b_dynamic = fill_bitbuffer(b_dynamic, &k_dynamic, 3);
    671             ll[border[j]] = (unsigned int) b_dynamic & 7;
     818            b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, 3);
     819            ll[border[j]] = (unsigned) b_dynamic & 7;
    672820            b_dynamic >>= 3;
    673821            k_dynamic -= 3;
     
    691839        m = mask_bits[bl];
    692840        i = l = 0;
    693         while ((unsigned int) i < n) {
    694             b_dynamic = fill_bitbuffer(b_dynamic, &k_dynamic, (unsigned int)bl);
    695             j = (td = tl + ((unsigned int) b_dynamic & m))->b;
     841        while ((unsigned) i < n) {
     842            b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, (unsigned)bl);
     843            j = (td = tl + ((unsigned) b_dynamic & m))->b;
    696844            b_dynamic >>= j;
    697845            k_dynamic -= j;
     
    700848                ll[i++] = l = j;    /* save last length in l */
    701849            } else if (j == 16) {   /* repeat last length 3 to 6 times */
    702                 b_dynamic = fill_bitbuffer(b_dynamic, &k_dynamic, 2);
    703                 j = 3 + ((unsigned int) b_dynamic & 3);
     850                b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, 2);
     851                j = 3 + ((unsigned) b_dynamic & 3);
    704852                b_dynamic >>= 2;
    705853                k_dynamic -= 2;
    706                 if ((unsigned int) i + j > n) {
     854                if ((unsigned) i + j > n) {
    707855                    return 1;
    708856                }
     
    711859                }
    712860            } else if (j == 17) {   /* 3 to 10 zero length codes */
    713                 b_dynamic = fill_bitbuffer(b_dynamic, &k_dynamic, 3);
    714                 j = 3 + ((unsigned int) b_dynamic & 7);
     861                b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, 3);
     862                j = 3 + ((unsigned) b_dynamic & 7);
    715863                b_dynamic >>= 3;
    716864                k_dynamic -= 3;
    717                 if ((unsigned int) i + j > n) {
     865                if ((unsigned) i + j > n) {
    718866                    return 1;
    719867                }
     
    723871                l = 0;
    724872            } else {    /* j == 18: 11 to 138 zero length codes */
    725                 b_dynamic = fill_bitbuffer(b_dynamic, &k_dynamic, 7);
    726                 j = 11 + ((unsigned int) b_dynamic & 0x7f);
     873                b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, 7);
     874                j = 11 + ((unsigned) b_dynamic & 0x7f);
    727875                b_dynamic >>= 7;
    728876                k_dynamic -= 7;
    729                 if ((unsigned int) i + j > n) {
     877                if ((unsigned) i + j > n) {
    730878                    return 1;
    731879                }
     
    747895        bl = lbits;
    748896
    749         if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) {
     897        i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl);
     898        if (i != 0) {
    750899            if (i == 1) {
    751                 bb_error_msg_and_die("Incomplete literal tree");
    752                 huft_free(tl);
     900//shouldn't we propagate error?
     901                bb_error_msg_and_die("incomplete literal tree");
     902                /* huft_free(tl); */
    753903            }
    754904            return i;   /* incomplete code set */
     
    756906
    757907        bd = dbits;
    758         if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) {
     908        i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd);
     909        if (i != 0) {
    759910            if (i == 1) {
     911//shouldn't we propagate error?
    760912                bb_error_msg_and_die("incomplete distance tree");
    761                 huft_free(td);
     913                /* huft_free(td); */
    762914            }
    763915            huft_free(tl);
     
    766918
    767919        /* decompress until an end-of-block code */
    768         inflate_codes(tl, td, bl, bd, 1); // Setup inflate_codes
     920        inflate_codes_setup(PASS_STATE tl, td, bl, bd); // Setup inflate_codes
    769921
    770922        /* huft_free code moved into inflate_codes */
     
    774926    default:
    775927        /* bad block type */
    776         bb_error_msg_and_die("bad block type %d\n", t);
    777     }
    778 }
    779 
    780 static void calculate_gunzip_crc(void)
     928//shouldn't we propagate error?
     929        bb_error_msg_and_die("bad block type %d", t);
     930    }
     931}
     932
     933/* Two callsites, both in inflate_get_next_window */
     934static void calculate_gunzip_crc(STATE_PARAM_ONLY)
    781935{
    782936    int n;
     
    787941}
    788942
    789 static int inflate_get_next_window(void)
    790 {
    791     static int method = -1; // Method == -1 for stored, -2 for codes
    792     static int e = 0;
    793     static int needAnotherBlock = 1;
    794 
     943/* One callsite in inflate_unzip_internal */
     944static int inflate_get_next_window(STATE_PARAM_ONLY)
     945{
    795946    gunzip_outbuf_count = 0;
    796947
    797     while(1) {
     948    while (1) {
    798949        int ret;
    799950
    800         if (needAnotherBlock) {
    801             if(e) {
    802                 calculate_gunzip_crc();
    803                 e = 0;
    804                 needAnotherBlock = 1;
    805                 return 0;
    806             } // Last block
    807             method = inflate_block(&e);
    808             needAnotherBlock = 0;
     951        if (need_another_block) {
     952            if (end_reached) {
     953                calculate_gunzip_crc(PASS_STATE_ONLY);
     954                end_reached = 0;
     955                need_another_block = 1;
     956                return 0; /* Last block */
     957            }
     958            method = inflate_block(PASS_STATE &end_reached);
     959            need_another_block = 0;
    809960        }
    810961
    811962        switch (method) {
    812             case -1:    ret = inflate_stored(0,0,0,0);
    813                     break;
    814             case -2:    ret = inflate_codes(0,0,0,0,0);
    815                     break;
    816             default:    bb_error_msg_and_die("inflate error %d", method);
     963        case -1:
     964            ret = inflate_stored(PASS_STATE_ONLY);
     965            break;
     966        case -2:
     967            ret = inflate_codes(PASS_STATE_ONLY);
     968            break;
     969        default:
     970//shouldn't we propagate error?
     971            bb_error_msg_and_die("inflate error %d", method);
    817972        }
    818973
    819974        if (ret == 1) {
    820             calculate_gunzip_crc();
     975            calculate_gunzip_crc(PASS_STATE_ONLY);
    821976            return 1; // More data left
    822         } else needAnotherBlock = 1; // End of that block
     977        }
     978        need_another_block = 1; // End of that block
    823979    }
    824980    /* Doesnt get here */
    825981}
    826982
    827 /* Initialise bytebuffer, be careful not to overfill the buffer */
    828 void inflate_init(unsigned int bufsize)
    829 {
    830     /* Set the bytebuffer size, default is same as gunzip_wsize */
    831     bytebuffer_max = bufsize + 8;
    832     bytebuffer_offset = 4;
    833     bytebuffer_size = 0;
    834 }
    835 
    836 void inflate_cleanup(void)
    837 {
    838     free(bytebuffer);
    839 }
    840 
    841 int inflate_unzip(int in, int out)
    842 {
     983
     984/* Called from unpack_gz_stream() and inflate_unzip() */
     985/* NB: bytebuffer is allocated here but freeing it is left to the caller! */
     986static USE_DESKTOP(long long) int
     987inflate_unzip_internal(STATE_PARAM int in, int out)
     988{
     989    USE_DESKTOP(long long) int n = 0;
    843990    ssize_t nwrote;
    844     typedef void (*sig_type) (int);
    845991
    846992    /* Allocate all global buffers (for DYN_ALLOC option) */
    847     gunzip_window = xmalloc(gunzip_wsize);
     993    gunzip_window = xmalloc(GUNZIP_WSIZE);
    848994    gunzip_outbuf_count = 0;
    849995    gunzip_bytes_out = 0;
     
    8551001
    8561002    /* Create the crc table */
    857     gunzip_crc_table = bb_crc32_filltable(0);
     1003    gunzip_crc_table = crc32_filltable(NULL, 0);
    8581004    gunzip_crc = ~0;
    859    
     1005
    8601006    /* Allocate space for buffer */
    8611007    bytebuffer = xmalloc(bytebuffer_max);
    8621008
    863     while(1) {
    864         int ret = inflate_get_next_window();
    865         nwrote = bb_full_write(out, gunzip_window, gunzip_outbuf_count);
    866         if (nwrote == -1) {
     1009    while (1) {
     1010        int r = inflate_get_next_window(PASS_STATE_ONLY);
     1011        nwrote = full_write(out, gunzip_window, gunzip_outbuf_count);
     1012        if (nwrote != gunzip_outbuf_count) {
    8671013            bb_perror_msg("write");
    868             return -1;
    869         }
    870         if (ret == 0) break;
    871     }
    872 
    873     /* Cleanup */
    874     free(gunzip_window);
    875     free(gunzip_crc_table);
     1014            n = -1;
     1015            goto ret;
     1016        }
     1017        USE_DESKTOP(n += nwrote;)
     1018        if (r == 0) break;
     1019    }
    8761020
    8771021    /* Store unused bytes in a global buffer so calling applets can access it */
     
    8841028        gunzip_bk -= 8;
    8851029    }
    886     return 0;
    887 }
    888 
    889 int inflate_gunzip(int in, int out)
     1030 ret:
     1031    /* Cleanup */
     1032    free(gunzip_window);
     1033    free(gunzip_crc_table);
     1034    return n;
     1035}
     1036
     1037
     1038USE_DESKTOP(long long) int
     1039inflate_unzip(inflate_unzip_result *res, unsigned bufsize, int in, int out)
     1040{
     1041    USE_DESKTOP(long long) int n;
     1042    DECLARE_STATE;
     1043
     1044    ALLOC_STATE;
     1045
     1046    bytebuffer_max = bufsize + 8;
     1047    bytebuffer_offset = 4;
     1048    n = inflate_unzip_internal(PASS_STATE in, out);
     1049
     1050    res->crc = gunzip_crc;
     1051    res->bytes_out = gunzip_bytes_out;
     1052    free(bytebuffer);
     1053    DEALLOC_STATE;
     1054    return n;
     1055}
     1056
     1057
     1058USE_DESKTOP(long long) int
     1059unpack_gz_stream(int in, int out)
    8901060{
    8911061    uint32_t stored_crc = 0;
    892     unsigned int count;
    893 
    894     inflate_unzip(in, out);
     1062    unsigned count;
     1063    USE_DESKTOP(long long) int n;
     1064    DECLARE_STATE;
     1065
     1066    ALLOC_STATE;
     1067
     1068    bytebuffer_max = 0x8000;
     1069    n = inflate_unzip_internal(PASS_STATE in, out);
     1070
     1071    if (n < 0) goto ret;
    8951072
    8961073    /* top up the input buffer with the rest of the trailer */
    8971074    count = bytebuffer_size - bytebuffer_offset;
    8981075    if (count < 8) {
    899         bb_xread_all(in, &bytebuffer[bytebuffer_size], 8 - count);
     1076        xread(in, &bytebuffer[bytebuffer_size], 8 - count);
     1077//shouldn't we propagate error?
    9001078        bytebuffer_size += 8 - count;
    9011079    }
     
    9081086    if (stored_crc != (~gunzip_crc)) {
    9091087        bb_error_msg("crc error");
    910         return -1;
     1088        n = -1;
     1089        goto ret;
    9111090    }
    9121091
     
    9141093    if (gunzip_bytes_out !=
    9151094        (bytebuffer[bytebuffer_offset] | (bytebuffer[bytebuffer_offset+1] << 8) |
    916         (bytebuffer[bytebuffer_offset+2] << 16) | (bytebuffer[bytebuffer_offset+3] << 24))) {
    917         bb_error_msg("Incorrect length");
    918         return -1;
    919     }
    920 
    921     return 0;
    922 }
     1095        (bytebuffer[bytebuffer_offset+2] << 16) | (bytebuffer[bytebuffer_offset+3] << 24))
     1096    ) {
     1097        bb_error_msg("incorrect length");
     1098        n = -1;
     1099    }
     1100 ret:
     1101    free(bytebuffer);
     1102    DEALLOC_STATE;
     1103    return n;
     1104}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/filter_accept_all.c

    r821 r1765  
    66 */
    77
    8 #include <stdlib.h>
     8#include "libbb.h"
    99#include "unarchive.h"
    1010
     
    1212char filter_accept_all(archive_handle_t *archive_handle)
    1313{
    14     if (archive_handle->file_header->name) {
    15         return(EXIT_SUCCESS);
    16     } else {
    17         return(EXIT_FAILURE);
    18     }
     14    if (archive_handle->file_header->name)
     15        return EXIT_SUCCESS;
     16    return EXIT_FAILURE;
    1917}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/filter_accept_list.c

    r821 r1765  
    66 */
    77
    8 #include <stdlib.h>
     8#include "libbb.h"
    99#include "unarchive.h"
    1010
     
    1414char filter_accept_list(archive_handle_t *archive_handle)
    1515{
    16     if (find_list_entry(archive_handle->accept, archive_handle->file_header->name)) {
    17         return(EXIT_SUCCESS);
    18     } else {
    19         return(EXIT_FAILURE);
    20     }
     16    if (find_list_entry(archive_handle->accept, archive_handle->file_header->name))
     17        return EXIT_SUCCESS;
     18    return EXIT_FAILURE;
    2119}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/filter_accept_list_reassign.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/*
    23 *  Copyright (C) 2002 by Glenn McGrath
    34 *
    4  *  This program is free software; you can redistribute it and/or modify
    5  *  it under the terms of the GNU General Public License as published by
    6  *  the Free Software Foundation; either version 2 of the License, or
    7  *  (at your option) any later version.
    8  *
    9  *  This program is distributed in the hope that it will be useful,
    10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  *  GNU General Public License for more details.
    13  *
    14  *  You should have received a copy of the GNU General Public License
    15  *  along with this program; if not, write to the Free Software
    16  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
     5 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
    176 */
    18 
    19 #include <stdlib.h>
    20 #include <string.h>
    21 #include <unistd.h>
    227
    238#include "libbb.h"
     
    2510
    2611/*
    27  *  Reassign the subarchive metadata parser based on the filename extension
    28  *  e.g. if its a .tar.gz modify archive_handle->sub_archive to process a .tar.gz
    29  *       or if its a .tar.bz2 make archive_handle->sub_archive handle that
     12 * Reassign the subarchive metadata parser based on the filename extension
     13 * e.g. if its a .tar.gz modify archive_handle->sub_archive to process a .tar.gz
     14 * or if its a .tar.bz2 make archive_handle->sub_archive handle that
    3015 */
    3116char filter_accept_list_reassign(archive_handle_t *archive_handle)
     
    3924
    4025        /* Modify the subarchive handler based on the extension */
    41 #ifdef CONFIG_FEATURE_DEB_TAR_GZ
     26#if ENABLE_FEATURE_DEB_TAR_GZ
    4227        if (strcmp(name_ptr, ".gz") == 0) {
    4328            archive_handle->action_data_subarchive = get_header_tar_gz;
    44             return(EXIT_SUCCESS);
     29            return EXIT_SUCCESS;
    4530        }
    4631#endif
    47 #ifdef CONFIG_FEATURE_DEB_TAR_BZ2
     32#if ENABLE_FEATURE_DEB_TAR_BZ2
    4833        if (strcmp(name_ptr, ".bz2") == 0) {
    4934            archive_handle->action_data_subarchive = get_header_tar_bz2;
    50             return(EXIT_SUCCESS);
     35            return EXIT_SUCCESS;
    5136        }
    5237#endif
    5338        if (ENABLE_FEATURE_DEB_TAR_LZMA && !strcmp(name_ptr, ".lzma")) {
    5439            archive_handle->action_data_subarchive = get_header_tar_lzma;
    55             return(EXIT_SUCCESS);
     40            return EXIT_SUCCESS;
    5641        }
    5742    }
    58     return(EXIT_FAILURE);
     43    return EXIT_FAILURE;
    5944}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/filter_accept_reject_list.c

    r821 r1765  
    66 */
    77
    8 #include <stdlib.h>
     8#include "libbb.h"
    99#include "unarchive.h"
    1010
     
    1515{
    1616    const char *key = archive_handle->file_header->name;
    17     const llist_t *reject_entry = find_list_entry(archive_handle->reject, key);
     17    const llist_t *reject_entry = find_list_entry2(archive_handle->reject, key);
    1818    const llist_t *accept_entry;
    1919
    2020    /* If the key is in a reject list fail */
    2121    if (reject_entry) {
    22         return(EXIT_FAILURE);
     22        return EXIT_FAILURE;
    2323    }
    24     accept_entry = find_list_entry(archive_handle->accept, key);
     24    accept_entry = find_list_entry2(archive_handle->accept, key);
    2525
    2626    /* Fail if an accept list was specified and the key wasnt in there */
    2727    if ((accept_entry == NULL) && archive_handle->accept) {
    28         return(EXIT_FAILURE);
     28        return EXIT_FAILURE;
    2929    }
    3030
    3131    /* Accepted */
    32     return(EXIT_SUCCESS);
     32    return EXIT_SUCCESS;
    3333}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/find_list_entry.c

    r902 r1765  
    77
    88#include <fnmatch.h>
    9 #include <stdlib.h>
     9#include "libbb.h"
    1010#include "unarchive.h"
    1111
    12 /* Find a string in a list */
     12/* Find a string in a shell pattern list */
    1313const llist_t *find_list_entry(const llist_t *list, const char *filename)
    1414{
    1515    while (list) {
    16         if (fnmatch(list->data, filename, FNM_LEADING_DIR) == 0) {
    17             return (list);
     16        if (fnmatch(list->data, filename, 0) == 0) {
     17            return list;
    1818        }
    1919        list = list->link;
    2020    }
    21     return(NULL);
     21    return NULL;
    2222}
     23
     24/* Same, but compares only path components present in pattern
     25 * (extra trailing path components in filename are assumed to match)
     26 */
     27const llist_t *find_list_entry2(const llist_t *list, const char *filename)
     28{
     29    char buf[PATH_MAX];
     30    int pattern_slash_cnt;
     31    const char *c;
     32    char *d;
     33
     34    while (list) {
     35        c = list->data;
     36        pattern_slash_cnt = 0;
     37        while (*c)
     38            if (*c++ == '/') pattern_slash_cnt++;
     39        c = filename;
     40        d = buf;
     41        /* paranoia is better that buffer overflows */
     42        while (*c && d != buf + sizeof(buf)-1) {
     43            if (*c == '/' && --pattern_slash_cnt < 0)
     44                break;
     45            *d++ = *c++;
     46        }
     47        *d = '\0';
     48        if (fnmatch(list->data, buf, 0) == 0) {
     49            return list;
     50        }
     51        list = list->link;
     52    }
     53    return NULL;
     54}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/get_header_ar.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/* Copyright 2001 Glenn McGrath.
    23 *
     
    45 */
    56
    6 #include <stdio.h>
    7 #include <stdlib.h>
    8 #include <string.h>
    9 #include <unistd.h>
     7#include "libbb.h"
    108#include "unarchive.h"
    11 #include "libbb.h"
    129
    1310char get_header_ar(archive_handle_t *archive_handle)
    1411{
     12    int err;
    1513    file_header_t *typed = archive_handle->file_header;
    1614    union {
     
    2422            char size[10];
    2523            char magic[2];
    26         } formated;
     24        } formatted;
    2725    } ar;
    28 #ifdef CONFIG_FEATURE_AR_LONG_FILENAMES
     26#if ENABLE_FEATURE_AR_LONG_FILENAMES
    2927    static char *ar_long_names;
    30     static unsigned int ar_long_name_size;
     28    static unsigned ar_long_name_size;
    3129#endif
    3230
    33     /* dont use bb_xread as we want to handle the error ourself */
     31    /* dont use xread as we want to handle the error ourself */
    3432    if (read(archive_handle->src_fd, ar.raw, 60) != 60) {
    3533        /* End Of File */
    36         return(EXIT_FAILURE);
     34        return EXIT_FAILURE;
    3735    }
    3836
     
    4341        /* fix up the header, we started reading 1 byte too early */
    4442        memmove(ar.raw, &ar.raw[1], 59);
    45         ar.raw[59] = bb_xread_char(archive_handle->src_fd);
     43        ar.raw[59] = xread_char(archive_handle->src_fd);
    4644        archive_handle->offset++;
    4745    }
     
    4947
    5048    /* align the headers based on the header magic */
    51     if ((ar.formated.magic[0] != '`') || (ar.formated.magic[1] != '\n')) {
    52         bb_error_msg_and_die("Invalid ar header");
    53     }
     49    if (ar.formatted.magic[0] != '`' || ar.formatted.magic[1] != '\n')
     50        bb_error_msg_and_die("invalid ar header");
    5451
    55     typed->mode = strtol(ar.formated.mode, NULL, 8);
    56     typed->mtime = atoi(ar.formated.date);
    57     typed->uid = atoi(ar.formated.uid);
    58     typed->gid = atoi(ar.formated.gid);
    59     typed->size = atoi(ar.formated.size);
     52    /* FIXME: more thorough routine would be in order here */
     53    /* (we have something like that in tar) */
     54    /* but for now we are lax. This code works because */
     55    /* on misformatted numbers bb_strtou returns all-ones */
     56    typed->mode = err = bb_strtou(ar.formatted.mode, NULL, 8);
     57    if (err == -1) bb_error_msg_and_die("invalid ar header");
     58    typed->mtime = err = bb_strtou(ar.formatted.date, NULL, 10);
     59    if (err == -1) bb_error_msg_and_die("invalid ar header");
     60    typed->uid = err = bb_strtou(ar.formatted.uid, NULL, 10);
     61    if (err == -1) bb_error_msg_and_die("invalid ar header");
     62    typed->gid = err = bb_strtou(ar.formatted.gid, NULL, 10);
     63    if (err == -1) bb_error_msg_and_die("invalid ar header");
     64    typed->size = err = bb_strtou(ar.formatted.size, NULL, 10);
     65    if (err == -1) bb_error_msg_and_die("invalid ar header");
    6066
    6167    /* long filenames have '/' as the first character */
    62     if (ar.formated.name[0] == '/') {
    63 #ifdef CONFIG_FEATURE_AR_LONG_FILENAMES
    64         if (ar.formated.name[1] == '/') {
     68    if (ar.formatted.name[0] == '/') {
     69#if ENABLE_FEATURE_AR_LONG_FILENAMES
     70        unsigned long_offset;
     71
     72        if (ar.formatted.name[1] == '/') {
    6573            /* If the second char is a '/' then this entries data section
    6674             * stores long filename for multiple entries, they are stored
     
    6876            ar_long_name_size = typed->size;
    6977            ar_long_names = xmalloc(ar_long_name_size);
    70             bb_xread_all(archive_handle->src_fd, ar_long_names, ar_long_name_size);
     78            xread(archive_handle->src_fd, ar_long_names, ar_long_name_size);
    7179            archive_handle->offset += ar_long_name_size;
    7280            /* This ar entries data section only contained filenames for other records
    7381             * they are stored in the static ar_long_names for future reference */
    74             return (get_header_ar(archive_handle)); /* Return next header */
    75         } else if (ar.formated.name[1] == ' ') {
     82            return get_header_ar(archive_handle); /* Return next header */
     83        }
     84
     85        if (ar.formatted.name[1] == ' ') {
    7686            /* This is the index of symbols in the file for compilers */
    7787            data_skip(archive_handle);
    7888            archive_handle->offset += typed->size;
    79             return (get_header_ar(archive_handle)); /* Return next header */
    80         } else {
    81             /* The number after the '/' indicates the offset in the ar data section
    82             (saved in variable long_name) that conatains the real filename */
    83             const unsigned int long_offset = atoi(&ar.formated.name[1]);
    84             if (long_offset >= ar_long_name_size) {
    85                 bb_error_msg_and_die("Cant resolve long filename");
    86             }
    87             typed->name = bb_xstrdup(ar_long_names + long_offset);
     89            return get_header_ar(archive_handle); /* Return next header */
    8890        }
     91
     92        /* The number after the '/' indicates the offset in the ar data section
     93         * (saved in variable long_name) that conatains the real filename */
     94        long_offset = atoi(&ar.formatted.name[1]);
     95        if (long_offset >= ar_long_name_size) {
     96            bb_error_msg_and_die("can't resolve long filename");
     97        }
     98        typed->name = xstrdup(ar_long_names + long_offset);
    8999#else
    90100        bb_error_msg_and_die("long filenames not supported");
     
    92102    } else {
    93103        /* short filenames */
    94            typed->name = bb_xstrndup(ar.formated.name, 16);
     104        typed->name = xstrndup(ar.formatted.name, 16);
    95105    }
    96106
     
    100110        archive_handle->action_header(typed);
    101111        if (archive_handle->sub_archive) {
    102             while (archive_handle->action_data_subarchive(archive_handle->sub_archive) == EXIT_SUCCESS);
     112            while (archive_handle->action_data_subarchive(archive_handle->sub_archive) == EXIT_SUCCESS)
     113                /* repeat */;
    103114        } else {
    104115            archive_handle->action_data(archive_handle);
     
    112123    lseek(archive_handle->src_fd, archive_handle->offset, SEEK_SET);
    113124
    114     return(EXIT_SUCCESS);
     125    return EXIT_SUCCESS;
    115126}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/get_header_cpio.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/* Copyright 2002 Laurence Anderson
    23 *
     
    45 */
    56
    6 #include <stdio.h>
    7 #include <stdlib.h>
    8 #include <string.h>
    9 #include <unistd.h>
    10 #include <sys/sysmacros.h>     /* major() and minor() */
     7#include "libbb.h"
    118#include "unarchive.h"
    12 #include "libbb.h"
    139
    1410typedef struct hardlinks_s {
    15     file_header_t *entry;
     11    char *name;
    1612    int inode;
    1713    struct hardlinks_s *next;
     
    2117{
    2218    static hardlinks_t *saved_hardlinks = NULL;
    23     static unsigned short pending_hardlinks = 0;
     19    static unsigned pending_hardlinks = 0;
     20    static int inode;
     21
    2422    file_header_t *file_header = archive_handle->file_header;
    2523    char cpio_header[110];
    2624    int namesize;
    2725    char dummy[16];
    28     int major, minor, nlink, inode;
     26    int major, minor, nlink;
    2927
    3028    if (pending_hardlinks) { /* Deal with any pending hardlinks */
    31         hardlinks_t *tmp;
    32         hardlinks_t *oldtmp;
     29        hardlinks_t *tmp, *oldtmp;
    3330
    3431        tmp = saved_hardlinks;
    3532        oldtmp = NULL;
    3633
     34        file_header->link_target = file_header->name;
     35        file_header->size = 0;
     36
    3737        while (tmp) {
    38             bb_error_msg_and_die("need to fix this\n");
    39             if (tmp->entry->link_name) { /* Found a hardlink ready to be extracted */
    40                 file_header = tmp->entry;
    41                 if (oldtmp) {
    42                     oldtmp->next = tmp->next; /* Remove item from linked list */
    43                 } else {
    44                     saved_hardlinks = tmp->next;
    45                 }
    46                 free(tmp);
     38            if (tmp->inode != inode) {
     39                tmp = tmp->next;
    4740                continue;
    4841            }
     42
     43            file_header->name = tmp->name;
     44
     45            if (archive_handle->filter(archive_handle) == EXIT_SUCCESS) {
     46                archive_handle->action_data(archive_handle);
     47                archive_handle->action_header(archive_handle->file_header);
     48            }
     49
     50            pending_hardlinks--;
     51
    4952            oldtmp = tmp;
    5053            tmp = tmp->next;
     54            free(oldtmp->name);
     55            free(oldtmp);
     56            if (oldtmp == saved_hardlinks)
     57                saved_hardlinks = tmp;
    5158        }
    52         pending_hardlinks = 0; /* No more pending hardlinks, read next file entry */
     59
     60        file_header->name = file_header->link_target;
     61
     62        if (pending_hardlinks > 1) {
     63            bb_error_msg("error resolving hardlink: archive made by GNU cpio 2.0-2.2?");
     64        }
     65
     66        /* No more pending hardlinks, read next file entry */
     67        pending_hardlinks = 0;
    5368    }
    5469
     
    5772
    5873    if (archive_xread_all_eof(archive_handle, (unsigned char*)cpio_header, 110) == 0) {
    59         return(EXIT_FAILURE);
     74        return EXIT_FAILURE;
    6075    }
    6176    archive_handle->offset += 110;
    6277
    63     if ((strncmp(&cpio_header[0], "07070", 5) != 0) || ((cpio_header[5] != '1') && (cpio_header[5] != '2'))) {
    64         bb_error_msg_and_die("Unsupported cpio format, use newc or crc");
     78    if (strncmp(&cpio_header[0], "07070", 5) != 0
     79     || (cpio_header[5] != '1' && cpio_header[5] != '2')
     80    ) {
     81        bb_error_msg_and_die("unsupported cpio format, use newc or crc");
    6582    }
    6683
    6784    {
    68         unsigned long tmpsize;
    69         sscanf(cpio_header, "%6c%8x%8x%8x%8x%8x%8lx%8lx%16c%8x%8x%8x%8c",
     85        unsigned long tmpsize;
     86        sscanf(cpio_header, "%6c%8x%8x%8x%8x%8x%8lx%8lx%16c%8x%8x%8x%8c",
    7087            dummy, &inode, (unsigned int*)&file_header->mode,
    7188            (unsigned int*)&file_header->uid, (unsigned int*)&file_header->gid,
    7289            &nlink, &file_header->mtime, &tmpsize,
    7390            dummy, &major, &minor, &namesize, dummy);
    74         file_header->size = tmpsize;
     91        file_header->size = tmpsize;
    7592    }
    7693
    77     file_header->name = (char *) xzalloc(namesize + 1);
    78     archive_xread_all(archive_handle, file_header->name, namesize); /* Read in filename */
     94    free(file_header->name);
     95    file_header->name = xzalloc(namesize + 1);
     96    /* Read in filename */
     97    xread(archive_handle->src_fd, file_header->name, namesize);
    7998    archive_handle->offset += namesize;
    8099
     
    83102
    84103    if (strcmp(file_header->name, "TRAILER!!!") == 0) {
    85         printf("%d blocks\n", (int) (archive_handle->offset % 512 ? (archive_handle->offset / 512) + 1 : archive_handle->offset / 512)); /* Always round up */
     104        /* Always round up */
     105        printf("%d blocks\n", (int) (archive_handle->offset % 512 ?
     106                                     archive_handle->offset / 512 + 1 :
     107                                     archive_handle->offset / 512
     108                                    ));
    86109        if (saved_hardlinks) { /* Bummer - we still have unresolved hardlinks */
    87110            hardlinks_t *tmp = saved_hardlinks;
    88111            hardlinks_t *oldtmp = NULL;
    89112            while (tmp) {
    90                 bb_error_msg("%s not created: cannot resolve hardlink", tmp->entry->name);
     113                bb_error_msg("%s not created: cannot resolve hardlink", tmp->name);
    91114                oldtmp = tmp;
    92115                tmp = tmp->next;
    93                 free (oldtmp->entry->name);
    94                 free (oldtmp->entry);
    95                 free (oldtmp);
     116                free(oldtmp->name);
     117                free(oldtmp);
    96118            }
    97119            saved_hardlinks = NULL;
    98120            pending_hardlinks = 0;
    99121        }
    100         return(EXIT_FAILURE);
     122        return EXIT_FAILURE;
    101123    }
    102124
    103125    if (S_ISLNK(file_header->mode)) {
    104         file_header->link_name = (char *) xzalloc(file_header->size + 1);
    105         archive_xread_all(archive_handle, file_header->link_name, file_header->size);
     126        file_header->link_target = xzalloc(file_header->size + 1);
     127        xread(archive_handle->src_fd, file_header->link_target, file_header->size);
    106128        archive_handle->offset += file_header->size;
    107129        file_header->size = 0; /* Stop possible seeks in future */
    108130    } else {
    109         file_header->link_name = NULL;
     131        file_header->link_target = NULL;
    110132    }
    111133    if (nlink > 1 && !S_ISDIR(file_header->mode)) {
     
    114136            new->next = saved_hardlinks;
    115137            new->inode = inode;
    116             new->entry = file_header;
     138            /* name current allocated, freed later */
     139            new->name = file_header->name;
     140            file_header->name = NULL;
    117141            saved_hardlinks = new;
    118             return(EXIT_SUCCESS); // Skip this one
    119         } else { /* Found the file with data in */
    120             hardlinks_t *tmp = saved_hardlinks;
    121             pending_hardlinks = 1;
    122             while (tmp) {
    123                 if (tmp->inode == inode) {
    124                     tmp->entry->link_name = bb_xstrdup(file_header->name);
    125                     nlink--;
    126                 }
    127                 tmp = tmp->next;
    128             }
    129             if (nlink > 1) {
    130                 bb_error_msg("error resolving hardlink: did you create the archive with GNU cpio 2.0-2.2?");
    131             }
     142            return EXIT_SUCCESS; /* Skip this one */
    132143        }
     144        /* Found the file with data in */
     145        pending_hardlinks = nlink;
    133146    }
    134147    file_header->device = makedev(major, minor);
     
    143156    archive_handle->offset += file_header->size;
    144157
    145     free(file_header->link_name);
     158    free(file_header->link_target);
    146159
    147     return (EXIT_SUCCESS);
     160    return EXIT_SUCCESS;
    148161}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/get_header_tar.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
    23 *
     
    1112 */
    1213
    13 #include <stdio.h>
    14 #include <stdlib.h>
    15 #include <string.h>
    16 #include <sys/sysmacros.h>  /* For makedev */
     14#include "libbb.h"
    1715#include "unarchive.h"
    18 #include "libbb.h"
    19 
    20 #ifdef CONFIG_FEATURE_TAR_GNU_EXTENSIONS
    21 static char *longname = NULL;
    22 static char *linkname = NULL;
    23 #endif
    24 
     16
     17#if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
     18static char *longname;
     19static char *linkname;
     20#else
     21enum {
     22    longname = 0,
     23    linkname = 0,
     24};
     25#endif
     26
     27/* NB: _DESTROYS_ str[len] character! */
     28static unsigned long long getOctal(char *str, int len)
     29{
     30    unsigned long long v;
     31    /* Actually, tar header allows leading spaces also.
     32     * Oh well, we will be liberal and skip this...
     33     * The only downside probably is that we allow "-123" too :)
     34    if (*str < '0' || *str > '7')
     35        bb_error_msg_and_die("corrupted octal value in tar header");
     36    */
     37    str[len] = '\0';
     38    v = strtoull(str, &str, 8);
     39    if (*str && (!ENABLE_FEATURE_TAR_OLDGNU_COMPATIBILITY || *str != ' '))
     40        bb_error_msg_and_die("corrupted octal value in tar header");
     41    return v;
     42}
     43#define GET_OCTAL(a) getOctal((a), sizeof(a))
     44
     45void BUG_tar_header_size(void);
    2546char get_header_tar(archive_handle_t *archive_handle)
    2647{
     48    static smallint end;
     49
    2750    file_header_t *file_header = archive_handle->file_header;
    28     union {
     51    struct {
    2952        /* ustar header, Posix 1003.1 */
    30         unsigned char raw[512];
    31         struct {
    32             char name[100]; /*   0-99 */
    33             char mode[8];   /* 100-107 */
    34             char uid[8];    /* 108-115 */
    35             char gid[8];    /* 116-123 */
    36             char size[12];  /* 124-135 */
    37             char mtime[12]; /* 136-147 */
    38             char chksum[8]; /* 148-155 */
    39             char typeflag;  /* 156-156 */
    40             char linkname[100]; /* 157-256 */
    41             char magic[6];  /* 257-262 */
    42             char version[2];    /* 263-264 */
    43             char uname[32]; /* 265-296 */
    44             char gname[32]; /* 297-328 */
    45             char devmajor[8];   /* 329-336 */
    46             char devminor[8];   /* 337-344 */
    47             char prefix[155];   /* 345-499 */
    48             char padding[12];   /* 500-512 */
    49         } formated;
     53        char name[100];     /*   0-99 */
     54        char mode[8];       /* 100-107 */
     55        char uid[8];        /* 108-115 */
     56        char gid[8];        /* 116-123 */
     57        char size[12];      /* 124-135 */
     58        char mtime[12];     /* 136-147 */
     59        char chksum[8];     /* 148-155 */
     60        char typeflag;      /* 156-156 */
     61        char linkname[100]; /* 157-256 */
     62        char magic[6];      /* 257-262 */
     63        char version[2];    /* 263-264 */
     64        char uname[32];     /* 265-296 */
     65        char gname[32];     /* 297-328 */
     66        char devmajor[8];   /* 329-336 */
     67        char devminor[8];   /* 337-344 */
     68        char prefix[155];   /* 345-499 */
     69        char padding[12];   /* 500-512 */
    5070    } tar;
    51     long sum = 0;
    52     long i;
    53     static int end = 0;
    54 
     71    char *cp;
     72    int i, sum_u, sum;
     73#if ENABLE_FEATURE_TAR_OLDSUN_COMPATIBILITY
     74    int sum_s;
     75#endif
     76    int parse_names;
     77
     78    if (sizeof(tar) != 512)
     79        BUG_tar_header_size();
     80
     81#if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
     82 again:
     83#endif
    5584    /* Align header */
    5685    data_align(archive_handle, 512);
    5786
    58     if (bb_full_read(archive_handle->src_fd, tar.raw, 512) != 512) {
    59         /* Assume end of file */
    60         bb_error_msg_and_die("Short header");
    61         //return(EXIT_FAILURE);
    62     }
     87 again_after_align:
     88
     89    xread(archive_handle->src_fd, &tar, 512);
    6390    archive_handle->offset += 512;
    6491
    6592    /* If there is no filename its an empty header */
    66     if (tar.formated.name[0] == 0) {
     93    if (tar.name[0] == 0) {
    6794        if (end) {
    6895            /* This is the second consecutive empty header! End of archive!
    6996             * Read until the end to empty the pipe from gz or bz2
    7097             */
    71             while (bb_full_read(archive_handle->src_fd, tar.raw, 512) == 512);
    72             return(EXIT_FAILURE);
     98            while (full_read(archive_handle->src_fd, &tar, 512) == 512)
     99                /* repeat */;
     100            return EXIT_FAILURE;
    73101        }
    74102        end = 1;
    75         return(EXIT_SUCCESS);
     103        return EXIT_SUCCESS;
    76104    }
    77105    end = 0;
     
    80108     * 0's are for the old tar format
    81109     */
    82     if (strncmp(tar.formated.magic, "ustar", 5) != 0) {
    83 #ifdef CONFIG_FEATURE_TAR_OLDGNU_COMPATIBILITY
    84         if (strncmp(tar.formated.magic, "\0\0\0\0\0", 5) != 0)
    85 #endif
    86             bb_error_msg_and_die("Invalid tar magic");
    87     }
    88     /* Do checksum on headers */
    89     for (i =  0; i < 148 ; i++) {
    90         sum += tar.raw[i];
    91     }
    92     sum += ' ' * 8;
    93     for (i =  156; i < 512 ; i++) {
    94         sum += tar.raw[i];
    95     }
    96     if (sum != strtol(tar.formated.chksum, NULL, 8)) {
    97         bb_error_msg("Invalid tar header checksum");
    98         return(EXIT_FAILURE);
    99     }
    100 
    101 #ifdef CONFIG_FEATURE_TAR_GNU_EXTENSIONS
     110    if (strncmp(tar.magic, "ustar", 5) != 0) {
     111#if ENABLE_FEATURE_TAR_OLDGNU_COMPATIBILITY
     112        if (memcmp(tar.magic, "\0\0\0\0", 5) != 0)
     113#endif
     114            bb_error_msg_and_die("invalid tar magic");
     115    }
     116
     117    /* Do checksum on headers.
     118     * POSIX says that checksum is done on unsigned bytes, but
     119     * Sun and HP-UX gets it wrong... more details in
     120     * GNU tar source. */
     121#if ENABLE_FEATURE_TAR_OLDSUN_COMPATIBILITY
     122    sum_s = ' ' * sizeof(tar.chksum);
     123#endif
     124    sum_u = ' ' * sizeof(tar.chksum);
     125    for (i = 0; i < 148; i++) {
     126        sum_u += ((unsigned char*)&tar)[i];
     127#if ENABLE_FEATURE_TAR_OLDSUN_COMPATIBILITY
     128        sum_s += ((signed char*)&tar)[i];
     129#endif
     130    }
     131    for (i = 156; i < 512; i++) {
     132        sum_u += ((unsigned char*)&tar)[i];
     133#if ENABLE_FEATURE_TAR_OLDSUN_COMPATIBILITY
     134        sum_s += ((signed char*)&tar)[i];
     135#endif
     136    }
     137#if ENABLE_FEATURE_TAR_OLDGNU_COMPATIBILITY
     138    sum = strtoul(tar.chksum, &cp, 8);
     139    if ((*cp && *cp != ' ')
     140     || (sum_u != sum USE_FEATURE_TAR_OLDSUN_COMPATIBILITY(&& sum_s != sum))
     141    ) {
     142        bb_error_msg_and_die("invalid tar header checksum");
     143    }
     144#else
     145    /* This field does not need special treatment (getOctal) */
     146    sum = xstrtoul(tar.chksum, 8);
     147    if (sum_u != sum USE_FEATURE_TAR_OLDSUN_COMPATIBILITY(&& sum_s != sum)) {
     148        bb_error_msg_and_die("invalid tar header checksum");
     149    }
     150#endif
     151
     152    /* 0 is reserved for high perf file, treat as normal file */
     153    if (!tar.typeflag) tar.typeflag = '0';
     154    parse_names = (tar.typeflag >= '0' && tar.typeflag <= '7');
     155
     156    /* getOctal trashes subsequent field, therefore we call it
     157     * on fields in reverse order */
     158    if (tar.devmajor[0]) {
     159        unsigned minor = GET_OCTAL(tar.devminor);
     160        unsigned major = GET_OCTAL(tar.devmajor);
     161        file_header->device = makedev(major, minor);
     162    }
     163    file_header->link_target = NULL;
     164    if (!linkname && parse_names && tar.linkname[0]) {
     165        /* we trash magic[0] here, it's ok */
     166        tar.linkname[sizeof(tar.linkname)] = '\0';
     167        file_header->link_target = xstrdup(tar.linkname);
     168        /* FIXME: what if we have non-link object with link_target? */
     169        /* Will link_target be free()ed? */
     170    }
     171    file_header->mtime = GET_OCTAL(tar.mtime);
     172    file_header->size = GET_OCTAL(tar.size);
     173    file_header->gid = GET_OCTAL(tar.gid);
     174    file_header->uid = GET_OCTAL(tar.uid);
     175    /* Set bits 0-11 of the files mode */
     176    file_header->mode = 07777 & GET_OCTAL(tar.mode);
     177
     178    file_header->name = NULL;
     179    if (!longname && parse_names) {
     180        /* we trash mode[0] here, it's ok */
     181        tar.name[sizeof(tar.name)] = '\0';
     182        if (tar.prefix[0]) {
     183            /* and padding[0] */
     184            tar.prefix[sizeof(tar.prefix)] = '\0';
     185            file_header->name = concat_path_file(tar.prefix, tar.name);
     186        } else
     187            file_header->name = xstrdup(tar.name);
     188    }
     189
     190    /* Set bits 12-15 of the files mode */
     191    /* (typeflag was not trashed because chksum does not use getOctal) */
     192    switch (tar.typeflag) {
     193    /* busybox identifies hard links as being regular files with 0 size and a link name */
     194    case '1':
     195        file_header->mode |= S_IFREG;
     196        break;
     197    case '7':
     198    /* case 0: */
     199    case '0':
     200#if ENABLE_FEATURE_TAR_OLDGNU_COMPATIBILITY
     201        if (last_char_is(file_header->name, '/')) {
     202            file_header->mode |= S_IFDIR;
     203        } else
     204#endif
     205        file_header->mode |= S_IFREG;
     206        break;
     207    case '2':
     208        file_header->mode |= S_IFLNK;
     209        break;
     210    case '3':
     211        file_header->mode |= S_IFCHR;
     212        break;
     213    case '4':
     214        file_header->mode |= S_IFBLK;
     215        break;
     216    case '5':
     217        file_header->mode |= S_IFDIR;
     218        break;
     219    case '6':
     220        file_header->mode |= S_IFIFO;
     221        break;
     222#if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
     223    case 'L':
     224        /* free: paranoia: tar with several consecutive longnames */
     225        free(longname);
     226        /* For paranoia reasons we allocate extra NUL char */
     227        longname = xzalloc(file_header->size + 1);
     228        /* We read ASCIZ string, including NUL */
     229        xread(archive_handle->src_fd, longname, file_header->size);
     230        archive_handle->offset += file_header->size;
     231        /* return get_header_tar(archive_handle); */
     232        /* gcc 4.1.1 didn't optimize it into jump */
     233        /* so we will do it ourself, this also saves stack */
     234        goto again;
     235    case 'K':
     236        free(linkname);
     237        linkname = xzalloc(file_header->size + 1);
     238        xread(archive_handle->src_fd, linkname, file_header->size);
     239        archive_handle->offset += file_header->size;
     240        /* return get_header_tar(archive_handle); */
     241        goto again;
     242    case 'D':   /* GNU dump dir */
     243    case 'M':   /* Continuation of multi volume archive */
     244    case 'N':   /* Old GNU for names > 100 characters */
     245    case 'S':   /* Sparse file */
     246    case 'V':   /* Volume header */
     247#endif
     248    case 'g':   /* pax global header */
     249    case 'x': { /* pax extended header */
     250        off_t sz;
     251        bb_error_msg("warning: skipping header '%c'", tar.typeflag);
     252        sz = (file_header->size + 511) & ~(off_t)511;
     253        archive_handle->offset += sz;
     254        sz >>= 9; /* sz /= 512 but w/o contortions for signed div */
     255        while (sz--)
     256            xread(archive_handle->src_fd, &tar, 512);
     257        /* return get_header_tar(archive_handle); */
     258        goto again_after_align;
     259    }
     260    default:
     261        bb_error_msg_and_die("unknown typeflag: 0x%x", tar.typeflag);
     262    }
     263
     264#if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
    102265    if (longname) {
    103266        file_header->name = longname;
    104267        longname = NULL;
    105268    }
    106     else if (linkname) {
    107         file_header->name = linkname;
     269    if (linkname) {
     270        file_header->link_target = linkname;
    108271        linkname = NULL;
    109     } else
    110 #endif
    111     {
    112         file_header->name = bb_xstrndup(tar.formated.name,100);
    113 
    114         if (tar.formated.prefix[0]) {
    115             char *temp = file_header->name;
    116             file_header->name = concat_path_file(tar.formated.prefix, temp);
    117             free(temp);
    118         }
    119     }
    120 
    121     file_header->uid = strtol(tar.formated.uid, NULL, 8);
    122     file_header->gid = strtol(tar.formated.gid, NULL, 8);
    123     file_header->size = strtol(tar.formated.size, NULL, 8);
    124     file_header->mtime = strtol(tar.formated.mtime, NULL, 8);
    125     file_header->link_name = (tar.formated.linkname[0] != '\0') ?
    126         bb_xstrdup(tar.formated.linkname) : NULL;
    127     file_header->device = makedev(strtol(tar.formated.devmajor, NULL, 8),
    128         strtol(tar.formated.devminor, NULL, 8));
    129 
    130     /* Set bits 0-11 of the files mode */
    131     file_header->mode = 07777 & strtol(tar.formated.mode, NULL, 8);
    132 
    133     /* Set bits 12-15 of the files mode */
    134     switch (tar.formated.typeflag) {
    135     /* busybox identifies hard links as being regular files with 0 size and a link name */
    136     case '1':
    137         file_header->mode |= S_IFREG;
    138         break;
    139     case '7':
    140         /* Reserved for high performance files, treat as normal file */
    141     case 0:
    142     case '0':
    143 #ifdef CONFIG_FEATURE_TAR_OLDGNU_COMPATIBILITY
    144         if (last_char_is(file_header->name, '/')) {
    145             file_header->mode |= S_IFDIR;
    146         } else
    147 #endif
    148             file_header->mode |= S_IFREG;
    149         break;
    150     case '2':
    151         file_header->mode |= S_IFLNK;
    152         break;
    153     case '3':
    154         file_header->mode |= S_IFCHR;
    155         break;
    156     case '4':
    157         file_header->mode |= S_IFBLK;
    158         break;
    159     case '5':
    160         file_header->mode |= S_IFDIR;
    161         break;
    162     case '6':
    163         file_header->mode |= S_IFIFO;
    164         break;
    165 #ifdef CONFIG_FEATURE_TAR_GNU_EXTENSIONS
    166     case 'L': {
    167             longname = xzalloc(file_header->size + 1);
    168             archive_xread_all(archive_handle, longname, file_header->size);
    169             archive_handle->offset += file_header->size;
    170 
    171             return(get_header_tar(archive_handle));
    172         }
    173     case 'K': {
    174             linkname = xzalloc(file_header->size + 1);
    175             archive_xread_all(archive_handle, linkname, file_header->size);
    176             archive_handle->offset += file_header->size;
    177 
    178             file_header->name = linkname;
    179             return(get_header_tar(archive_handle));
    180         }
    181     case 'D':   /* GNU dump dir */
    182     case 'M':   /* Continuation of multi volume archive*/
    183     case 'N':   /* Old GNU for names > 100 characters */
    184     case 'S':   /* Sparse file */
    185     case 'V':   /* Volume header */
    186 #endif
    187     case 'g':   /* pax global header */
    188     case 'x':   /* pax extended header */
    189         bb_error_msg("Ignoring extension type %c", tar.formated.typeflag);
    190         break;
    191     default:
    192         bb_error_msg("Unknown typeflag: 0x%x", tar.formated.typeflag);
    193     }
    194     {   /* Strip trailing '/' in directories */
    195         /* Must be done after mode is set as '/' is used to check if its a directory */
    196         char *tmp = last_char_is(file_header->name, '/');
    197         if (tmp) {
    198             *tmp = '\0';
    199         }
    200     }
     272    }
     273#endif
     274    if (!strncmp(file_header->name, "/../"+1, 3)
     275     || strstr(file_header->name, "/../")
     276    ) {
     277        bb_error_msg_and_die("name with '..' encountered: '%s'",
     278                file_header->name);
     279    }
     280
     281    /* Strip trailing '/' in directories */
     282    /* Must be done after mode is set as '/' is used to check if it's a directory */
     283    cp = last_char_is(file_header->name, '/');
    201284
    202285    if (archive_handle->filter(archive_handle) == EXIT_SUCCESS) {
    203286        archive_handle->action_header(archive_handle->file_header);
     287        /* Note that we kill the '/' only after action_header() */
     288        /* (like GNU tar 1.15.1: verbose mode outputs "dir/dir/") */
     289        if (cp) *cp = '\0';
    204290        archive_handle->flags |= ARCHIVE_EXTRACT_QUIET;
    205291        archive_handle->action_data(archive_handle);
     
    207293    } else {
    208294        data_skip(archive_handle);
     295        free(file_header->name);
    209296    }
    210297    archive_handle->offset += file_header->size;
    211298
    212     free(file_header->link_name);
    213 
    214     return(EXIT_SUCCESS);
     299    free(file_header->link_target);
     300    /* Do not free(file_header->name)! */
     301
     302    return EXIT_SUCCESS;
    215303}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/get_header_tar_bz2.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/*
    2  *  This program is free software; you can redistribute it and/or modify
    3  *  it under the terms of the GNU General Public License as published by
    4  *  the Free Software Foundation; either version 2 of the License, or
    5  *  (at your option) any later version.
    6  *
    7  *  This program is distributed in the hope that it will be useful,
    8  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
    9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    10  *  GNU Library General Public License for more details.
    11  *
    12  *  You should have received a copy of the GNU General Public License
    13  *  along with this program; if not, write to the Free Software
    14  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
     3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
    154 */
    165
    17 #include <sys/types.h>
    18 #include <sys/wait.h>
    19 #include <signal.h>
    20 #include <stdio.h>
    21 #include <stdlib.h>
    22 #include <string.h>
    23 #include <unistd.h>
    246#include "libbb.h"
    257#include "unarchive.h"
     
    279char get_header_tar_bz2(archive_handle_t *archive_handle)
    2810{
    29     /* Cant lseek over pipe's */
    30     archive_handle->seek = seek_by_char;
     11    /* Can't lseek over pipes */
     12    archive_handle->seek = seek_by_read;
    3113
    32     archive_handle->src_fd = open_transformer(archive_handle->src_fd, uncompressStream);
     14    archive_handle->src_fd = open_transformer(archive_handle->src_fd, unpack_bz2_stream, "bunzip2", "bunzip2", "-cf", "-", NULL);
    3315    archive_handle->offset = 0;
    34     while (get_header_tar(archive_handle) == EXIT_SUCCESS);
     16    while (get_header_tar(archive_handle) == EXIT_SUCCESS) /**/;
    3517
    3618    /* Can only do one file at a time */
    37     return(EXIT_FAILURE);
     19    return EXIT_FAILURE;
    3820}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/get_header_tar_gz.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/*
    2  *  This program is free software; you can redistribute it and/or modify
    3  *  it under the terms of the GNU General Public License as published by
    4  *  the Free Software Foundation; either version 2 of the License, or
    5  *  (at your option) any later version.
    6  *
    7  *  This program is distributed in the hope that it will be useful,
    8  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
    9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    10  *  GNU Library General Public License for more details.
    11  *
    12  *  You should have received a copy of the GNU General Public License
    13  *  along with this program; if not, write to the Free Software
    14  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
     3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
    154 */
    16 
    17 #include <stdlib.h>
    185
    196#include "libbb.h"
     
    229char get_header_tar_gz(archive_handle_t *archive_handle)
    2310{
     11#if BB_MMU
    2412    unsigned char magic[2];
     13#endif
    2514
    26     /* Cant lseek over pipe's */
    27     archive_handle->seek = seek_by_char;
     15    /* Can't lseek over pipes */
     16    archive_handle->seek = seek_by_read;
    2817
    29     archive_xread_all(archive_handle, &magic, 2);
     18    /* Check gzip magic only if open_transformer will invoke unpack_gz_stream (MMU case).
     19     * Otherwise, it will invoke an external helper "gunzip -cf" (NOMMU case) which will
     20     * need the header. */
     21#if BB_MMU
     22    xread(archive_handle->src_fd, &magic, 2);
    3023    if ((magic[0] != 0x1f) || (magic[1] != 0x8b)) {
    31         bb_error_msg_and_die("Invalid gzip magic");
     24        bb_error_msg_and_die("invalid gzip magic");
    3225    }
    3326
    34     check_header_gzip(archive_handle->src_fd);
     27    check_header_gzip_or_die(archive_handle->src_fd);
     28#endif
    3529
    36     archive_handle->src_fd = open_transformer(archive_handle->src_fd, inflate_gunzip);
     30    archive_handle->src_fd = open_transformer(archive_handle->src_fd, unpack_gz_stream, "gunzip", "gunzip", "-cf", "-", NULL);
    3731    archive_handle->offset = 0;
    38     while (get_header_tar(archive_handle) == EXIT_SUCCESS);
     32    while (get_header_tar(archive_handle) == EXIT_SUCCESS) /**/;
    3933
    4034    /* Can only do one file at a time */
    41     return(EXIT_FAILURE);
     35    return EXIT_FAILURE;
    4236}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/get_header_tar_lzma.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/*
    23 * Small lzma deflate implementation.
     
    67 */
    78
     9#include "libbb.h"
    810#include "unarchive.h"
    911
     
    1113{
    1214    /* Can't lseek over pipes */
    13     archive_handle->seek = seek_by_char;
     15    archive_handle->seek = seek_by_read;
    1416
    15     archive_handle->src_fd = open_transformer(archive_handle->src_fd, unlzma);
     17    archive_handle->src_fd = open_transformer(archive_handle->src_fd, unpack_lzma_stream, "unlzma", "unlzma", "-cf", "-", NULL);
    1618    archive_handle->offset = 0;
    17     while (get_header_tar(archive_handle) == EXIT_SUCCESS);
     19    while (get_header_tar(archive_handle) == EXIT_SUCCESS) /**/;
    1820
    1921    /* Can only do one file at a time */
    2022    return EXIT_FAILURE;
    2123}
    22 
    23 /* vi:set ts=4: */
  • branches/2.2.5/mindi-busybox/archival/libunarchive/header_list.c

    r821 r1765  
    1 #include <stdio.h>
     1/* vi: set sw=4 ts=4: */
     2/*
     3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
     4 */
     5#include "libbb.h"
    26#include "unarchive.h"
    37
  • branches/2.2.5/mindi-busybox/archival/libunarchive/header_skip.c

    r821 r1765  
    1 #include <stdio.h>
     1/* vi: set sw=4 ts=4: */
     2/*
     3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
     4 */
     5#include "libbb.h"
    26#include "unarchive.h"
    37
  • branches/2.2.5/mindi-busybox/archival/libunarchive/header_verbose_list.c

    r821 r1765  
    1 #include <stdio.h>
    2 #include <string.h>
    3 #include <time.h>
     1/* vi: set sw=4 ts=4: */
     2/*
     3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
     4 */
     5
    46#include "libbb.h"
    57#include "unarchive.h"
     
    911    struct tm *mtime = localtime(&(file_header->mtime));
    1012
    11     printf("%s %d/%d%10u %4u-%02u-%02u %02u:%02u:%02u %s",
     13    printf("%s %d/%d %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
    1214        bb_mode_string(file_header->mode),
    1315        file_header->uid,
    1416        file_header->gid,
    15         (unsigned int) file_header->size,
     17        file_header->size,
    1618        1900 + mtime->tm_year,
    1719        1 + mtime->tm_mon,
     
    2224        file_header->name);
    2325
    24     if (file_header->link_name) {
    25         printf(" -> %s", file_header->link_name);
     26    if (file_header->link_target) {
     27        printf(" -> %s", file_header->link_target);
    2628    }
    2729    /* putchar isnt used anywhere else i dont think */
  • branches/2.2.5/mindi-busybox/archival/libunarchive/init_handle.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/*
    2  *  This program is free software; you can redistribute it and/or modify
    3  *  it under the terms of the GNU General Public License as published by
    4  *  the Free Software Foundation; either version 2 of the License, or
    5  *  (at your option) any later version.
    6  *
    7  *  This program is distributed in the hope that it will be useful,
    8  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
    9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    10  *  GNU General Public License for more details.
    11  *
    12  *  You should have received a copy of the GNU General Public License
    13  *  along with this program; if not, write to the Free Software
    14  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
     3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
    154 */
    165
    17 #include <unistd.h>
    18 #include <string.h>
    196#include "libbb.h"
    207#include "unarchive.h"
     
    2411    archive_handle_t *archive_handle;
    2512
    26     /* Initialise default values */
     13    /* Initialize default values */
    2714    archive_handle = xzalloc(sizeof(archive_handle_t));
    28     archive_handle->file_header = xmalloc(sizeof(file_header_t));
     15    archive_handle->file_header = xzalloc(sizeof(file_header_t));
    2916    archive_handle->action_header = header_skip;
    3017    archive_handle->action_data = data_skip;
     
    3219    archive_handle->seek = seek_by_jump;
    3320
    34     return(archive_handle);
     21    return archive_handle;
    3522}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/open_transformer.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/*
    23 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
    34 */
    45
    5 #include <stdlib.h>
    6 #include <unistd.h>
    7 
    86#include "libbb.h"
    9 
    107#include "unarchive.h"
    118
    129/* transformer(), more than meets the eye */
    13 int open_transformer(int src_fd, int (*transformer)(int src_fd, int dst_fd))
     10/*
     11 * On MMU machine, the transform_prog and ... are stripped
     12 * by a macro in include/unarchive.h. On NOMMU, transformer is stripped.
     13 */
     14int open_transformer(int src_fd,
     15    USE_DESKTOP(long long) int (*transformer)(int src_fd, int dst_fd),
     16    const char *transform_prog, ...)
    1417{
    1518    int fd_pipe[2];
    1619    int pid;
    1720
    18     if (pipe(fd_pipe) != 0) {
    19         bb_perror_msg_and_die("Can't create pipe");
    20     }
     21    xpipe(fd_pipe);
    2122
     23#if BB_MMU
    2224    pid = fork();
    23     if (pid == -1) {
    24         bb_perror_msg_and_die("Fork failed");
    25     }
     25#else
     26    pid = vfork();
     27#endif
     28    if (pid == -1)
     29        bb_perror_msg_and_die("fork failed");
    2630
    2731    if (pid == 0) {
     32#if !BB_MMU
     33        va_list ap;
     34#endif
    2835        /* child process */
    29         close(fd_pipe[0]); /* We don't wan't to read from the parent */
    30         transformer(src_fd, fd_pipe[1]);
    31         close(fd_pipe[1]); /* Send EOF */
    32         close(src_fd);
    33         exit(0);
    34         /* notreached */
     36        close(fd_pipe[0]); /* We don't wan't to read from the parent */
     37        // FIXME: error check?
     38#if BB_MMU
     39        transformer(src_fd, fd_pipe[1]);
     40        if (ENABLE_FEATURE_CLEAN_UP) {
     41            close(fd_pipe[1]); /* Send EOF */
     42            close(src_fd);
     43        }
     44        exit(0);
     45#else
     46        xmove_fd(src_fd, 0);
     47        xmove_fd(fd_pipe[1], 1);
     48        va_start(ap, transform_prog);
     49        BB_EXECVP(transform_prog, ap);
     50        bb_perror_and_die("exec failed");
     51#endif
     52        /* notreached */
    3553    }
    3654
     
    3856    close(fd_pipe[1]); /* Don't want to write to the child */
    3957
    40     return(fd_pipe[0]);
     58    return fd_pipe[0];
    4159}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/seek_by_jump.c

    r821 r1765  
     1/* vi: set sw=4 ts=4: */
    12/*
    2  *  This program is free software; you can redistribute it and/or modify
    3  *  it under the terms of the GNU General Public License as published by
    4  *  the Free Software Foundation; either version 2 of the License, or
    5  *  (at your option) any later version.
    6  *
    7  *  This program is distributed in the hope that it will be useful,
    8  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
    9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    10  *  GNU Library General Public License for more details.
    11  *
    12  *  You should have received a copy of the GNU General Public License
    13  *  along with this program; if not, write to the Free Software
    14  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
     3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
    154 */
    16 
    17 #include <sys/types.h>
    18 #include <errno.h>
    19 #include <unistd.h>
    20 #include <stdlib.h>
    215
    226#include "libbb.h"
     
    2610{
    2711    if (lseek(archive_handle->src_fd, (off_t) amount, SEEK_CUR) == (off_t) -1) {
    28 #ifdef CONFIG_FEATURE_UNARCHIVE_TAPE
     12#if ENABLE_FEATURE_UNARCHIVE_TAPE
    2913        if (errno == ESPIPE) {
    30             seek_by_char(archive_handle, amount);
     14            seek_by_read(archive_handle, amount);
    3115        } else
    3216#endif
    33             bb_perror_msg_and_die("Seek failure");
     17            bb_perror_msg_and_die("seek failure");
    3418    }
    3519}
  • branches/2.2.5/mindi-busybox/archival/libunarchive/unpack_ar_archive.c

    r821 r1765  
    1 /* vi:set ts=4:*/
     1/* vi: set sw=4 ts=4: */
    22/*
    33 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
    44 */
    5 #include <fcntl.h>
    6 #include <stdlib.h>
    7 #include <string.h>
     5
     6#include "libbb.h"
    87#include "unarchive.h"
    9 #include "libbb.h"
    108
    119void unpack_ar_archive(archive_handle_t *ar_archive)
     
    1311    char magic[7];
    1412
    15     archive_xread_all(ar_archive, magic, 7);
     13    xread(ar_archive->src_fd, magic, 7);
    1614    if (strncmp(magic, "!<arch>", 7) != 0) {
    17         bb_error_msg_and_die("Invalid ar magic");
     15        bb_error_msg_and_die("invalid ar magic");
    1816    }
    1917    ar_archive->offset += 7;
Note: See TracChangeset for help on using the changeset viewer.