Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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