You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PackFile.java 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. /*
  2. * Copyright (C) 2008-2009, Google Inc.
  3. * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2006-2008, Shawn O. Pearce <spearce@spearce.org>
  5. * and other copyright owners as documented in the project's IP log.
  6. *
  7. * This program and the accompanying materials are made available
  8. * under the terms of the Eclipse Distribution License v1.0 which
  9. * accompanies this distribution, is reproduced below, and is
  10. * available at http://www.eclipse.org/org/documents/edl-v10.php
  11. *
  12. * All rights reserved.
  13. *
  14. * Redistribution and use in source and binary forms, with or
  15. * without modification, are permitted provided that the following
  16. * conditions are met:
  17. *
  18. * - Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. *
  21. * - Redistributions in binary form must reproduce the above
  22. * copyright notice, this list of conditions and the following
  23. * disclaimer in the documentation and/or other materials provided
  24. * with the distribution.
  25. *
  26. * - Neither the name of the Eclipse Foundation, Inc. nor the
  27. * names of its contributors may be used to endorse or promote
  28. * products derived from this software without specific prior
  29. * written permission.
  30. *
  31. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  32. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  33. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  34. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  35. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  36. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  37. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  38. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  39. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  40. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  41. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  42. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  43. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. */
  45. package org.eclipse.jgit.internal.storage.file;
  46. import static org.eclipse.jgit.internal.storage.pack.PackExt.BITMAP_INDEX;
  47. import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
  48. import static org.eclipse.jgit.internal.storage.pack.PackExt.KEEP;
  49. import java.io.EOFException;
  50. import java.io.File;
  51. import java.io.FileNotFoundException;
  52. import java.io.IOException;
  53. import java.io.InterruptedIOException;
  54. import java.io.RandomAccessFile;
  55. import java.nio.MappedByteBuffer;
  56. import java.nio.channels.FileChannel.MapMode;
  57. import java.nio.file.AccessDeniedException;
  58. import java.nio.file.NoSuchFileException;
  59. import java.text.MessageFormat;
  60. import java.util.Arrays;
  61. import java.util.Collections;
  62. import java.util.Comparator;
  63. import java.util.Iterator;
  64. import java.util.Set;
  65. import java.util.concurrent.atomic.AtomicInteger;
  66. import java.util.zip.CRC32;
  67. import java.util.zip.DataFormatException;
  68. import java.util.zip.Inflater;
  69. import org.eclipse.jgit.errors.CorruptObjectException;
  70. import org.eclipse.jgit.errors.LargeObjectException;
  71. import org.eclipse.jgit.errors.MissingObjectException;
  72. import org.eclipse.jgit.errors.NoPackSignatureException;
  73. import org.eclipse.jgit.errors.PackInvalidException;
  74. import org.eclipse.jgit.errors.PackMismatchException;
  75. import org.eclipse.jgit.errors.StoredObjectRepresentationNotAvailableException;
  76. import org.eclipse.jgit.errors.UnpackException;
  77. import org.eclipse.jgit.errors.UnsupportedPackIndexVersionException;
  78. import org.eclipse.jgit.errors.UnsupportedPackVersionException;
  79. import org.eclipse.jgit.internal.JGitText;
  80. import org.eclipse.jgit.internal.storage.pack.BinaryDelta;
  81. import org.eclipse.jgit.internal.storage.pack.ObjectToPack;
  82. import org.eclipse.jgit.internal.storage.pack.PackExt;
  83. import org.eclipse.jgit.internal.storage.pack.PackOutputStream;
  84. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  85. import org.eclipse.jgit.lib.AnyObjectId;
  86. import org.eclipse.jgit.lib.Constants;
  87. import org.eclipse.jgit.lib.ObjectId;
  88. import org.eclipse.jgit.lib.ObjectLoader;
  89. import org.eclipse.jgit.util.LongList;
  90. import org.eclipse.jgit.util.NB;
  91. import org.eclipse.jgit.util.RawParseUtils;
  92. /**
  93. * A Git version 2 pack file representation. A pack file contains Git objects in
  94. * delta packed format yielding high compression of lots of object where some
  95. * objects are similar.
  96. */
  97. public class PackFile implements Iterable<PackIndex.MutableEntry> {
  98. /** Sorts PackFiles to be most recently created to least recently created. */
  99. public static final Comparator<PackFile> SORT = new Comparator<PackFile>() {
  100. @Override
  101. public int compare(final PackFile a, final PackFile b) {
  102. return b.packLastModified - a.packLastModified;
  103. }
  104. };
  105. private final File packFile;
  106. private final int extensions;
  107. private File keepFile;
  108. private volatile String packName;
  109. final int hash;
  110. private RandomAccessFile fd;
  111. /** Serializes reads performed against {@link #fd}. */
  112. private final Object readLock = new Object();
  113. long length;
  114. private int activeWindows;
  115. private int activeCopyRawData;
  116. int packLastModified;
  117. private FileSnapshot fileSnapshot;
  118. private volatile boolean invalid;
  119. private volatile Exception invalidatingCause;
  120. private boolean invalidBitmap;
  121. private AtomicInteger transientErrorCount = new AtomicInteger();
  122. private byte[] packChecksum;
  123. private PackIndex loadedIdx;
  124. private PackReverseIndex reverseIdx;
  125. private PackBitmapIndex bitmapIdx;
  126. /**
  127. * Objects we have tried to read, and discovered to be corrupt.
  128. * <p>
  129. * The list is allocated after the first corruption is found, and filled in
  130. * as more entries are discovered. Typically this list is never used, as
  131. * pack files do not usually contain corrupt objects.
  132. */
  133. private volatile LongList corruptObjects;
  134. /**
  135. * Construct a reader for an existing, pre-indexed packfile.
  136. *
  137. * @param packFile
  138. * path of the <code>.pack</code> file holding the data.
  139. * @param extensions
  140. * additional pack file extensions with the same base as the pack
  141. */
  142. public PackFile(final File packFile, int extensions) {
  143. this.packFile = packFile;
  144. this.fileSnapshot = FileSnapshot.save(packFile);
  145. this.packLastModified = (int) (fileSnapshot.lastModified() >> 10);
  146. this.extensions = extensions;
  147. // Multiply by 31 here so we can more directly combine with another
  148. // value in WindowCache.hash(), without doing the multiply there.
  149. //
  150. hash = System.identityHashCode(this) * 31;
  151. length = Long.MAX_VALUE;
  152. }
  153. private synchronized PackIndex idx() throws IOException {
  154. if (loadedIdx == null) {
  155. if (invalid) {
  156. throw new PackInvalidException(packFile, invalidatingCause);
  157. }
  158. try {
  159. final PackIndex idx = PackIndex.open(extFile(INDEX));
  160. if (packChecksum == null) {
  161. packChecksum = idx.packChecksum;
  162. } else if (!Arrays.equals(packChecksum, idx.packChecksum)) {
  163. throw new PackMismatchException(MessageFormat.format(
  164. JGitText.get().packChecksumMismatch,
  165. packFile.getPath()));
  166. }
  167. loadedIdx = idx;
  168. } catch (InterruptedIOException e) {
  169. // don't invalidate the pack, we are interrupted from another thread
  170. throw e;
  171. } catch (IOException e) {
  172. invalid = true;
  173. invalidatingCause = e;
  174. throw e;
  175. }
  176. }
  177. return loadedIdx;
  178. }
  179. /** @return the File object which locates this pack on disk. */
  180. public File getPackFile() {
  181. return packFile;
  182. }
  183. /**
  184. * @return the index for this pack file.
  185. * @throws IOException
  186. */
  187. public PackIndex getIndex() throws IOException {
  188. return idx();
  189. }
  190. /** @return name extracted from {@code pack-*.pack} pattern. */
  191. public String getPackName() {
  192. String name = packName;
  193. if (name == null) {
  194. name = getPackFile().getName();
  195. if (name.startsWith("pack-")) //$NON-NLS-1$
  196. name = name.substring("pack-".length()); //$NON-NLS-1$
  197. if (name.endsWith(".pack")) //$NON-NLS-1$
  198. name = name.substring(0, name.length() - ".pack".length()); //$NON-NLS-1$
  199. packName = name;
  200. }
  201. return name;
  202. }
  203. /**
  204. * Determine if an object is contained within the pack file.
  205. * <p>
  206. * For performance reasons only the index file is searched; the main pack
  207. * content is ignored entirely.
  208. * </p>
  209. *
  210. * @param id
  211. * the object to look for. Must not be null.
  212. * @return true if the object is in this pack; false otherwise.
  213. * @throws IOException
  214. * the index file cannot be loaded into memory.
  215. */
  216. public boolean hasObject(final AnyObjectId id) throws IOException {
  217. final long offset = idx().findOffset(id);
  218. return 0 < offset && !isCorrupt(offset);
  219. }
  220. /**
  221. * Determines whether a .keep file exists for this pack file.
  222. *
  223. * @return true if a .keep file exist.
  224. */
  225. public boolean shouldBeKept() {
  226. if (keepFile == null)
  227. keepFile = extFile(KEEP);
  228. return keepFile.exists();
  229. }
  230. /**
  231. * Get an object from this pack.
  232. *
  233. * @param curs
  234. * temporary working space associated with the calling thread.
  235. * @param id
  236. * the object to obtain from the pack. Must not be null.
  237. * @return the object loader for the requested object if it is contained in
  238. * this pack; null if the object was not found.
  239. * @throws IOException
  240. * the pack file or the index could not be read.
  241. */
  242. ObjectLoader get(final WindowCursor curs, final AnyObjectId id)
  243. throws IOException {
  244. final long offset = idx().findOffset(id);
  245. return 0 < offset && !isCorrupt(offset) ? load(curs, offset) : null;
  246. }
  247. void resolve(Set<ObjectId> matches, AbbreviatedObjectId id, int matchLimit)
  248. throws IOException {
  249. idx().resolve(matches, id, matchLimit);
  250. }
  251. /**
  252. * Close the resources utilized by this repository
  253. */
  254. public void close() {
  255. WindowCache.purge(this);
  256. synchronized (this) {
  257. loadedIdx = null;
  258. reverseIdx = null;
  259. }
  260. }
  261. /**
  262. * Provide iterator over entries in associated pack index, that should also
  263. * exist in this pack file. Objects returned by such iterator are mutable
  264. * during iteration.
  265. * <p>
  266. * Iterator returns objects in SHA-1 lexicographical order.
  267. * </p>
  268. *
  269. * @return iterator over entries of associated pack index
  270. *
  271. * @see PackIndex#iterator()
  272. */
  273. @Override
  274. public Iterator<PackIndex.MutableEntry> iterator() {
  275. try {
  276. return idx().iterator();
  277. } catch (IOException e) {
  278. return Collections.<PackIndex.MutableEntry> emptyList().iterator();
  279. }
  280. }
  281. /**
  282. * Obtain the total number of objects available in this pack. This method
  283. * relies on pack index, giving number of effectively available objects.
  284. *
  285. * @return number of objects in index of this pack, likewise in this pack
  286. * @throws IOException
  287. * the index file cannot be loaded into memory.
  288. */
  289. long getObjectCount() throws IOException {
  290. return idx().getObjectCount();
  291. }
  292. /**
  293. * Search for object id with the specified start offset in associated pack
  294. * (reverse) index.
  295. *
  296. * @param offset
  297. * start offset of object to find
  298. * @return object id for this offset, or null if no object was found
  299. * @throws IOException
  300. * the index file cannot be loaded into memory.
  301. */
  302. ObjectId findObjectForOffset(final long offset) throws IOException {
  303. return getReverseIdx().findObject(offset);
  304. }
  305. /**
  306. * Return the @{@link FileSnapshot} associated to the underlying packfile
  307. * that has been used when the object was created.
  308. *
  309. * @return the packfile @{@link FileSnapshot} that the object is loaded from.
  310. */
  311. FileSnapshot getFileSnapshot() {
  312. return fileSnapshot;
  313. }
  314. private final byte[] decompress(final long position, final int sz,
  315. final WindowCursor curs) throws IOException, DataFormatException {
  316. byte[] dstbuf;
  317. try {
  318. dstbuf = new byte[sz];
  319. } catch (OutOfMemoryError noMemory) {
  320. // The size may be larger than our heap allows, return null to
  321. // let the caller know allocation isn't possible and it should
  322. // use the large object streaming approach instead.
  323. //
  324. // For example, this can occur when sz is 640 MB, and JRE
  325. // maximum heap size is only 256 MB. Even if the JRE has
  326. // 200 MB free, it cannot allocate a 640 MB byte array.
  327. return null;
  328. }
  329. if (curs.inflate(this, position, dstbuf, false) != sz)
  330. throw new EOFException(MessageFormat.format(
  331. JGitText.get().shortCompressedStreamAt,
  332. Long.valueOf(position)));
  333. return dstbuf;
  334. }
  335. void copyPackAsIs(PackOutputStream out, WindowCursor curs)
  336. throws IOException {
  337. // Pin the first window, this ensures the length is accurate.
  338. curs.pin(this, 0);
  339. curs.copyPackAsIs(this, length, out);
  340. }
  341. final void copyAsIs(PackOutputStream out, LocalObjectToPack src,
  342. boolean validate, WindowCursor curs) throws IOException,
  343. StoredObjectRepresentationNotAvailableException {
  344. beginCopyAsIs(src);
  345. try {
  346. copyAsIs2(out, src, validate, curs);
  347. } finally {
  348. endCopyAsIs();
  349. }
  350. }
  351. private void copyAsIs2(PackOutputStream out, LocalObjectToPack src,
  352. boolean validate, WindowCursor curs) throws IOException,
  353. StoredObjectRepresentationNotAvailableException {
  354. final CRC32 crc1 = validate ? new CRC32() : null;
  355. final CRC32 crc2 = validate ? new CRC32() : null;
  356. final byte[] buf = out.getCopyBuffer();
  357. // Rip apart the header so we can discover the size.
  358. //
  359. readFully(src.offset, buf, 0, 20, curs);
  360. int c = buf[0] & 0xff;
  361. final int typeCode = (c >> 4) & 7;
  362. long inflatedLength = c & 15;
  363. int shift = 4;
  364. int headerCnt = 1;
  365. while ((c & 0x80) != 0) {
  366. c = buf[headerCnt++] & 0xff;
  367. inflatedLength += ((long) (c & 0x7f)) << shift;
  368. shift += 7;
  369. }
  370. if (typeCode == Constants.OBJ_OFS_DELTA) {
  371. do {
  372. c = buf[headerCnt++] & 0xff;
  373. } while ((c & 128) != 0);
  374. if (validate) {
  375. assert(crc1 != null && crc2 != null);
  376. crc1.update(buf, 0, headerCnt);
  377. crc2.update(buf, 0, headerCnt);
  378. }
  379. } else if (typeCode == Constants.OBJ_REF_DELTA) {
  380. if (validate) {
  381. assert(crc1 != null && crc2 != null);
  382. crc1.update(buf, 0, headerCnt);
  383. crc2.update(buf, 0, headerCnt);
  384. }
  385. readFully(src.offset + headerCnt, buf, 0, 20, curs);
  386. if (validate) {
  387. assert(crc1 != null && crc2 != null);
  388. crc1.update(buf, 0, 20);
  389. crc2.update(buf, 0, 20);
  390. }
  391. headerCnt += 20;
  392. } else if (validate) {
  393. assert(crc1 != null && crc2 != null);
  394. crc1.update(buf, 0, headerCnt);
  395. crc2.update(buf, 0, headerCnt);
  396. }
  397. final long dataOffset = src.offset + headerCnt;
  398. final long dataLength = src.length;
  399. final long expectedCRC;
  400. final ByteArrayWindow quickCopy;
  401. // Verify the object isn't corrupt before sending. If it is,
  402. // we report it missing instead.
  403. //
  404. try {
  405. quickCopy = curs.quickCopy(this, dataOffset, dataLength);
  406. if (validate && idx().hasCRC32Support()) {
  407. assert(crc1 != null);
  408. // Index has the CRC32 code cached, validate the object.
  409. //
  410. expectedCRC = idx().findCRC32(src);
  411. if (quickCopy != null) {
  412. quickCopy.crc32(crc1, dataOffset, (int) dataLength);
  413. } else {
  414. long pos = dataOffset;
  415. long cnt = dataLength;
  416. while (cnt > 0) {
  417. final int n = (int) Math.min(cnt, buf.length);
  418. readFully(pos, buf, 0, n, curs);
  419. crc1.update(buf, 0, n);
  420. pos += n;
  421. cnt -= n;
  422. }
  423. }
  424. if (crc1.getValue() != expectedCRC) {
  425. setCorrupt(src.offset);
  426. throw new CorruptObjectException(MessageFormat.format(
  427. JGitText.get().objectAtHasBadZlibStream,
  428. Long.valueOf(src.offset), getPackFile()));
  429. }
  430. } else if (validate) {
  431. // We don't have a CRC32 code in the index, so compute it
  432. // now while inflating the raw data to get zlib to tell us
  433. // whether or not the data is safe.
  434. //
  435. Inflater inf = curs.inflater();
  436. byte[] tmp = new byte[1024];
  437. if (quickCopy != null) {
  438. quickCopy.check(inf, tmp, dataOffset, (int) dataLength);
  439. } else {
  440. assert(crc1 != null);
  441. long pos = dataOffset;
  442. long cnt = dataLength;
  443. while (cnt > 0) {
  444. final int n = (int) Math.min(cnt, buf.length);
  445. readFully(pos, buf, 0, n, curs);
  446. crc1.update(buf, 0, n);
  447. inf.setInput(buf, 0, n);
  448. while (inf.inflate(tmp, 0, tmp.length) > 0)
  449. continue;
  450. pos += n;
  451. cnt -= n;
  452. }
  453. }
  454. if (!inf.finished() || inf.getBytesRead() != dataLength) {
  455. setCorrupt(src.offset);
  456. throw new EOFException(MessageFormat.format(
  457. JGitText.get().shortCompressedStreamAt,
  458. Long.valueOf(src.offset)));
  459. }
  460. assert(crc1 != null);
  461. expectedCRC = crc1.getValue();
  462. } else {
  463. expectedCRC = -1;
  464. }
  465. } catch (DataFormatException dataFormat) {
  466. setCorrupt(src.offset);
  467. CorruptObjectException corruptObject = new CorruptObjectException(
  468. MessageFormat.format(
  469. JGitText.get().objectAtHasBadZlibStream,
  470. Long.valueOf(src.offset), getPackFile()));
  471. corruptObject.initCause(dataFormat);
  472. StoredObjectRepresentationNotAvailableException gone;
  473. gone = new StoredObjectRepresentationNotAvailableException(src);
  474. gone.initCause(corruptObject);
  475. throw gone;
  476. } catch (IOException ioError) {
  477. StoredObjectRepresentationNotAvailableException gone;
  478. gone = new StoredObjectRepresentationNotAvailableException(src);
  479. gone.initCause(ioError);
  480. throw gone;
  481. }
  482. if (quickCopy != null) {
  483. // The entire object fits into a single byte array window slice,
  484. // and we have it pinned. Write this out without copying.
  485. //
  486. out.writeHeader(src, inflatedLength);
  487. quickCopy.write(out, dataOffset, (int) dataLength);
  488. } else if (dataLength <= buf.length) {
  489. // Tiny optimization: Lots of objects are very small deltas or
  490. // deflated commits that are likely to fit in the copy buffer.
  491. //
  492. if (!validate) {
  493. long pos = dataOffset;
  494. long cnt = dataLength;
  495. while (cnt > 0) {
  496. final int n = (int) Math.min(cnt, buf.length);
  497. readFully(pos, buf, 0, n, curs);
  498. pos += n;
  499. cnt -= n;
  500. }
  501. }
  502. out.writeHeader(src, inflatedLength);
  503. out.write(buf, 0, (int) dataLength);
  504. } else {
  505. // Now we are committed to sending the object. As we spool it out,
  506. // check its CRC32 code to make sure there wasn't corruption between
  507. // the verification we did above, and us actually outputting it.
  508. //
  509. out.writeHeader(src, inflatedLength);
  510. long pos = dataOffset;
  511. long cnt = dataLength;
  512. while (cnt > 0) {
  513. final int n = (int) Math.min(cnt, buf.length);
  514. readFully(pos, buf, 0, n, curs);
  515. if (validate) {
  516. assert(crc2 != null);
  517. crc2.update(buf, 0, n);
  518. }
  519. out.write(buf, 0, n);
  520. pos += n;
  521. cnt -= n;
  522. }
  523. if (validate) {
  524. assert(crc2 != null);
  525. if (crc2.getValue() != expectedCRC) {
  526. throw new CorruptObjectException(MessageFormat.format(
  527. JGitText.get().objectAtHasBadZlibStream,
  528. Long.valueOf(src.offset), getPackFile()));
  529. }
  530. }
  531. }
  532. }
  533. boolean invalid() {
  534. return invalid;
  535. }
  536. void setInvalid() {
  537. invalid = true;
  538. }
  539. int incrementTransientErrorCount() {
  540. return transientErrorCount.incrementAndGet();
  541. }
  542. void resetTransientErrorCount() {
  543. transientErrorCount.set(0);
  544. }
  545. private void readFully(final long position, final byte[] dstbuf,
  546. int dstoff, final int cnt, final WindowCursor curs)
  547. throws IOException {
  548. if (curs.copy(this, position, dstbuf, dstoff, cnt) != cnt)
  549. throw new EOFException();
  550. }
  551. private synchronized void beginCopyAsIs(ObjectToPack otp)
  552. throws StoredObjectRepresentationNotAvailableException {
  553. if (++activeCopyRawData == 1 && activeWindows == 0) {
  554. try {
  555. doOpen();
  556. } catch (IOException thisPackNotValid) {
  557. StoredObjectRepresentationNotAvailableException gone;
  558. gone = new StoredObjectRepresentationNotAvailableException(otp);
  559. gone.initCause(thisPackNotValid);
  560. throw gone;
  561. }
  562. }
  563. }
  564. private synchronized void endCopyAsIs() {
  565. if (--activeCopyRawData == 0 && activeWindows == 0)
  566. doClose();
  567. }
  568. synchronized boolean beginWindowCache() throws IOException {
  569. if (++activeWindows == 1) {
  570. if (activeCopyRawData == 0)
  571. doOpen();
  572. return true;
  573. }
  574. return false;
  575. }
  576. synchronized boolean endWindowCache() {
  577. final boolean r = --activeWindows == 0;
  578. if (r && activeCopyRawData == 0)
  579. doClose();
  580. return r;
  581. }
  582. private void doOpen() throws IOException {
  583. if (invalid) {
  584. throw new PackInvalidException(packFile, invalidatingCause);
  585. }
  586. try {
  587. synchronized (readLock) {
  588. fd = new RandomAccessFile(packFile, "r"); //$NON-NLS-1$
  589. length = fd.length();
  590. onOpenPack();
  591. }
  592. } catch (InterruptedIOException e) {
  593. // don't invalidate the pack, we are interrupted from another thread
  594. openFail(false, e);
  595. throw e;
  596. } catch (FileNotFoundException fn) {
  597. // don't invalidate the pack if opening an existing file failed
  598. // since it may be related to a temporary lack of resources (e.g.
  599. // max open files)
  600. openFail(!packFile.exists(), fn);
  601. throw fn;
  602. } catch (EOFException | AccessDeniedException | NoSuchFileException
  603. | CorruptObjectException | NoPackSignatureException
  604. | PackMismatchException | UnpackException
  605. | UnsupportedPackIndexVersionException
  606. | UnsupportedPackVersionException pe) {
  607. // exceptions signaling permanent problems with a pack
  608. openFail(true, pe);
  609. throw pe;
  610. } catch (IOException | RuntimeException ge) {
  611. // generic exceptions could be transient so we should not mark the
  612. // pack invalid to avoid false MissingObjectExceptions
  613. openFail(false, ge);
  614. throw ge;
  615. }
  616. }
  617. private void openFail(boolean invalidate, Exception cause) {
  618. activeWindows = 0;
  619. activeCopyRawData = 0;
  620. invalid = invalidate;
  621. invalidatingCause = cause;
  622. doClose();
  623. }
  624. private void doClose() {
  625. synchronized (readLock) {
  626. if (fd != null) {
  627. try {
  628. fd.close();
  629. } catch (IOException err) {
  630. // Ignore a close event. We had it open only for reading.
  631. // There should not be errors related to network buffers
  632. // not flushed, etc.
  633. }
  634. fd = null;
  635. }
  636. }
  637. }
  638. ByteArrayWindow read(final long pos, int size) throws IOException {
  639. synchronized (readLock) {
  640. if (invalid || fd == null) {
  641. // Due to concurrency between a read and another packfile invalidation thread
  642. // one thread could come up to this point and then fail with NPE.
  643. // Detect the situation and throw a proper exception so that can be properly
  644. // managed by the main packfile search loop and the Git client won't receive
  645. // any failures.
  646. throw new PackInvalidException(packFile, invalidatingCause);
  647. }
  648. if (length < pos + size)
  649. size = (int) (length - pos);
  650. final byte[] buf = new byte[size];
  651. fd.seek(pos);
  652. fd.readFully(buf, 0, size);
  653. return new ByteArrayWindow(this, pos, buf);
  654. }
  655. }
  656. ByteWindow mmap(final long pos, int size) throws IOException {
  657. synchronized (readLock) {
  658. if (length < pos + size)
  659. size = (int) (length - pos);
  660. MappedByteBuffer map;
  661. try {
  662. map = fd.getChannel().map(MapMode.READ_ONLY, pos, size);
  663. } catch (IOException ioe1) {
  664. // The most likely reason this failed is the JVM has run out
  665. // of virtual memory. We need to discard quickly, and try to
  666. // force the GC to finalize and release any existing mappings.
  667. //
  668. System.gc();
  669. System.runFinalization();
  670. map = fd.getChannel().map(MapMode.READ_ONLY, pos, size);
  671. }
  672. if (map.hasArray())
  673. return new ByteArrayWindow(this, pos, map.array());
  674. return new ByteBufferWindow(this, pos, map);
  675. }
  676. }
  677. private void onOpenPack() throws IOException {
  678. final PackIndex idx = idx();
  679. final byte[] buf = new byte[20];
  680. fd.seek(0);
  681. fd.readFully(buf, 0, 12);
  682. if (RawParseUtils.match(buf, 0, Constants.PACK_SIGNATURE) != 4) {
  683. throw new NoPackSignatureException(JGitText.get().notAPACKFile);
  684. }
  685. final long vers = NB.decodeUInt32(buf, 4);
  686. final long packCnt = NB.decodeUInt32(buf, 8);
  687. if (vers != 2 && vers != 3) {
  688. throw new UnsupportedPackVersionException(vers);
  689. }
  690. if (packCnt != idx.getObjectCount()) {
  691. throw new PackMismatchException(MessageFormat.format(
  692. JGitText.get().packObjectCountMismatch,
  693. Long.valueOf(packCnt), Long.valueOf(idx.getObjectCount()),
  694. getPackFile()));
  695. }
  696. fd.seek(length - 20);
  697. fd.readFully(buf, 0, 20);
  698. if (!Arrays.equals(buf, packChecksum)) {
  699. throw new PackMismatchException(MessageFormat.format(
  700. JGitText.get().packObjectCountMismatch
  701. , ObjectId.fromRaw(buf).name()
  702. , ObjectId.fromRaw(idx.packChecksum).name()
  703. , getPackFile()));
  704. }
  705. }
  706. ObjectLoader load(final WindowCursor curs, long pos)
  707. throws IOException, LargeObjectException {
  708. try {
  709. final byte[] ib = curs.tempId;
  710. Delta delta = null;
  711. byte[] data = null;
  712. int type = Constants.OBJ_BAD;
  713. boolean cached = false;
  714. SEARCH: for (;;) {
  715. readFully(pos, ib, 0, 20, curs);
  716. int c = ib[0] & 0xff;
  717. final int typeCode = (c >> 4) & 7;
  718. long sz = c & 15;
  719. int shift = 4;
  720. int p = 1;
  721. while ((c & 0x80) != 0) {
  722. c = ib[p++] & 0xff;
  723. sz += ((long) (c & 0x7f)) << shift;
  724. shift += 7;
  725. }
  726. switch (typeCode) {
  727. case Constants.OBJ_COMMIT:
  728. case Constants.OBJ_TREE:
  729. case Constants.OBJ_BLOB:
  730. case Constants.OBJ_TAG: {
  731. if (delta != null || sz < curs.getStreamFileThreshold())
  732. data = decompress(pos + p, (int) sz, curs);
  733. if (delta != null) {
  734. type = typeCode;
  735. break SEARCH;
  736. }
  737. if (data != null)
  738. return new ObjectLoader.SmallObject(typeCode, data);
  739. else
  740. return new LargePackedWholeObject(typeCode, sz, pos, p,
  741. this, curs.db);
  742. }
  743. case Constants.OBJ_OFS_DELTA: {
  744. c = ib[p++] & 0xff;
  745. long base = c & 127;
  746. while ((c & 128) != 0) {
  747. base += 1;
  748. c = ib[p++] & 0xff;
  749. base <<= 7;
  750. base += (c & 127);
  751. }
  752. base = pos - base;
  753. delta = new Delta(delta, pos, (int) sz, p, base);
  754. if (sz != delta.deltaSize)
  755. break SEARCH;
  756. DeltaBaseCache.Entry e = curs.getDeltaBaseCache().get(this, base);
  757. if (e != null) {
  758. type = e.type;
  759. data = e.data;
  760. cached = true;
  761. break SEARCH;
  762. }
  763. pos = base;
  764. continue SEARCH;
  765. }
  766. case Constants.OBJ_REF_DELTA: {
  767. readFully(pos + p, ib, 0, 20, curs);
  768. long base = findDeltaBase(ObjectId.fromRaw(ib));
  769. delta = new Delta(delta, pos, (int) sz, p + 20, base);
  770. if (sz != delta.deltaSize)
  771. break SEARCH;
  772. DeltaBaseCache.Entry e = curs.getDeltaBaseCache().get(this, base);
  773. if (e != null) {
  774. type = e.type;
  775. data = e.data;
  776. cached = true;
  777. break SEARCH;
  778. }
  779. pos = base;
  780. continue SEARCH;
  781. }
  782. default:
  783. throw new IOException(MessageFormat.format(
  784. JGitText.get().unknownObjectType,
  785. Integer.valueOf(typeCode)));
  786. }
  787. }
  788. // At this point there is at least one delta to apply to data.
  789. // (Whole objects with no deltas to apply return early above.)
  790. if (data == null)
  791. throw new IOException(JGitText.get().inMemoryBufferLimitExceeded);
  792. assert(delta != null);
  793. do {
  794. // Cache only the base immediately before desired object.
  795. if (cached)
  796. cached = false;
  797. else if (delta.next == null)
  798. curs.getDeltaBaseCache().store(this, delta.basePos, data, type);
  799. pos = delta.deltaPos;
  800. final byte[] cmds = decompress(pos + delta.hdrLen,
  801. delta.deltaSize, curs);
  802. if (cmds == null) {
  803. data = null; // Discard base in case of OutOfMemoryError
  804. throw new LargeObjectException.OutOfMemory(new OutOfMemoryError());
  805. }
  806. final long sz = BinaryDelta.getResultSize(cmds);
  807. if (Integer.MAX_VALUE <= sz)
  808. throw new LargeObjectException.ExceedsByteArrayLimit();
  809. final byte[] result;
  810. try {
  811. result = new byte[(int) sz];
  812. } catch (OutOfMemoryError tooBig) {
  813. data = null; // Discard base in case of OutOfMemoryError
  814. throw new LargeObjectException.OutOfMemory(tooBig);
  815. }
  816. BinaryDelta.apply(data, cmds, result);
  817. data = result;
  818. delta = delta.next;
  819. } while (delta != null);
  820. return new ObjectLoader.SmallObject(type, data);
  821. } catch (DataFormatException dfe) {
  822. CorruptObjectException coe = new CorruptObjectException(
  823. MessageFormat.format(
  824. JGitText.get().objectAtHasBadZlibStream,
  825. Long.valueOf(pos), getPackFile()));
  826. coe.initCause(dfe);
  827. throw coe;
  828. }
  829. }
  830. private long findDeltaBase(ObjectId baseId) throws IOException,
  831. MissingObjectException {
  832. long ofs = idx().findOffset(baseId);
  833. if (ofs < 0)
  834. throw new MissingObjectException(baseId,
  835. JGitText.get().missingDeltaBase);
  836. return ofs;
  837. }
  838. private static class Delta {
  839. /** Child that applies onto this object. */
  840. final Delta next;
  841. /** Offset of the delta object. */
  842. final long deltaPos;
  843. /** Size of the inflated delta stream. */
  844. final int deltaSize;
  845. /** Total size of the delta's pack entry header (including base). */
  846. final int hdrLen;
  847. /** Offset of the base object this delta applies onto. */
  848. final long basePos;
  849. Delta(Delta next, long ofs, int sz, int hdrLen, long baseOffset) {
  850. this.next = next;
  851. this.deltaPos = ofs;
  852. this.deltaSize = sz;
  853. this.hdrLen = hdrLen;
  854. this.basePos = baseOffset;
  855. }
  856. }
  857. byte[] getDeltaHeader(WindowCursor wc, long pos)
  858. throws IOException, DataFormatException {
  859. // The delta stream starts as two variable length integers. If we
  860. // assume they are 64 bits each, we need 16 bytes to encode them,
  861. // plus 2 extra bytes for the variable length overhead. So 18 is
  862. // the longest delta instruction header.
  863. //
  864. final byte[] hdr = new byte[18];
  865. wc.inflate(this, pos, hdr, true /* headerOnly */);
  866. return hdr;
  867. }
  868. int getObjectType(final WindowCursor curs, long pos) throws IOException {
  869. final byte[] ib = curs.tempId;
  870. for (;;) {
  871. readFully(pos, ib, 0, 20, curs);
  872. int c = ib[0] & 0xff;
  873. final int type = (c >> 4) & 7;
  874. switch (type) {
  875. case Constants.OBJ_COMMIT:
  876. case Constants.OBJ_TREE:
  877. case Constants.OBJ_BLOB:
  878. case Constants.OBJ_TAG:
  879. return type;
  880. case Constants.OBJ_OFS_DELTA: {
  881. int p = 1;
  882. while ((c & 0x80) != 0)
  883. c = ib[p++] & 0xff;
  884. c = ib[p++] & 0xff;
  885. long ofs = c & 127;
  886. while ((c & 128) != 0) {
  887. ofs += 1;
  888. c = ib[p++] & 0xff;
  889. ofs <<= 7;
  890. ofs += (c & 127);
  891. }
  892. pos = pos - ofs;
  893. continue;
  894. }
  895. case Constants.OBJ_REF_DELTA: {
  896. int p = 1;
  897. while ((c & 0x80) != 0)
  898. c = ib[p++] & 0xff;
  899. readFully(pos + p, ib, 0, 20, curs);
  900. pos = findDeltaBase(ObjectId.fromRaw(ib));
  901. continue;
  902. }
  903. default:
  904. throw new IOException(
  905. MessageFormat.format(JGitText.get().unknownObjectType,
  906. Integer.valueOf(type)));
  907. }
  908. }
  909. }
  910. long getObjectSize(final WindowCursor curs, final AnyObjectId id)
  911. throws IOException {
  912. final long offset = idx().findOffset(id);
  913. return 0 < offset ? getObjectSize(curs, offset) : -1;
  914. }
  915. long getObjectSize(final WindowCursor curs, final long pos)
  916. throws IOException {
  917. final byte[] ib = curs.tempId;
  918. readFully(pos, ib, 0, 20, curs);
  919. int c = ib[0] & 0xff;
  920. final int type = (c >> 4) & 7;
  921. long sz = c & 15;
  922. int shift = 4;
  923. int p = 1;
  924. while ((c & 0x80) != 0) {
  925. c = ib[p++] & 0xff;
  926. sz += ((long) (c & 0x7f)) << shift;
  927. shift += 7;
  928. }
  929. long deltaAt;
  930. switch (type) {
  931. case Constants.OBJ_COMMIT:
  932. case Constants.OBJ_TREE:
  933. case Constants.OBJ_BLOB:
  934. case Constants.OBJ_TAG:
  935. return sz;
  936. case Constants.OBJ_OFS_DELTA:
  937. c = ib[p++] & 0xff;
  938. while ((c & 128) != 0)
  939. c = ib[p++] & 0xff;
  940. deltaAt = pos + p;
  941. break;
  942. case Constants.OBJ_REF_DELTA:
  943. deltaAt = pos + p + 20;
  944. break;
  945. default:
  946. throw new IOException(MessageFormat.format(
  947. JGitText.get().unknownObjectType, Integer.valueOf(type)));
  948. }
  949. try {
  950. return BinaryDelta.getResultSize(getDeltaHeader(curs, deltaAt));
  951. } catch (DataFormatException e) {
  952. throw new CorruptObjectException(MessageFormat.format(
  953. JGitText.get().objectAtHasBadZlibStream, Long.valueOf(pos),
  954. getPackFile()));
  955. }
  956. }
  957. LocalObjectRepresentation representation(final WindowCursor curs,
  958. final AnyObjectId objectId) throws IOException {
  959. final long pos = idx().findOffset(objectId);
  960. if (pos < 0)
  961. return null;
  962. final byte[] ib = curs.tempId;
  963. readFully(pos, ib, 0, 20, curs);
  964. int c = ib[0] & 0xff;
  965. int p = 1;
  966. final int typeCode = (c >> 4) & 7;
  967. while ((c & 0x80) != 0)
  968. c = ib[p++] & 0xff;
  969. long len = (findEndOffset(pos) - pos);
  970. switch (typeCode) {
  971. case Constants.OBJ_COMMIT:
  972. case Constants.OBJ_TREE:
  973. case Constants.OBJ_BLOB:
  974. case Constants.OBJ_TAG:
  975. return LocalObjectRepresentation.newWhole(this, pos, len - p);
  976. case Constants.OBJ_OFS_DELTA: {
  977. c = ib[p++] & 0xff;
  978. long ofs = c & 127;
  979. while ((c & 128) != 0) {
  980. ofs += 1;
  981. c = ib[p++] & 0xff;
  982. ofs <<= 7;
  983. ofs += (c & 127);
  984. }
  985. ofs = pos - ofs;
  986. return LocalObjectRepresentation.newDelta(this, pos, len - p, ofs);
  987. }
  988. case Constants.OBJ_REF_DELTA: {
  989. len -= p;
  990. len -= Constants.OBJECT_ID_LENGTH;
  991. readFully(pos + p, ib, 0, 20, curs);
  992. ObjectId id = ObjectId.fromRaw(ib);
  993. return LocalObjectRepresentation.newDelta(this, pos, len, id);
  994. }
  995. default:
  996. throw new IOException(
  997. MessageFormat.format(JGitText.get().unknownObjectType,
  998. Integer.valueOf(typeCode)));
  999. }
  1000. }
  1001. private long findEndOffset(final long startOffset)
  1002. throws IOException, CorruptObjectException {
  1003. final long maxOffset = length - 20;
  1004. return getReverseIdx().findNextOffset(startOffset, maxOffset);
  1005. }
  1006. synchronized PackBitmapIndex getBitmapIndex() throws IOException {
  1007. if (invalid || invalidBitmap)
  1008. return null;
  1009. if (bitmapIdx == null && hasExt(BITMAP_INDEX)) {
  1010. final PackBitmapIndex idx;
  1011. try {
  1012. idx = PackBitmapIndex.open(extFile(BITMAP_INDEX), idx(),
  1013. getReverseIdx());
  1014. } catch (FileNotFoundException e) {
  1015. // Once upon a time this bitmap file existed. Now it
  1016. // has been removed. Most likely an external gc has
  1017. // removed this packfile and the bitmap
  1018. invalidBitmap = true;
  1019. return null;
  1020. }
  1021. // At this point, idx() will have set packChecksum.
  1022. if (Arrays.equals(packChecksum, idx.packChecksum))
  1023. bitmapIdx = idx;
  1024. else
  1025. invalidBitmap = true;
  1026. }
  1027. return bitmapIdx;
  1028. }
  1029. private synchronized PackReverseIndex getReverseIdx() throws IOException {
  1030. if (reverseIdx == null)
  1031. reverseIdx = new PackReverseIndex(idx());
  1032. return reverseIdx;
  1033. }
  1034. private boolean isCorrupt(long offset) {
  1035. LongList list = corruptObjects;
  1036. if (list == null)
  1037. return false;
  1038. synchronized (list) {
  1039. return list.contains(offset);
  1040. }
  1041. }
  1042. private void setCorrupt(long offset) {
  1043. LongList list = corruptObjects;
  1044. if (list == null) {
  1045. synchronized (readLock) {
  1046. list = corruptObjects;
  1047. if (list == null) {
  1048. list = new LongList();
  1049. corruptObjects = list;
  1050. }
  1051. }
  1052. }
  1053. synchronized (list) {
  1054. list.add(offset);
  1055. }
  1056. }
  1057. private File extFile(PackExt ext) {
  1058. String p = packFile.getName();
  1059. int dot = p.lastIndexOf('.');
  1060. String b = (dot < 0) ? p : p.substring(0, dot);
  1061. return new File(packFile.getParentFile(), b + '.' + ext.getExtension());
  1062. }
  1063. private boolean hasExt(PackExt ext) {
  1064. return (extensions & ext.getBit()) != 0;
  1065. }
  1066. }