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 35KB

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