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

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