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

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