選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

PackFile.java 33KB

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