unbflz.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <bio.h>
  12. #include "bzfs.h"
  13. int
  14. Bgetint(Biobuf *b)
  15. {
  16. uchar p[4];
  17. if(Bread(b, p, 4) != 4)
  18. sysfatal("short read");
  19. return (p[0]<<24)|(p[1]<<16)|(p[2]<<8)|p[3];
  20. }
  21. /*
  22. * memmove but make sure overlap works properly.
  23. */
  24. void
  25. copy(uchar *dst, uchar *src, int n)
  26. {
  27. while(n-- > 0)
  28. *dst++ = *src++;
  29. }
  30. int
  31. unbflz(int in)
  32. {
  33. int rv, out, p[2];
  34. Biobuf *b, bin;
  35. char buf[5];
  36. uchar *data;
  37. int i, j, length, n, m, o, sum;
  38. uint32_t *blk;
  39. int nblk, mblk;
  40. if(pipe(p) < 0)
  41. sysfatal("pipe: %r");
  42. rv = p[0];
  43. out = p[1];
  44. switch(rfork(RFPROC|RFFDG|RFNOTEG|RFMEM)){
  45. case -1:
  46. sysfatal("fork: %r");
  47. case 0:
  48. close(rv);
  49. break;
  50. default:
  51. close(in);
  52. close(out);
  53. return rv;
  54. }
  55. Binit(&bin, in, OREAD);
  56. b = &bin;
  57. if(Bread(b, buf, 4) != 4)
  58. sysfatal("short read");
  59. if(memcmp(buf, "BLZ\n", 4) != 0)
  60. sysfatal("bad header");
  61. length = Bgetint(b);
  62. data = malloc(length);
  63. if(data == nil)
  64. sysfatal("out of memory");
  65. sum = 0;
  66. nblk = 0;
  67. mblk = 0;
  68. blk = nil;
  69. while(sum < length){
  70. if(nblk>=mblk){
  71. mblk += 16384;
  72. blk = realloc(blk, (mblk+1)*sizeof(blk[0]));
  73. if(blk == nil)
  74. sysfatal("out of memory");
  75. }
  76. n = Bgetint(b);
  77. blk[nblk++] = n;
  78. if(n&(1<<31))
  79. n &= ~(1<<31);
  80. else
  81. blk[nblk++] = Bgetint(b);
  82. sum += n;
  83. }
  84. if(sum != length)
  85. sysfatal("bad compressed data %d %d", sum, length);
  86. i = 0;
  87. j = 0;
  88. while(i < length){
  89. assert(j < nblk);
  90. n = blk[j++];
  91. if(n&(1<<31)){
  92. n &= ~(1<<31);
  93. if((m=Bread(b, data+i, n)) != n)
  94. sysfatal("short read %d %d", n, m);
  95. }else{
  96. o = blk[j++];
  97. copy(data+i, data+o, n);
  98. }
  99. i += n;
  100. }
  101. write(out, data, length);
  102. close(in);
  103. close(out);
  104. _exits(0);
  105. return -1;
  106. }