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.

Pack.java 33KB

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