all repos — mgba @ dab12cf5c674542cae0db7708c333035255fbc65

mGBA Game Boy Advance Emulator

src/third-party/lzma/Util/7z/7zMain.c (view raw)

  1/* 7zMain.c - Test application for 7z Decoder
  22015-08-02 : Igor Pavlov : Public domain */
  3
  4#include "Precomp.h"
  5
  6#include <stdio.h>
  7#include <string.h>
  8
  9#include "../../7z.h"
 10#include "../../7zAlloc.h"
 11#include "../../7zBuf.h"
 12#include "../../7zCrc.h"
 13#include "../../7zFile.h"
 14#include "../../7zVersion.h"
 15
 16#ifndef USE_WINDOWS_FILE
 17/* for mkdir */
 18#ifdef _WIN32
 19#include <direct.h>
 20#else
 21#include <sys/stat.h>
 22#include <errno.h>
 23#endif
 24#endif
 25
 26static ISzAlloc g_Alloc = { SzAlloc, SzFree };
 27
 28static int Buf_EnsureSize(CBuf *dest, size_t size)
 29{
 30  if (dest->size >= size)
 31    return 1;
 32  Buf_Free(dest, &g_Alloc);
 33  return Buf_Create(dest, size, &g_Alloc);
 34}
 35
 36#ifndef _WIN32
 37#define _USE_UTF8
 38#endif
 39
 40/* #define _USE_UTF8 */
 41
 42#ifdef _USE_UTF8
 43
 44#define _UTF8_START(n) (0x100 - (1 << (7 - (n))))
 45
 46#define _UTF8_RANGE(n) (((UInt32)1) << ((n) * 5 + 6))
 47
 48#define _UTF8_HEAD(n, val) ((Byte)(_UTF8_START(n) + (val >> (6 * (n)))))
 49#define _UTF8_CHAR(n, val) ((Byte)(0x80 + (((val) >> (6 * (n))) & 0x3F)))
 50
 51static size_t Utf16_To_Utf8_Calc(const UInt16 *src, const UInt16 *srcLim)
 52{
 53  size_t size = 0;
 54  for (;;)
 55  {
 56    UInt32 val;
 57    if (src == srcLim)
 58      return size;
 59    
 60    size++;
 61    val = *src++;
 62   
 63    if (val < 0x80)
 64      continue;
 65
 66    if (val < _UTF8_RANGE(1))
 67    {
 68      size++;
 69      continue;
 70    }
 71
 72    if (val >= 0xD800 && val < 0xDC00 && src != srcLim)
 73    {
 74      UInt32 c2 = *src;
 75      if (c2 >= 0xDC00 && c2 < 0xE000)
 76      {
 77        src++;
 78        size += 3;
 79        continue;
 80      }
 81    }
 82
 83    size += 2;
 84  }
 85}
 86
 87static Byte *Utf16_To_Utf8(Byte *dest, const UInt16 *src, const UInt16 *srcLim)
 88{
 89  for (;;)
 90  {
 91    UInt32 val;
 92    if (src == srcLim)
 93      return dest;
 94    
 95    val = *src++;
 96    
 97    if (val < 0x80)
 98    {
 99      *dest++ = (char)val;
100      continue;
101    }
102
103    if (val < _UTF8_RANGE(1))
104    {
105      dest[0] = _UTF8_HEAD(1, val);
106      dest[1] = _UTF8_CHAR(0, val);
107      dest += 2;
108      continue;
109    }
110
111    if (val >= 0xD800 && val < 0xDC00 && src != srcLim)
112    {
113      UInt32 c2 = *src;
114      if (c2 >= 0xDC00 && c2 < 0xE000)
115      {
116        src++;
117        val = (((val - 0xD800) << 10) | (c2 - 0xDC00)) + 0x10000;
118        dest[0] = _UTF8_HEAD(3, val);
119        dest[1] = _UTF8_CHAR(2, val);
120        dest[2] = _UTF8_CHAR(1, val);
121        dest[3] = _UTF8_CHAR(0, val);
122        dest += 4;
123        continue;
124      }
125    }
126    
127    dest[0] = _UTF8_HEAD(2, val);
128    dest[1] = _UTF8_CHAR(1, val);
129    dest[2] = _UTF8_CHAR(0, val);
130    dest += 3;
131  }
132}
133
134static SRes Utf16_To_Utf8Buf(CBuf *dest, const UInt16 *src, size_t srcLen)
135{
136  size_t destLen = Utf16_To_Utf8_Calc(src, src + srcLen);
137  destLen += 1;
138  if (!Buf_EnsureSize(dest, destLen))
139    return SZ_ERROR_MEM;
140  *Utf16_To_Utf8(dest->data, src, src + srcLen) = 0;
141  return SZ_OK;
142}
143
144#endif
145
146static SRes Utf16_To_Char(CBuf *buf, const UInt16 *s
147    #ifndef _USE_UTF8
148    , UINT codePage
149    #endif
150    )
151{
152  unsigned len = 0;
153  for (len = 0; s[len] != 0; len++);
154
155  #ifndef _USE_UTF8
156  {
157    unsigned size = len * 3 + 100;
158    if (!Buf_EnsureSize(buf, size))
159      return SZ_ERROR_MEM;
160    {
161      buf->data[0] = 0;
162      if (len != 0)
163      {
164        char defaultChar = '_';
165        BOOL defUsed;
166        unsigned numChars = 0;
167        numChars = WideCharToMultiByte(codePage, 0, s, len, (char *)buf->data, size, &defaultChar, &defUsed);
168        if (numChars == 0 || numChars >= size)
169          return SZ_ERROR_FAIL;
170        buf->data[numChars] = 0;
171      }
172      return SZ_OK;
173    }
174  }
175  #else
176  return Utf16_To_Utf8Buf(buf, s, len);
177  #endif
178}
179
180#ifdef _WIN32
181  #ifndef USE_WINDOWS_FILE
182    static UINT g_FileCodePage = CP_ACP;
183  #endif
184  #define MY_FILE_CODE_PAGE_PARAM ,g_FileCodePage
185#else
186  #define MY_FILE_CODE_PAGE_PARAM
187#endif
188
189static WRes MyCreateDir(const UInt16 *name)
190{
191  #ifdef USE_WINDOWS_FILE
192  
193  return CreateDirectoryW(name, NULL) ? 0 : GetLastError();
194  
195  #else
196
197  CBuf buf;
198  WRes res;
199  Buf_Init(&buf);
200  RINOK(Utf16_To_Char(&buf, name MY_FILE_CODE_PAGE_PARAM));
201
202  res =
203  #ifdef _WIN32
204  _mkdir((const char *)buf.data)
205  #else
206  mkdir((const char *)buf.data, 0777)
207  #endif
208  == 0 ? 0 : errno;
209  Buf_Free(&buf, &g_Alloc);
210  return res;
211  
212  #endif
213}
214
215static WRes OutFile_OpenUtf16(CSzFile *p, const UInt16 *name)
216{
217  #ifdef USE_WINDOWS_FILE
218  return OutFile_OpenW(p, name);
219  #else
220  CBuf buf;
221  WRes res;
222  Buf_Init(&buf);
223  RINOK(Utf16_To_Char(&buf, name MY_FILE_CODE_PAGE_PARAM));
224  res = OutFile_Open(p, (const char *)buf.data);
225  Buf_Free(&buf, &g_Alloc);
226  return res;
227  #endif
228}
229
230static SRes PrintString(const UInt16 *s)
231{
232  CBuf buf;
233  SRes res;
234  Buf_Init(&buf);
235  res = Utf16_To_Char(&buf, s
236      #ifndef _USE_UTF8
237      , CP_OEMCP
238      #endif
239      );
240  if (res == SZ_OK)
241    fputs((const char *)buf.data, stdout);
242  Buf_Free(&buf, &g_Alloc);
243  return res;
244}
245
246static void UInt64ToStr(UInt64 value, char *s)
247{
248  char temp[32];
249  int pos = 0;
250  do
251  {
252    temp[pos++] = (char)('0' + (unsigned)(value % 10));
253    value /= 10;
254  }
255  while (value != 0);
256  do
257    *s++ = temp[--pos];
258  while (pos);
259  *s = '\0';
260}
261
262static char *UIntToStr(char *s, unsigned value, int numDigits)
263{
264  char temp[16];
265  int pos = 0;
266  do
267    temp[pos++] = (char)('0' + (value % 10));
268  while (value /= 10);
269  for (numDigits -= pos; numDigits > 0; numDigits--)
270    *s++ = '0';
271  do
272    *s++ = temp[--pos];
273  while (pos);
274  *s = '\0';
275  return s;
276}
277
278static void UIntToStr_2(char *s, unsigned value)
279{
280  s[0] = (char)('0' + (value / 10));
281  s[1] = (char)('0' + (value % 10));
282}
283
284#define PERIOD_4 (4 * 365 + 1)
285#define PERIOD_100 (PERIOD_4 * 25 - 1)
286#define PERIOD_400 (PERIOD_100 * 4 + 1)
287
288static void ConvertFileTimeToString(const CNtfsFileTime *nt, char *s)
289{
290  unsigned year, mon, hour, min, sec;
291  Byte ms[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
292  unsigned t;
293  UInt32 v;
294  UInt64 v64 = nt->Low | ((UInt64)nt->High << 32);
295  v64 /= 10000000;
296  sec = (unsigned)(v64 % 60); v64 /= 60;
297  min = (unsigned)(v64 % 60); v64 /= 60;
298  hour = (unsigned)(v64 % 24); v64 /= 24;
299
300  v = (UInt32)v64;
301
302  year = (unsigned)(1601 + v / PERIOD_400 * 400);
303  v %= PERIOD_400;
304
305  t = v / PERIOD_100; if (t ==  4) t =  3; year += t * 100; v -= t * PERIOD_100;
306  t = v / PERIOD_4;   if (t == 25) t = 24; year += t * 4;   v -= t * PERIOD_4;
307  t = v / 365;        if (t ==  4) t =  3; year += t;       v -= t * 365;
308
309  if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
310    ms[1] = 29;
311  for (mon = 0;; mon++)
312  {
313    unsigned s = ms[mon];
314    if (v < s)
315      break;
316    v -= s;
317  }
318  s = UIntToStr(s, year, 4); *s++ = '-';
319  UIntToStr_2(s, mon + 1); s[2] = '-'; s += 3;
320  UIntToStr_2(s, (unsigned)v + 1); s[2] = ' '; s += 3;
321  UIntToStr_2(s, hour); s[2] = ':'; s += 3;
322  UIntToStr_2(s, min); s[2] = ':'; s += 3;
323  UIntToStr_2(s, sec); s[2] = 0;
324}
325
326void PrintError(char *sz)
327{
328  printf("\nERROR: %s\n", sz);
329}
330
331static void GetAttribString(UInt32 wa, Bool isDir, char *s)
332{
333  #ifdef USE_WINDOWS_FILE
334  s[0] = (char)(((wa & FILE_ATTRIBUTE_DIRECTORY) != 0 || isDir) ? 'D' : '.');
335  s[1] = (char)(((wa & FILE_ATTRIBUTE_READONLY ) != 0) ? 'R': '.');
336  s[2] = (char)(((wa & FILE_ATTRIBUTE_HIDDEN   ) != 0) ? 'H': '.');
337  s[3] = (char)(((wa & FILE_ATTRIBUTE_SYSTEM   ) != 0) ? 'S': '.');
338  s[4] = (char)(((wa & FILE_ATTRIBUTE_ARCHIVE  ) != 0) ? 'A': '.');
339  s[5] = 0;
340  #else
341  s[0] = (char)(((wa & (1 << 4)) != 0 || isDir) ? 'D' : '.');
342  s[1] = 0;
343  #endif
344}
345
346// #define NUM_PARENTS_MAX 128
347
348int MY_CDECL main(int numargs, char *args[])
349{
350  CFileInStream archiveStream;
351  CLookToRead lookStream;
352  CSzArEx db;
353  SRes res;
354  ISzAlloc allocImp;
355  ISzAlloc allocTempImp;
356  UInt16 *temp = NULL;
357  size_t tempSize = 0;
358  // UInt32 parents[NUM_PARENTS_MAX];
359
360  printf("\n7z ANSI-C Decoder " MY_VERSION_COPYRIGHT_DATE "\n\n");
361
362  if (numargs == 1)
363  {
364    printf(
365      "Usage: 7zDec <command> <archive_name>\n\n"
366      "<Commands>\n"
367      "  e: Extract files from archive (without using directory names)\n"
368      "  l: List contents of archive\n"
369      "  t: Test integrity of archive\n"
370      "  x: eXtract files with full paths\n");
371    return 0;
372  }
373  
374  if (numargs < 3)
375  {
376    PrintError("incorrect command");
377    return 1;
378  }
379
380  #if defined(_WIN32) && !defined(USE_WINDOWS_FILE) && !defined(UNDER_CE)
381  g_FileCodePage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
382  #endif
383
384  allocImp.Alloc = SzAlloc;
385  allocImp.Free = SzFree;
386
387  allocTempImp.Alloc = SzAllocTemp;
388  allocTempImp.Free = SzFreeTemp;
389
390  #ifdef UNDER_CE
391  if (InFile_OpenW(&archiveStream.file, L"\test.7z"))
392  #else
393  if (InFile_Open(&archiveStream.file, args[2]))
394  #endif
395  {
396    PrintError("can not open input file");
397    return 1;
398  }
399
400  FileInStream_CreateVTable(&archiveStream);
401  LookToRead_CreateVTable(&lookStream, False);
402  
403  lookStream.realStream = &archiveStream.s;
404  LookToRead_Init(&lookStream);
405
406  CrcGenerateTable();
407
408  SzArEx_Init(&db);
409  
410  res = SzArEx_Open(&db, &lookStream.s, &allocImp, &allocTempImp);
411  
412  if (res == SZ_OK)
413  {
414    char *command = args[1];
415    int listCommand = 0, testCommand = 0, fullPaths = 0;
416    
417    if (strcmp(command, "l") == 0) listCommand = 1;
418    else if (strcmp(command, "t") == 0) testCommand = 1;
419    else if (strcmp(command, "e") == 0) { }
420    else if (strcmp(command, "x") == 0) { fullPaths = 1; }
421    else
422    {
423      PrintError("incorrect command");
424      res = SZ_ERROR_FAIL;
425    }
426
427    if (res == SZ_OK)
428    {
429      UInt32 i;
430
431      /*
432      if you need cache, use these 3 variables.
433      if you use external function, you can make these variable as static.
434      */
435      UInt32 blockIndex = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */
436      Byte *outBuffer = 0; /* it must be 0 before first call for each new archive. */
437      size_t outBufferSize = 0;  /* it can have any value before first call (if outBuffer = 0) */
438
439      for (i = 0; i < db.NumFiles; i++)
440      {
441        size_t offset = 0;
442        size_t outSizeProcessed = 0;
443        // const CSzFileItem *f = db.Files + i;
444        size_t len;
445        unsigned isDir = SzArEx_IsDir(&db, i);
446        if (listCommand == 0 && isDir && !fullPaths)
447          continue;
448        len = SzArEx_GetFileNameUtf16(&db, i, NULL);
449        // len = SzArEx_GetFullNameLen(&db, i);
450
451        if (len > tempSize)
452        {
453          SzFree(NULL, temp);
454          tempSize = len;
455          temp = (UInt16 *)SzAlloc(NULL, tempSize * sizeof(temp[0]));
456          if (!temp)
457          {
458            res = SZ_ERROR_MEM;
459            break;
460          }
461        }
462
463        SzArEx_GetFileNameUtf16(&db, i, temp);
464        /*
465        if (SzArEx_GetFullNameUtf16_Back(&db, i, temp + len) != temp)
466        {
467          res = SZ_ERROR_FAIL;
468          break;
469        }
470        */
471
472        if (listCommand)
473        {
474          char attr[8], s[32], t[32];
475          UInt64 fileSize;
476
477          GetAttribString(SzBitWithVals_Check(&db.Attribs, i) ? db.Attribs.Vals[i] : 0, isDir, attr);
478
479          fileSize = SzArEx_GetFileSize(&db, i);
480          UInt64ToStr(fileSize, s);
481          
482          if (SzBitWithVals_Check(&db.MTime, i))
483            ConvertFileTimeToString(&db.MTime.Vals[i], t);
484          else
485          {
486            size_t j;
487            for (j = 0; j < 19; j++)
488              t[j] = ' ';
489            t[j] = '\0';
490          }
491          
492          printf("%s %s %10s  ", t, attr, s);
493          res = PrintString(temp);
494          if (res != SZ_OK)
495            break;
496          if (isDir)
497            printf("/");
498          printf("\n");
499          continue;
500        }
501
502        fputs(testCommand ?
503            "Testing    ":
504            "Extracting ",
505            stdout);
506        res = PrintString(temp);
507        if (res != SZ_OK)
508          break;
509        
510        if (isDir)
511          printf("/");
512        else
513        {
514          res = SzArEx_Extract(&db, &lookStream.s, i,
515              &blockIndex, &outBuffer, &outBufferSize,
516              &offset, &outSizeProcessed,
517              &allocImp, &allocTempImp);
518          if (res != SZ_OK)
519            break;
520        }
521        
522        if (!testCommand)
523        {
524          CSzFile outFile;
525          size_t processedSize;
526          size_t j;
527          UInt16 *name = (UInt16 *)temp;
528          const UInt16 *destPath = (const UInt16 *)name;
529 
530          for (j = 0; name[j] != 0; j++)
531            if (name[j] == '/')
532            {
533              if (fullPaths)
534              {
535                name[j] = 0;
536                MyCreateDir(name);
537                name[j] = CHAR_PATH_SEPARATOR;
538              }
539              else
540                destPath = name + j + 1;
541            }
542    
543          if (isDir)
544          {
545            MyCreateDir(destPath);
546            printf("\n");
547            continue;
548          }
549          else if (OutFile_OpenUtf16(&outFile, destPath))
550          {
551            PrintError("can not open output file");
552            res = SZ_ERROR_FAIL;
553            break;
554          }
555
556          processedSize = outSizeProcessed;
557          
558          if (File_Write(&outFile, outBuffer + offset, &processedSize) != 0 || processedSize != outSizeProcessed)
559          {
560            PrintError("can not write output file");
561            res = SZ_ERROR_FAIL;
562            break;
563          }
564          
565          if (File_Close(&outFile))
566          {
567            PrintError("can not close output file");
568            res = SZ_ERROR_FAIL;
569            break;
570          }
571          
572          #ifdef USE_WINDOWS_FILE
573          if (SzBitWithVals_Check(&db.Attribs, i))
574            SetFileAttributesW(destPath, db.Attribs.Vals[i]);
575          #endif
576        }
577        printf("\n");
578      }
579      IAlloc_Free(&allocImp, outBuffer);
580    }
581  }
582
583  SzArEx_Free(&db, &allocImp);
584  SzFree(NULL, temp);
585
586  File_Close(&archiveStream.file);
587  
588  if (res == SZ_OK)
589  {
590    printf("\nEverything is Ok\n");
591    return 0;
592  }
593  
594  if (res == SZ_ERROR_UNSUPPORTED)
595    PrintError("decoder doesn't support this archive");
596  else if (res == SZ_ERROR_MEM)
597    PrintError("can not allocate memory");
598  else if (res == SZ_ERROR_CRC)
599    PrintError("CRC error");
600  else
601    printf("\nERROR #%d\n", res);
602  
603  return 1;
604}