1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 package org.eclipse.jgit.internal.storage.file;
47
48 import static org.eclipse.jgit.internal.storage.pack.PackExt.BITMAP_INDEX;
49 import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
50 import static org.eclipse.jgit.internal.storage.pack.PackExt.KEEP;
51
52 import java.io.EOFException;
53 import java.io.File;
54 import java.io.FileNotFoundException;
55 import java.io.IOException;
56 import java.io.InterruptedIOException;
57 import java.io.RandomAccessFile;
58 import java.nio.MappedByteBuffer;
59 import java.nio.channels.FileChannel.MapMode;
60 import java.nio.file.AccessDeniedException;
61 import java.nio.file.NoSuchFileException;
62 import java.text.MessageFormat;
63 import java.time.Instant;
64 import java.util.Arrays;
65 import java.util.Collections;
66 import java.util.Comparator;
67 import java.util.Iterator;
68 import java.util.Set;
69 import java.util.concurrent.atomic.AtomicInteger;
70 import java.util.zip.CRC32;
71 import java.util.zip.DataFormatException;
72 import java.util.zip.Inflater;
73
74 import org.eclipse.jgit.errors.CorruptObjectException;
75 import org.eclipse.jgit.errors.LargeObjectException;
76 import org.eclipse.jgit.errors.MissingObjectException;
77 import org.eclipse.jgit.errors.NoPackSignatureException;
78 import org.eclipse.jgit.errors.PackInvalidException;
79 import org.eclipse.jgit.errors.PackMismatchException;
80 import org.eclipse.jgit.errors.StoredObjectRepresentationNotAvailableException;
81 import org.eclipse.jgit.errors.UnpackException;
82 import org.eclipse.jgit.errors.UnsupportedPackIndexVersionException;
83 import org.eclipse.jgit.errors.UnsupportedPackVersionException;
84 import org.eclipse.jgit.internal.JGitText;
85 import org.eclipse.jgit.internal.storage.pack.BinaryDelta;
86 import org.eclipse.jgit.internal.storage.pack.ObjectToPack;
87 import org.eclipse.jgit.internal.storage.pack.PackExt;
88 import org.eclipse.jgit.internal.storage.pack.PackOutputStream;
89 import org.eclipse.jgit.lib.AbbreviatedObjectId;
90 import org.eclipse.jgit.lib.AnyObjectId;
91 import org.eclipse.jgit.lib.Constants;
92 import org.eclipse.jgit.lib.ObjectId;
93 import org.eclipse.jgit.lib.ObjectLoader;
94 import org.eclipse.jgit.util.LongList;
95 import org.eclipse.jgit.util.NB;
96 import org.eclipse.jgit.util.RawParseUtils;
97 import org.slf4j.Logger;
98 import org.slf4j.LoggerFactory;
99
100
101
102
103
104
105 public class PackFile implements Iterable<PackIndex.MutableEntry> {
106 private final static Logger LOG = LoggerFactory.getLogger(PackFile.class);
107
108 public static final Comparator<PackFile> SORT = new Comparator<PackFile>() {
109 @Override
110 public int compare(PackFile a, PackFile b) {
111 return b.packLastModified.compareTo(a.packLastModified);
112 }
113 };
114
115 private final File packFile;
116
117 private final int extensions;
118
119 private File keepFile;
120
121 private volatile String packName;
122
123 final int hash;
124
125 private RandomAccessFile fd;
126
127
128 private final Object readLock = new Object();
129
130 long length;
131
132 private int activeWindows;
133
134 private int activeCopyRawData;
135
136 Instant packLastModified;
137
138 private PackFileSnapshot fileSnapshot;
139
140 private volatile boolean invalid;
141
142 private volatile Exception invalidatingCause;
143
144 private boolean invalidBitmap;
145
146 private AtomicInteger transientErrorCount = new AtomicInteger();
147
148 private byte[] packChecksum;
149
150 private volatile PackIndex loadedIdx;
151
152 private PackReverseIndex reverseIdx;
153
154 private PackBitmapIndex bitmapIdx;
155
156
157
158
159
160
161
162
163 private volatile LongList corruptObjects;
164
165
166
167
168
169
170
171
172
173 public PackFile(File packFile, int extensions) {
174 this.packFile = packFile;
175 this.fileSnapshot = PackFileSnapshot.save(packFile);
176 this.packLastModified = fileSnapshot.lastModifiedInstant();
177 this.extensions = extensions;
178
179
180
181
182 hash = System.identityHashCode(this) * 31;
183 length = Long.MAX_VALUE;
184 }
185
186 private PackIndex idx() throws IOException {
187 PackIndex idx = loadedIdx;
188 if (idx == null) {
189 synchronized (this) {
190 idx = loadedIdx;
191 if (idx == null) {
192 if (invalid) {
193 throw new PackInvalidException(packFile, invalidatingCause);
194 }
195 try {
196 long start = System.currentTimeMillis();
197 idx = PackIndex.open(extFile(INDEX));
198 if (LOG.isDebugEnabled()) {
199 LOG.debug(String.format(
200 "Opening pack index %s, size %.3f MB took %d ms",
201 extFile(INDEX).getAbsolutePath(),
202 Float.valueOf(extFile(INDEX).length()
203 / (1024f * 1024)),
204 Long.valueOf(System.currentTimeMillis()
205 - start)));
206 }
207
208 if (packChecksum == null) {
209 packChecksum = idx.packChecksum;
210 fileSnapshot.setChecksum(
211 ObjectId.fromRaw(packChecksum));
212 } else if (!Arrays.equals(packChecksum,
213 idx.packChecksum)) {
214 throw new PackMismatchException(MessageFormat
215 .format(JGitText.get().packChecksumMismatch,
216 packFile.getPath(),
217 ObjectId.fromRaw(packChecksum)
218 .name(),
219 ObjectId.fromRaw(idx.packChecksum)
220 .name()));
221 }
222 loadedIdx = idx;
223 } catch (InterruptedIOException e) {
224
225
226 throw e;
227 } catch (IOException e) {
228 invalid = true;
229 invalidatingCause = e;
230 throw e;
231 }
232 }
233 }
234 }
235 return idx;
236 }
237
238
239
240
241
242 public File getPackFile() {
243 return packFile;
244 }
245
246
247
248
249
250
251
252 public PackIndex getIndex() throws IOException {
253 return idx();
254 }
255
256
257
258
259
260
261 public String getPackName() {
262 String name = packName;
263 if (name == null) {
264 name = getPackFile().getName();
265 if (name.startsWith("pack-"))
266 name = name.substring("pack-".length());
267 if (name.endsWith(".pack"))
268 name = name.substring(0, name.length() - ".pack".length());
269 packName = name;
270 }
271 return name;
272 }
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287 public boolean hasObject(AnyObjectId id) throws IOException {
288 final long offset = idx().findOffset(id);
289 return 0 < offset && !isCorrupt(offset);
290 }
291
292
293
294
295
296
297 public boolean shouldBeKept() {
298 if (keepFile == null)
299 keepFile = extFile(KEEP);
300 return keepFile.exists();
301 }
302
303
304
305
306
307
308
309
310
311
312
313
314
315 ObjectLoader get(WindowCursor curs, AnyObjectId id)
316 throws IOException {
317 final long offset = idx().findOffset(id);
318 return 0 < offset && !isCorrupt(offset) ? load(curs, offset) : null;
319 }
320
321 void resolve(Set<ObjectId> matches, AbbreviatedObjectId id, int matchLimit)
322 throws IOException {
323 idx().resolve(matches, id, matchLimit);
324 }
325
326
327
328
329 public void close() {
330 WindowCache.purge(this);
331 synchronized (this) {
332 loadedIdx = null;
333 reverseIdx = null;
334 }
335 }
336
337
338
339
340
341
342
343
344
345
346
347
348
349 @Override
350 public Iterator<PackIndex.MutableEntry> iterator() {
351 try {
352 return idx().iterator();
353 } catch (IOException e) {
354 return Collections.<PackIndex.MutableEntry> emptyList().iterator();
355 }
356 }
357
358
359
360
361
362
363
364
365
366 long getObjectCount() throws IOException {
367 return idx().getObjectCount();
368 }
369
370
371
372
373
374
375
376
377
378
379
380 ObjectId findObjectForOffset(long offset) throws IOException {
381 return getReverseIdx().findObject(offset);
382 }
383
384
385
386
387
388
389
390 PackFileSnapshot getFileSnapshot() {
391 return fileSnapshot;
392 }
393
394 AnyObjectId getPackChecksum() {
395 return ObjectId.fromRaw(packChecksum);
396 }
397
398 private final byte[] decompress(final long position, final int sz,
399 final WindowCursor curs) throws IOException, DataFormatException {
400 byte[] dstbuf;
401 try {
402 dstbuf = new byte[sz];
403 } catch (OutOfMemoryError noMemory) {
404
405
406
407
408
409
410
411 return null;
412 }
413
414 if (curs.inflate(this, position, dstbuf, false) != sz)
415 throw new EOFException(MessageFormat.format(
416 JGitText.get().shortCompressedStreamAt,
417 Long.valueOf(position)));
418 return dstbuf;
419 }
420
421 void copyPackAsIs(PackOutputStream out, WindowCursor curs)
422 throws IOException {
423
424 curs.pin(this, 0);
425 curs.copyPackAsIs(this, length, out);
426 }
427
428 final void copyAsIs(PackOutputStream out, LocalObjectToPack src,
429 boolean validate, WindowCursor curs) throws IOException,
430 StoredObjectRepresentationNotAvailableException {
431 beginCopyAsIs(src);
432 try {
433 copyAsIs2(out, src, validate, curs);
434 } finally {
435 endCopyAsIs();
436 }
437 }
438
439 private void copyAsIs2(PackOutputStream out, LocalObjectToPack src,
440 boolean validate, WindowCursor curs) throws IOException,
441 StoredObjectRepresentationNotAvailableException {
442 final CRC32 crc1 = validate ? new CRC32() : null;
443 final CRC32 crc2 = validate ? new CRC32() : null;
444 final byte[] buf = out.getCopyBuffer();
445
446
447
448 readFully(src.offset, buf, 0, 20, curs);
449 int c = buf[0] & 0xff;
450 final int typeCode = (c >> 4) & 7;
451 long inflatedLength = c & 15;
452 int shift = 4;
453 int headerCnt = 1;
454 while ((c & 0x80) != 0) {
455 c = buf[headerCnt++] & 0xff;
456 inflatedLength += ((long) (c & 0x7f)) << shift;
457 shift += 7;
458 }
459
460 if (typeCode == Constants.OBJ_OFS_DELTA) {
461 do {
462 c = buf[headerCnt++] & 0xff;
463 } while ((c & 128) != 0);
464 if (validate) {
465 assert(crc1 != null && crc2 != null);
466 crc1.update(buf, 0, headerCnt);
467 crc2.update(buf, 0, headerCnt);
468 }
469 } else if (typeCode == Constants.OBJ_REF_DELTA) {
470 if (validate) {
471 assert(crc1 != null && crc2 != null);
472 crc1.update(buf, 0, headerCnt);
473 crc2.update(buf, 0, headerCnt);
474 }
475
476 readFully(src.offset + headerCnt, buf, 0, 20, curs);
477 if (validate) {
478 assert(crc1 != null && crc2 != null);
479 crc1.update(buf, 0, 20);
480 crc2.update(buf, 0, 20);
481 }
482 headerCnt += 20;
483 } else if (validate) {
484 assert(crc1 != null && crc2 != null);
485 crc1.update(buf, 0, headerCnt);
486 crc2.update(buf, 0, headerCnt);
487 }
488
489 final long dataOffset = src.offset + headerCnt;
490 final long dataLength = src.length;
491 final long expectedCRC;
492 final ByteArrayWindow quickCopy;
493
494
495
496
497 try {
498 quickCopy = curs.quickCopy(this, dataOffset, dataLength);
499
500 if (validate && idx().hasCRC32Support()) {
501 assert(crc1 != null);
502
503
504 expectedCRC = idx().findCRC32(src);
505 if (quickCopy != null) {
506 quickCopy.crc32(crc1, dataOffset, (int) dataLength);
507 } else {
508 long pos = dataOffset;
509 long cnt = dataLength;
510 while (cnt > 0) {
511 final int n = (int) Math.min(cnt, buf.length);
512 readFully(pos, buf, 0, n, curs);
513 crc1.update(buf, 0, n);
514 pos += n;
515 cnt -= n;
516 }
517 }
518 if (crc1.getValue() != expectedCRC) {
519 setCorrupt(src.offset);
520 throw new CorruptObjectException(MessageFormat.format(
521 JGitText.get().objectAtHasBadZlibStream,
522 Long.valueOf(src.offset), getPackFile()));
523 }
524 } else if (validate) {
525
526
527
528
529 Inflater inf = curs.inflater();
530 byte[] tmp = new byte[1024];
531 if (quickCopy != null) {
532 quickCopy.check(inf, tmp, dataOffset, (int) dataLength);
533 } else {
534 assert(crc1 != null);
535 long pos = dataOffset;
536 long cnt = dataLength;
537 while (cnt > 0) {
538 final int n = (int) Math.min(cnt, buf.length);
539 readFully(pos, buf, 0, n, curs);
540 crc1.update(buf, 0, n);
541 inf.setInput(buf, 0, n);
542 while (inf.inflate(tmp, 0, tmp.length) > 0)
543 continue;
544 pos += n;
545 cnt -= n;
546 }
547 }
548 if (!inf.finished() || inf.getBytesRead() != dataLength) {
549 setCorrupt(src.offset);
550 throw new EOFException(MessageFormat.format(
551 JGitText.get().shortCompressedStreamAt,
552 Long.valueOf(src.offset)));
553 }
554 assert(crc1 != null);
555 expectedCRC = crc1.getValue();
556 } else {
557 expectedCRC = -1;
558 }
559 } catch (DataFormatException dataFormat) {
560 setCorrupt(src.offset);
561
562 CorruptObjectException corruptObject = new CorruptObjectException(
563 MessageFormat.format(
564 JGitText.get().objectAtHasBadZlibStream,
565 Long.valueOf(src.offset), getPackFile()),
566 dataFormat);
567
568 throw new StoredObjectRepresentationNotAvailableException(src,
569 corruptObject);
570
571 } catch (IOException ioError) {
572 throw new StoredObjectRepresentationNotAvailableException(src,
573 ioError);
574 }
575
576 if (quickCopy != null) {
577
578
579
580 out.writeHeader(src, inflatedLength);
581 quickCopy.write(out, dataOffset, (int) dataLength);
582
583 } else if (dataLength <= buf.length) {
584
585
586
587 if (!validate) {
588 long pos = dataOffset;
589 long cnt = dataLength;
590 while (cnt > 0) {
591 final int n = (int) Math.min(cnt, buf.length);
592 readFully(pos, buf, 0, n, curs);
593 pos += n;
594 cnt -= n;
595 }
596 }
597 out.writeHeader(src, inflatedLength);
598 out.write(buf, 0, (int) dataLength);
599 } else {
600
601
602
603
604 out.writeHeader(src, inflatedLength);
605 long pos = dataOffset;
606 long cnt = dataLength;
607 while (cnt > 0) {
608 final int n = (int) Math.min(cnt, buf.length);
609 readFully(pos, buf, 0, n, curs);
610 if (validate) {
611 assert(crc2 != null);
612 crc2.update(buf, 0, n);
613 }
614 out.write(buf, 0, n);
615 pos += n;
616 cnt -= n;
617 }
618 if (validate) {
619 assert(crc2 != null);
620 if (crc2.getValue() != expectedCRC) {
621 throw new CorruptObjectException(MessageFormat.format(
622 JGitText.get().objectAtHasBadZlibStream,
623 Long.valueOf(src.offset), getPackFile()));
624 }
625 }
626 }
627 }
628
629 boolean invalid() {
630 return invalid;
631 }
632
633 void setInvalid() {
634 invalid = true;
635 }
636
637 int incrementTransientErrorCount() {
638 return transientErrorCount.incrementAndGet();
639 }
640
641 void resetTransientErrorCount() {
642 transientErrorCount.set(0);
643 }
644
645 private void readFully(final long position, final byte[] dstbuf,
646 int dstoff, final int cnt, final WindowCursor curs)
647 throws IOException {
648 if (curs.copy(this, position, dstbuf, dstoff, cnt) != cnt)
649 throw new EOFException();
650 }
651
652 private synchronized void beginCopyAsIs(ObjectToPack otp)
653 throws StoredObjectRepresentationNotAvailableException {
654 if (++activeCopyRawData == 1 && activeWindows == 0) {
655 try {
656 doOpen();
657 } catch (IOException thisPackNotValid) {
658 throw new StoredObjectRepresentationNotAvailableException(otp,
659 thisPackNotValid);
660 }
661 }
662 }
663
664 private synchronized void endCopyAsIs() {
665 if (--activeCopyRawData == 0 && activeWindows == 0)
666 doClose();
667 }
668
669 synchronized boolean beginWindowCache() throws IOException {
670 if (++activeWindows == 1) {
671 if (activeCopyRawData == 0)
672 doOpen();
673 return true;
674 }
675 return false;
676 }
677
678 synchronized boolean endWindowCache() {
679 final boolean r = --activeWindows == 0;
680 if (r && activeCopyRawData == 0)
681 doClose();
682 return r;
683 }
684
685 private void doOpen() throws IOException {
686 if (invalid) {
687 openFail(true, invalidatingCause);
688 throw new PackInvalidException(packFile, invalidatingCause);
689 }
690 try {
691 synchronized (readLock) {
692 fd = new RandomAccessFile(packFile, "r");
693 length = fd.length();
694 onOpenPack();
695 }
696 } catch (InterruptedIOException e) {
697
698 openFail(false, e);
699 throw e;
700 } catch (FileNotFoundException fn) {
701
702
703
704 openFail(!packFile.exists(), fn);
705 throw fn;
706 } catch (EOFException | AccessDeniedException | NoSuchFileException
707 | CorruptObjectException | NoPackSignatureException
708 | PackMismatchException | UnpackException
709 | UnsupportedPackIndexVersionException
710 | UnsupportedPackVersionException pe) {
711
712 openFail(true, pe);
713 throw pe;
714 } catch (IOException | RuntimeException ge) {
715
716
717 openFail(false, ge);
718 throw ge;
719 }
720 }
721
722 private void openFail(boolean invalidate, Exception cause) {
723 activeWindows = 0;
724 activeCopyRawData = 0;
725 invalid = invalidate;
726 invalidatingCause = cause;
727 doClose();
728 }
729
730 private void doClose() {
731 synchronized (readLock) {
732 if (fd != null) {
733 try {
734 fd.close();
735 } catch (IOException err) {
736
737
738
739 }
740 fd = null;
741 }
742 }
743 }
744
745 ByteArrayWindow read(long pos, int size) throws IOException {
746 synchronized (readLock) {
747 if (invalid || fd == null) {
748
749
750
751
752
753 throw new PackInvalidException(packFile, invalidatingCause);
754 }
755 if (length < pos + size)
756 size = (int) (length - pos);
757 final byte[] buf = new byte[size];
758 fd.seek(pos);
759 fd.readFully(buf, 0, size);
760 return new ByteArrayWindow(this, pos, buf);
761 }
762 }
763
764 ByteWindow mmap(long pos, int size) throws IOException {
765 synchronized (readLock) {
766 if (length < pos + size)
767 size = (int) (length - pos);
768
769 MappedByteBuffer map;
770 try {
771 map = fd.getChannel().map(MapMode.READ_ONLY, pos, size);
772 } catch (IOException ioe1) {
773
774
775
776
777 System.gc();
778 System.runFinalization();
779 map = fd.getChannel().map(MapMode.READ_ONLY, pos, size);
780 }
781
782 if (map.hasArray())
783 return new ByteArrayWindow(this, pos, map.array());
784 return new ByteBufferWindow(this, pos, map);
785 }
786 }
787
788 private void onOpenPack() throws IOException {
789 final PackIndex idx = idx();
790 final byte[] buf = new byte[20];
791
792 fd.seek(0);
793 fd.readFully(buf, 0, 12);
794 if (RawParseUtils.match(buf, 0, Constants.PACK_SIGNATURE) != 4) {
795 throw new NoPackSignatureException(JGitText.get().notAPACKFile);
796 }
797 final long vers = NB.decodeUInt32(buf, 4);
798 final long packCnt = NB.decodeUInt32(buf, 8);
799 if (vers != 2 && vers != 3) {
800 throw new UnsupportedPackVersionException(vers);
801 }
802
803 if (packCnt != idx.getObjectCount()) {
804 throw new PackMismatchException(MessageFormat.format(
805 JGitText.get().packObjectCountMismatch,
806 Long.valueOf(packCnt), Long.valueOf(idx.getObjectCount()),
807 getPackFile()));
808 }
809
810 fd.seek(length - 20);
811 fd.readFully(buf, 0, 20);
812 if (!Arrays.equals(buf, packChecksum)) {
813 throw new PackMismatchException(MessageFormat.format(
814 JGitText.get().packChecksumMismatch,
815 getPackFile(),
816 ObjectId.fromRaw(buf).name(),
817 ObjectId.fromRaw(idx.packChecksum).name()));
818 }
819 }
820
821 ObjectLoader load(WindowCursor curs, long pos)
822 throws IOException, LargeObjectException {
823 try {
824 final byte[] ib = curs.tempId;
825 Delta delta = null;
826 byte[] data = null;
827 int type = Constants.OBJ_BAD;
828 boolean cached = false;
829
830 SEARCH: for (;;) {
831 readFully(pos, ib, 0, 20, curs);
832 int c = ib[0] & 0xff;
833 final int typeCode = (c >> 4) & 7;
834 long sz = c & 15;
835 int shift = 4;
836 int p = 1;
837 while ((c & 0x80) != 0) {
838 c = ib[p++] & 0xff;
839 sz += ((long) (c & 0x7f)) << shift;
840 shift += 7;
841 }
842
843 switch (typeCode) {
844 case Constants.OBJ_COMMIT:
845 case Constants.OBJ_TREE:
846 case Constants.OBJ_BLOB:
847 case Constants.OBJ_TAG: {
848 if (delta != null || sz < curs.getStreamFileThreshold())
849 data = decompress(pos + p, (int) sz, curs);
850
851 if (delta != null) {
852 type = typeCode;
853 break SEARCH;
854 }
855
856 if (data != null)
857 return new ObjectLoader.SmallObject(typeCode, data);
858 else
859 return new LargePackedWholeObject(typeCode, sz, pos, p,
860 this, curs.db);
861 }
862
863 case Constants.OBJ_OFS_DELTA: {
864 c = ib[p++] & 0xff;
865 long base = c & 127;
866 while ((c & 128) != 0) {
867 base += 1;
868 c = ib[p++] & 0xff;
869 base <<= 7;
870 base += (c & 127);
871 }
872 base = pos - base;
873 delta = new Delta(delta, pos, (int) sz, p, base);
874 if (sz != delta.deltaSize)
875 break SEARCH;
876
877 DeltaBaseCache.Entry e = curs.getDeltaBaseCache().get(this, base);
878 if (e != null) {
879 type = e.type;
880 data = e.data;
881 cached = true;
882 break SEARCH;
883 }
884 pos = base;
885 continue SEARCH;
886 }
887
888 case Constants.OBJ_REF_DELTA: {
889 readFully(pos + p, ib, 0, 20, curs);
890 long base = findDeltaBase(ObjectId.fromRaw(ib));
891 delta = new Delta(delta, pos, (int) sz, p + 20, base);
892 if (sz != delta.deltaSize)
893 break SEARCH;
894
895 DeltaBaseCache.Entry e = curs.getDeltaBaseCache().get(this, base);
896 if (e != null) {
897 type = e.type;
898 data = e.data;
899 cached = true;
900 break SEARCH;
901 }
902 pos = base;
903 continue SEARCH;
904 }
905
906 default:
907 throw new IOException(MessageFormat.format(
908 JGitText.get().unknownObjectType,
909 Integer.valueOf(typeCode)));
910 }
911 }
912
913
914
915
916 if (data == null)
917 throw new IOException(JGitText.get().inMemoryBufferLimitExceeded);
918
919 assert(delta != null);
920 do {
921
922 if (cached)
923 cached = false;
924 else if (delta.next == null)
925 curs.getDeltaBaseCache().store(this, delta.basePos, data, type);
926
927 pos = delta.deltaPos;
928
929 final byte[] cmds = decompress(pos + delta.hdrLen,
930 delta.deltaSize, curs);
931 if (cmds == null) {
932 data = null;
933 throw new LargeObjectException.OutOfMemory(new OutOfMemoryError());
934 }
935
936 final long sz = BinaryDelta.getResultSize(cmds);
937 if (Integer.MAX_VALUE <= sz)
938 throw new LargeObjectException.ExceedsByteArrayLimit();
939
940 final byte[] result;
941 try {
942 result = new byte[(int) sz];
943 } catch (OutOfMemoryError tooBig) {
944 data = null;
945 throw new LargeObjectException.OutOfMemory(tooBig);
946 }
947
948 BinaryDelta.apply(data, cmds, result);
949 data = result;
950 delta = delta.next;
951 } while (delta != null);
952
953 return new ObjectLoader.SmallObject(type, data);
954
955 } catch (DataFormatException dfe) {
956 throw new CorruptObjectException(
957 MessageFormat.format(
958 JGitText.get().objectAtHasBadZlibStream,
959 Long.valueOf(pos), getPackFile()),
960 dfe);
961 }
962 }
963
964 private long findDeltaBase(ObjectId baseId) throws IOException,
965 MissingObjectException {
966 long ofs = idx().findOffset(baseId);
967 if (ofs < 0)
968 throw new MissingObjectException(baseId,
969 JGitText.get().missingDeltaBase);
970 return ofs;
971 }
972
973 private static class Delta {
974
975 final Delta next;
976
977
978 final long deltaPos;
979
980
981 final int deltaSize;
982
983
984 final int hdrLen;
985
986
987 final long basePos;
988
989 Delta(Delta next, long ofs, int sz, int hdrLen, long baseOffset) {
990 this.next = next;
991 this.deltaPos = ofs;
992 this.deltaSize = sz;
993 this.hdrLen = hdrLen;
994 this.basePos = baseOffset;
995 }
996 }
997
998 byte[] getDeltaHeader(WindowCursor wc, long pos)
999 throws IOException, DataFormatException {
1000
1001
1002
1003
1004
1005 final byte[] hdr = new byte[18];
1006 wc.inflate(this, pos, hdr, true );
1007 return hdr;
1008 }
1009
1010 int getObjectType(WindowCursor curs, long pos) throws IOException {
1011 final byte[] ib = curs.tempId;
1012 for (;;) {
1013 readFully(pos, ib, 0, 20, curs);
1014 int c = ib[0] & 0xff;
1015 final int type = (c >> 4) & 7;
1016
1017 switch (type) {
1018 case Constants.OBJ_COMMIT:
1019 case Constants.OBJ_TREE:
1020 case Constants.OBJ_BLOB:
1021 case Constants.OBJ_TAG:
1022 return type;
1023
1024 case Constants.OBJ_OFS_DELTA: {
1025 int p = 1;
1026 while ((c & 0x80) != 0)
1027 c = ib[p++] & 0xff;
1028 c = ib[p++] & 0xff;
1029 long ofs = c & 127;
1030 while ((c & 128) != 0) {
1031 ofs += 1;
1032 c = ib[p++] & 0xff;
1033 ofs <<= 7;
1034 ofs += (c & 127);
1035 }
1036 pos = pos - ofs;
1037 continue;
1038 }
1039
1040 case Constants.OBJ_REF_DELTA: {
1041 int p = 1;
1042 while ((c & 0x80) != 0)
1043 c = ib[p++] & 0xff;
1044 readFully(pos + p, ib, 0, 20, curs);
1045 pos = findDeltaBase(ObjectId.fromRaw(ib));
1046 continue;
1047 }
1048
1049 default:
1050 throw new IOException(
1051 MessageFormat.format(JGitText.get().unknownObjectType,
1052 Integer.valueOf(type)));
1053 }
1054 }
1055 }
1056
1057 long getObjectSize(WindowCursor curs, AnyObjectId id)
1058 throws IOException {
1059 final long offset = idx().findOffset(id);
1060 return 0 < offset ? getObjectSize(curs, offset) : -1;
1061 }
1062
1063 long getObjectSize(WindowCursor curs, long pos)
1064 throws IOException {
1065 final byte[] ib = curs.tempId;
1066 readFully(pos, ib, 0, 20, curs);
1067 int c = ib[0] & 0xff;
1068 final int type = (c >> 4) & 7;
1069 long sz = c & 15;
1070 int shift = 4;
1071 int p = 1;
1072 while ((c & 0x80) != 0) {
1073 c = ib[p++] & 0xff;
1074 sz += ((long) (c & 0x7f)) << shift;
1075 shift += 7;
1076 }
1077
1078 long deltaAt;
1079 switch (type) {
1080 case Constants.OBJ_COMMIT:
1081 case Constants.OBJ_TREE:
1082 case Constants.OBJ_BLOB:
1083 case Constants.OBJ_TAG:
1084 return sz;
1085
1086 case Constants.OBJ_OFS_DELTA:
1087 c = ib[p++] & 0xff;
1088 while ((c & 128) != 0)
1089 c = ib[p++] & 0xff;
1090 deltaAt = pos + p;
1091 break;
1092
1093 case Constants.OBJ_REF_DELTA:
1094 deltaAt = pos + p + 20;
1095 break;
1096
1097 default:
1098 throw new IOException(MessageFormat.format(
1099 JGitText.get().unknownObjectType, Integer.valueOf(type)));
1100 }
1101
1102 try {
1103 return BinaryDelta.getResultSize(getDeltaHeader(curs, deltaAt));
1104 } catch (DataFormatException e) {
1105 throw new CorruptObjectException(MessageFormat.format(
1106 JGitText.get().objectAtHasBadZlibStream, Long.valueOf(pos),
1107 getPackFile()));
1108 }
1109 }
1110
1111 LocalObjectRepresentation representation(final WindowCursor curs,
1112 final AnyObjectId objectId) throws IOException {
1113 final long pos = idx().findOffset(objectId);
1114 if (pos < 0)
1115 return null;
1116
1117 final byte[] ib = curs.tempId;
1118 readFully(pos, ib, 0, 20, curs);
1119 int c = ib[0] & 0xff;
1120 int p = 1;
1121 final int typeCode = (c >> 4) & 7;
1122 while ((c & 0x80) != 0)
1123 c = ib[p++] & 0xff;
1124
1125 long len = (findEndOffset(pos) - pos);
1126 switch (typeCode) {
1127 case Constants.OBJ_COMMIT:
1128 case Constants.OBJ_TREE:
1129 case Constants.OBJ_BLOB:
1130 case Constants.OBJ_TAG:
1131 return LocalObjectRepresentation.newWhole(this, pos, len - p);
1132
1133 case Constants.OBJ_OFS_DELTA: {
1134 c = ib[p++] & 0xff;
1135 long ofs = c & 127;
1136 while ((c & 128) != 0) {
1137 ofs += 1;
1138 c = ib[p++] & 0xff;
1139 ofs <<= 7;
1140 ofs += (c & 127);
1141 }
1142 ofs = pos - ofs;
1143 return LocalObjectRepresentation.newDelta(this, pos, len - p, ofs);
1144 }
1145
1146 case Constants.OBJ_REF_DELTA: {
1147 len -= p;
1148 len -= Constants.OBJECT_ID_LENGTH;
1149 readFully(pos + p, ib, 0, 20, curs);
1150 ObjectId id = ObjectId.fromRaw(ib);
1151 return LocalObjectRepresentation.newDelta(this, pos, len, id);
1152 }
1153
1154 default:
1155 throw new IOException(
1156 MessageFormat.format(JGitText.get().unknownObjectType,
1157 Integer.valueOf(typeCode)));
1158 }
1159 }
1160
1161 private long findEndOffset(long startOffset)
1162 throws IOException, CorruptObjectException {
1163 final long maxOffset = length - 20;
1164 return getReverseIdx().findNextOffset(startOffset, maxOffset);
1165 }
1166
1167 synchronized PackBitmapIndex getBitmapIndex() throws IOException {
1168 if (invalid || invalidBitmap)
1169 return null;
1170 if (bitmapIdx == null && hasExt(BITMAP_INDEX)) {
1171 final PackBitmapIndex idx;
1172 try {
1173 idx = PackBitmapIndex.open(extFile(BITMAP_INDEX), idx(),
1174 getReverseIdx());
1175 } catch (FileNotFoundException e) {
1176
1177
1178
1179 invalidBitmap = true;
1180 return null;
1181 }
1182
1183
1184 if (Arrays.equals(packChecksum, idx.packChecksum))
1185 bitmapIdx = idx;
1186 else
1187 invalidBitmap = true;
1188 }
1189 return bitmapIdx;
1190 }
1191
1192 private synchronized PackReverseIndex getReverseIdx() throws IOException {
1193 if (reverseIdx == null)
1194 reverseIdx = new PackReverseIndex(idx());
1195 return reverseIdx;
1196 }
1197
1198 private boolean isCorrupt(long offset) {
1199 LongList list = corruptObjects;
1200 if (list == null)
1201 return false;
1202 synchronized (list) {
1203 return list.contains(offset);
1204 }
1205 }
1206
1207 private void setCorrupt(long offset) {
1208 LongList list = corruptObjects;
1209 if (list == null) {
1210 synchronized (readLock) {
1211 list = corruptObjects;
1212 if (list == null) {
1213 list = new LongList();
1214 corruptObjects = list;
1215 }
1216 }
1217 }
1218 synchronized (list) {
1219 list.add(offset);
1220 }
1221 }
1222
1223 private File extFile(PackExt ext) {
1224 String p = packFile.getName();
1225 int dot = p.lastIndexOf('.');
1226 String b = (dot < 0) ? p : p.substring(0, dot);
1227 return new File(packFile.getParentFile(), b + '.' + ext.getExtension());
1228 }
1229
1230 private boolean hasExt(PackExt ext) {
1231 return (extensions & ext.getBit()) != 0;
1232 }
1233
1234 @SuppressWarnings("nls")
1235 @Override
1236 public String toString() {
1237 return "PackFile [packFileName=" + packFile.getName() + ", length="
1238 + packFile.length() + ", packChecksum="
1239 + ObjectId.fromRaw(packChecksum).name() + "]";
1240 }
1241 }