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

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