Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

PackFile.java 34KB

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