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

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