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

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