Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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