您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

PackFile.java 29KB

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