You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PackFile.java 31KB

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