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.

DfsPackFile.java 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. /*
  2. * Copyright (C) 2008-2011, 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.dfs;
  46. import static org.eclipse.jgit.internal.storage.dfs.DfsObjDatabase.PackSource.UNREACHABLE_GARBAGE;
  47. import static org.eclipse.jgit.internal.storage.pack.PackExt.BITMAP_INDEX;
  48. import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
  49. import static org.eclipse.jgit.internal.storage.pack.PackExt.PACK;
  50. import java.io.BufferedInputStream;
  51. import java.io.EOFException;
  52. import java.io.IOException;
  53. import java.io.InputStream;
  54. import java.nio.ByteBuffer;
  55. import java.nio.channels.Channels;
  56. import java.text.MessageFormat;
  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.LargeObjectException;
  63. import org.eclipse.jgit.errors.MissingObjectException;
  64. import org.eclipse.jgit.errors.PackInvalidException;
  65. import org.eclipse.jgit.errors.StoredObjectRepresentationNotAvailableException;
  66. import org.eclipse.jgit.internal.JGitText;
  67. import org.eclipse.jgit.internal.storage.file.PackBitmapIndex;
  68. import org.eclipse.jgit.internal.storage.file.PackIndex;
  69. import org.eclipse.jgit.internal.storage.file.PackReverseIndex;
  70. import org.eclipse.jgit.internal.storage.pack.BinaryDelta;
  71. import org.eclipse.jgit.internal.storage.pack.PackOutputStream;
  72. import org.eclipse.jgit.internal.storage.pack.StoredObjectRepresentation;
  73. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  74. import org.eclipse.jgit.lib.AnyObjectId;
  75. import org.eclipse.jgit.lib.Constants;
  76. import org.eclipse.jgit.lib.ObjectId;
  77. import org.eclipse.jgit.lib.ObjectLoader;
  78. import org.eclipse.jgit.lib.Repository;
  79. import org.eclipse.jgit.util.LongList;
  80. /**
  81. * A Git version 2 pack file representation. A pack file contains Git objects in
  82. * delta packed format yielding high compression of lots of object where some
  83. * objects are similar.
  84. */
  85. public final class DfsPackFile extends BlockBasedFile {
  86. /**
  87. * Lock for initialization of {@link #index} and {@link #corruptObjects}.
  88. * <p>
  89. * This lock ensures only one thread can perform the initialization work.
  90. */
  91. private final Object initLock = new Object();
  92. /** Index mapping {@link ObjectId} to position within the pack stream. */
  93. private volatile DfsBlockCache.Ref<PackIndex> index;
  94. /** Reverse version of {@link #index} mapping position to {@link ObjectId}. */
  95. private volatile DfsBlockCache.Ref<PackReverseIndex> reverseIndex;
  96. /** Index of compressed bitmap mapping entire object graph. */
  97. private volatile DfsBlockCache.Ref<PackBitmapIndex> bitmapIndex;
  98. /**
  99. * Objects we have tried to read, and discovered to be corrupt.
  100. * <p>
  101. * The list is allocated after the first corruption is found, and filled in
  102. * as more entries are discovered. Typically this list is never used, as
  103. * pack files do not usually contain corrupt objects.
  104. */
  105. private volatile LongList corruptObjects;
  106. /**
  107. * Construct a reader for an existing, packfile.
  108. *
  109. * @param cache
  110. * cache that owns the pack data.
  111. * @param desc
  112. * description of the pack within the DFS.
  113. */
  114. DfsPackFile(DfsBlockCache cache, DfsPackDescription desc) {
  115. super(cache, desc, PACK);
  116. length = desc.getFileSize(PACK);
  117. if (length <= 0)
  118. length = -1;
  119. }
  120. /** @return description that was originally used to configure this pack file. */
  121. public DfsPackDescription getPackDescription() {
  122. return desc;
  123. }
  124. /**
  125. * @return whether the pack index file is loaded and cached in memory.
  126. */
  127. public boolean isIndexLoaded() {
  128. DfsBlockCache.Ref<PackIndex> idxref = index;
  129. return idxref != null && idxref.has();
  130. }
  131. void setPackIndex(PackIndex idx) {
  132. long objCnt = idx.getObjectCount();
  133. int recSize = Constants.OBJECT_ID_LENGTH + 8;
  134. long sz = objCnt * recSize;
  135. index = cache.putRef(desc.getStreamKey(INDEX), sz, idx);
  136. }
  137. /**
  138. * Get the PackIndex for this PackFile.
  139. *
  140. * @param ctx
  141. * reader context to support reading from the backing store if
  142. * the index is not already loaded in memory.
  143. * @return the PackIndex.
  144. * @throws IOException
  145. * the pack index is not available, or is corrupt.
  146. */
  147. public PackIndex getPackIndex(DfsReader ctx) throws IOException {
  148. return idx(ctx);
  149. }
  150. private PackIndex idx(DfsReader ctx) throws IOException {
  151. DfsBlockCache.Ref<PackIndex> idxref = index;
  152. if (idxref != null) {
  153. PackIndex idx = idxref.get();
  154. if (idx != null)
  155. return idx;
  156. }
  157. if (invalid)
  158. throw new PackInvalidException(getFileName());
  159. Repository.getGlobalListenerList()
  160. .dispatch(new BeforeDfsPackIndexLoadedEvent(this));
  161. synchronized (initLock) {
  162. idxref = index;
  163. if (idxref != null) {
  164. PackIndex idx = idxref.get();
  165. if (idx != null)
  166. return idx;
  167. }
  168. DfsStreamKey idxKey = desc.getStreamKey(INDEX);
  169. idxref = cache.getRef(idxKey);
  170. if (idxref != null) {
  171. PackIndex idx = idxref.get();
  172. if (idx != null) {
  173. index = idxref;
  174. return idx;
  175. }
  176. }
  177. PackIndex idx;
  178. try {
  179. ctx.stats.readIdx++;
  180. long start = System.nanoTime();
  181. ReadableChannel rc = ctx.db.openFile(desc, INDEX);
  182. try {
  183. InputStream in = Channels.newInputStream(rc);
  184. int wantSize = 8192;
  185. int bs = rc.blockSize();
  186. if (0 < bs && bs < wantSize)
  187. bs = (wantSize / bs) * bs;
  188. else if (bs <= 0)
  189. bs = wantSize;
  190. idx = PackIndex.read(new BufferedInputStream(in, bs));
  191. ctx.stats.readIdxBytes += rc.position();
  192. } finally {
  193. rc.close();
  194. ctx.stats.readIdxMicros += elapsedMicros(start);
  195. }
  196. } catch (EOFException e) {
  197. invalid = true;
  198. throw new IOException(MessageFormat.format(
  199. DfsText.get().shortReadOfIndex,
  200. desc.getFileName(INDEX)), e);
  201. } catch (IOException e) {
  202. invalid = true;
  203. throw new IOException(MessageFormat.format(
  204. DfsText.get().cannotReadIndex,
  205. desc.getFileName(INDEX)), e);
  206. }
  207. setPackIndex(idx);
  208. return idx;
  209. }
  210. }
  211. final boolean isGarbage() {
  212. return desc.getPackSource() == UNREACHABLE_GARBAGE;
  213. }
  214. PackBitmapIndex getBitmapIndex(DfsReader ctx) throws IOException {
  215. if (invalid || isGarbage() || !desc.hasFileExt(BITMAP_INDEX))
  216. return null;
  217. DfsBlockCache.Ref<PackBitmapIndex> idxref = bitmapIndex;
  218. if (idxref != null) {
  219. PackBitmapIndex idx = idxref.get();
  220. if (idx != null)
  221. return idx;
  222. }
  223. synchronized (initLock) {
  224. idxref = bitmapIndex;
  225. if (idxref != null) {
  226. PackBitmapIndex idx = idxref.get();
  227. if (idx != null)
  228. return idx;
  229. }
  230. DfsStreamKey bitmapKey = desc.getStreamKey(BITMAP_INDEX);
  231. idxref = cache.getRef(bitmapKey);
  232. if (idxref != null) {
  233. PackBitmapIndex idx = idxref.get();
  234. if (idx != null) {
  235. bitmapIndex = idxref;
  236. return idx;
  237. }
  238. }
  239. long size;
  240. PackBitmapIndex idx;
  241. try {
  242. ctx.stats.readBitmap++;
  243. long start = System.nanoTime();
  244. ReadableChannel rc = ctx.db.openFile(desc, BITMAP_INDEX);
  245. try {
  246. InputStream in = Channels.newInputStream(rc);
  247. int wantSize = 8192;
  248. int bs = rc.blockSize();
  249. if (0 < bs && bs < wantSize)
  250. bs = (wantSize / bs) * bs;
  251. else if (bs <= 0)
  252. bs = wantSize;
  253. in = new BufferedInputStream(in, bs);
  254. idx = PackBitmapIndex.read(
  255. in, idx(ctx), getReverseIdx(ctx));
  256. } finally {
  257. size = rc.position();
  258. rc.close();
  259. ctx.stats.readIdxBytes += size;
  260. ctx.stats.readIdxMicros += elapsedMicros(start);
  261. }
  262. } catch (EOFException e) {
  263. throw new IOException(MessageFormat.format(
  264. DfsText.get().shortReadOfIndex,
  265. desc.getFileName(BITMAP_INDEX)), e);
  266. } catch (IOException e) {
  267. throw new IOException(MessageFormat.format(
  268. DfsText.get().cannotReadIndex,
  269. desc.getFileName(BITMAP_INDEX)), e);
  270. }
  271. bitmapIndex = cache.putRef(bitmapKey, size, idx);
  272. return idx;
  273. }
  274. }
  275. PackReverseIndex getReverseIdx(DfsReader ctx) throws IOException {
  276. DfsBlockCache.Ref<PackReverseIndex> revref = reverseIndex;
  277. if (revref != null) {
  278. PackReverseIndex revidx = revref.get();
  279. if (revidx != null)
  280. return revidx;
  281. }
  282. synchronized (initLock) {
  283. revref = reverseIndex;
  284. if (revref != null) {
  285. PackReverseIndex revidx = revref.get();
  286. if (revidx != null)
  287. return revidx;
  288. }
  289. DfsStreamKey revKey =
  290. new DfsStreamKey.ForReverseIndex(desc.getStreamKey(INDEX));
  291. revref = cache.getRef(revKey);
  292. if (revref != null) {
  293. PackReverseIndex idx = revref.get();
  294. if (idx != null) {
  295. reverseIndex = revref;
  296. return idx;
  297. }
  298. }
  299. PackIndex idx = idx(ctx);
  300. PackReverseIndex revidx = new PackReverseIndex(idx);
  301. long cnt = idx.getObjectCount();
  302. reverseIndex = cache.putRef(revKey, cnt * 8, revidx);
  303. return revidx;
  304. }
  305. }
  306. /**
  307. * Check if an object is stored within this pack.
  308. *
  309. * @param ctx
  310. * reader context to support reading from the backing store if
  311. * the index is not already loaded in memory.
  312. * @param id
  313. * object to be located.
  314. * @return true if the object exists in this pack; false if it does not.
  315. * @throws IOException
  316. * the pack index is not available, or is corrupt.
  317. */
  318. public boolean hasObject(DfsReader ctx, AnyObjectId id) throws IOException {
  319. final long offset = idx(ctx).findOffset(id);
  320. return 0 < offset && !isCorrupt(offset);
  321. }
  322. /**
  323. * Get an object from this pack.
  324. *
  325. * @param ctx
  326. * temporary working space associated with the calling thread.
  327. * @param id
  328. * the object to obtain from the pack. Must not be null.
  329. * @return the object loader for the requested object if it is contained in
  330. * this pack; null if the object was not found.
  331. * @throws IOException
  332. * the pack file or the index could not be read.
  333. */
  334. ObjectLoader get(DfsReader ctx, AnyObjectId id)
  335. throws IOException {
  336. long offset = idx(ctx).findOffset(id);
  337. return 0 < offset && !isCorrupt(offset) ? load(ctx, offset) : null;
  338. }
  339. long findOffset(DfsReader ctx, AnyObjectId id) throws IOException {
  340. return idx(ctx).findOffset(id);
  341. }
  342. void resolve(DfsReader ctx, Set<ObjectId> matches, AbbreviatedObjectId id,
  343. int matchLimit) throws IOException {
  344. idx(ctx).resolve(matches, id, matchLimit);
  345. }
  346. /** Release all memory used by this DfsPackFile instance. */
  347. public void close() {
  348. index = null;
  349. reverseIndex = null;
  350. }
  351. /**
  352. * Obtain the total number of objects available in this pack. This method
  353. * relies on pack index, giving number of effectively available objects.
  354. *
  355. * @param ctx
  356. * current reader for the calling thread.
  357. * @return number of objects in index of this pack, likewise in this pack
  358. * @throws IOException
  359. * the index file cannot be loaded into memory.
  360. */
  361. long getObjectCount(DfsReader ctx) throws IOException {
  362. return idx(ctx).getObjectCount();
  363. }
  364. private byte[] decompress(long position, int sz, DfsReader ctx)
  365. throws IOException, DataFormatException {
  366. byte[] dstbuf;
  367. try {
  368. dstbuf = new byte[sz];
  369. } catch (OutOfMemoryError noMemory) {
  370. // The size may be larger than our heap allows, return null to
  371. // let the caller know allocation isn't possible and it should
  372. // use the large object streaming approach instead.
  373. //
  374. // For example, this can occur when sz is 640 MB, and JRE
  375. // maximum heap size is only 256 MB. Even if the JRE has
  376. // 200 MB free, it cannot allocate a 640 MB byte array.
  377. return null;
  378. }
  379. if (ctx.inflate(this, position, dstbuf, false) != sz)
  380. throw new EOFException(MessageFormat.format(
  381. JGitText.get().shortCompressedStreamAt,
  382. Long.valueOf(position)));
  383. return dstbuf;
  384. }
  385. void copyPackAsIs(PackOutputStream out, DfsReader ctx)
  386. throws IOException {
  387. // If the length hasn't been determined yet, pin to set it.
  388. if (length == -1) {
  389. ctx.pin(this, 0);
  390. ctx.unpin();
  391. }
  392. if (cache.shouldCopyThroughCache(length))
  393. copyPackThroughCache(out, ctx);
  394. else
  395. copyPackBypassCache(out, ctx);
  396. }
  397. private void copyPackThroughCache(PackOutputStream out, DfsReader ctx)
  398. throws IOException {
  399. ReadableChannel rc = null;
  400. try {
  401. long position = 12;
  402. long remaining = length - (12 + 20);
  403. while (0 < remaining) {
  404. DfsBlock b;
  405. if (rc != null) {
  406. b = cache.getOrLoad(this, position, ctx, rc);
  407. } else {
  408. b = cache.get(key, alignToBlock(position));
  409. if (b == null) {
  410. rc = ctx.db.openFile(desc, PACK);
  411. int sz = ctx.getOptions().getStreamPackBufferSize();
  412. if (sz > 0) {
  413. rc.setReadAheadBytes(sz);
  414. }
  415. b = cache.getOrLoad(this, position, ctx, rc);
  416. }
  417. }
  418. int ptr = (int) (position - b.start);
  419. int n = (int) Math.min(b.size() - ptr, remaining);
  420. b.write(out, position, n);
  421. position += n;
  422. remaining -= n;
  423. }
  424. } finally {
  425. if (rc != null) {
  426. rc.close();
  427. }
  428. }
  429. }
  430. private long copyPackBypassCache(PackOutputStream out, DfsReader ctx)
  431. throws IOException {
  432. try (ReadableChannel rc = ctx.db.openFile(desc, PACK)) {
  433. ByteBuffer buf = newCopyBuffer(out, rc);
  434. if (ctx.getOptions().getStreamPackBufferSize() > 0)
  435. rc.setReadAheadBytes(ctx.getOptions().getStreamPackBufferSize());
  436. long position = 12;
  437. long remaining = length - (12 + 20);
  438. boolean packHeadSkipped = false;
  439. while (0 < remaining) {
  440. DfsBlock b = cache.get(key, alignToBlock(position));
  441. if (b != null) {
  442. int ptr = (int) (position - b.start);
  443. int n = (int) Math.min(b.size() - ptr, remaining);
  444. b.write(out, position, n);
  445. position += n;
  446. remaining -= n;
  447. rc.position(position);
  448. packHeadSkipped = true;
  449. continue;
  450. }
  451. buf.position(0);
  452. int n = read(rc, buf);
  453. if (n <= 0)
  454. throw packfileIsTruncated();
  455. else if (n > remaining)
  456. n = (int) remaining;
  457. if (!packHeadSkipped) {
  458. // Need skip the 'PACK' header for the first read
  459. out.write(buf.array(), 12, n - 12);
  460. packHeadSkipped = true;
  461. } else {
  462. out.write(buf.array(), 0, n);
  463. }
  464. position += n;
  465. remaining -= n;
  466. }
  467. return position;
  468. }
  469. }
  470. private ByteBuffer newCopyBuffer(PackOutputStream out, ReadableChannel rc) {
  471. int bs = blockSize(rc);
  472. byte[] copyBuf = out.getCopyBuffer();
  473. if (bs > copyBuf.length)
  474. copyBuf = new byte[bs];
  475. return ByteBuffer.wrap(copyBuf, 0, bs);
  476. }
  477. void copyAsIs(PackOutputStream out, DfsObjectToPack src,
  478. boolean validate, DfsReader ctx) throws IOException,
  479. StoredObjectRepresentationNotAvailableException {
  480. final CRC32 crc1 = validate ? new CRC32() : null;
  481. final CRC32 crc2 = validate ? new CRC32() : null;
  482. final byte[] buf = out.getCopyBuffer();
  483. // Rip apart the header so we can discover the size.
  484. //
  485. try {
  486. readFully(src.offset, buf, 0, 20, ctx);
  487. } catch (IOException ioError) {
  488. StoredObjectRepresentationNotAvailableException gone;
  489. gone = new StoredObjectRepresentationNotAvailableException(src);
  490. gone.initCause(ioError);
  491. throw gone;
  492. }
  493. int c = buf[0] & 0xff;
  494. final int typeCode = (c >> 4) & 7;
  495. long inflatedLength = c & 15;
  496. int shift = 4;
  497. int headerCnt = 1;
  498. while ((c & 0x80) != 0) {
  499. c = buf[headerCnt++] & 0xff;
  500. inflatedLength += ((long) (c & 0x7f)) << shift;
  501. shift += 7;
  502. }
  503. if (typeCode == Constants.OBJ_OFS_DELTA) {
  504. do {
  505. c = buf[headerCnt++] & 0xff;
  506. } while ((c & 128) != 0);
  507. if (validate) {
  508. assert(crc1 != null && crc2 != null);
  509. crc1.update(buf, 0, headerCnt);
  510. crc2.update(buf, 0, headerCnt);
  511. }
  512. } else if (typeCode == Constants.OBJ_REF_DELTA) {
  513. if (validate) {
  514. assert(crc1 != null && crc2 != null);
  515. crc1.update(buf, 0, headerCnt);
  516. crc2.update(buf, 0, headerCnt);
  517. }
  518. readFully(src.offset + headerCnt, buf, 0, 20, ctx);
  519. if (validate) {
  520. assert(crc1 != null && crc2 != null);
  521. crc1.update(buf, 0, 20);
  522. crc2.update(buf, 0, 20);
  523. }
  524. headerCnt += 20;
  525. } else if (validate) {
  526. assert(crc1 != null && crc2 != null);
  527. crc1.update(buf, 0, headerCnt);
  528. crc2.update(buf, 0, headerCnt);
  529. }
  530. final long dataOffset = src.offset + headerCnt;
  531. final long dataLength = src.length;
  532. final long expectedCRC;
  533. final DfsBlock quickCopy;
  534. // Verify the object isn't corrupt before sending. If it is,
  535. // we report it missing instead.
  536. //
  537. try {
  538. quickCopy = ctx.quickCopy(this, dataOffset, dataLength);
  539. if (validate && idx(ctx).hasCRC32Support()) {
  540. assert(crc1 != null);
  541. // Index has the CRC32 code cached, validate the object.
  542. //
  543. expectedCRC = idx(ctx).findCRC32(src);
  544. if (quickCopy != null) {
  545. quickCopy.crc32(crc1, dataOffset, (int) dataLength);
  546. } else {
  547. long pos = dataOffset;
  548. long cnt = dataLength;
  549. while (cnt > 0) {
  550. final int n = (int) Math.min(cnt, buf.length);
  551. readFully(pos, buf, 0, n, ctx);
  552. crc1.update(buf, 0, n);
  553. pos += n;
  554. cnt -= n;
  555. }
  556. }
  557. if (crc1.getValue() != expectedCRC) {
  558. setCorrupt(src.offset);
  559. throw new CorruptObjectException(MessageFormat.format(
  560. JGitText.get().objectAtHasBadZlibStream,
  561. Long.valueOf(src.offset), getFileName()));
  562. }
  563. } else if (validate) {
  564. assert(crc1 != null);
  565. // We don't have a CRC32 code in the index, so compute it
  566. // now while inflating the raw data to get zlib to tell us
  567. // whether or not the data is safe.
  568. //
  569. Inflater inf = ctx.inflater();
  570. byte[] tmp = new byte[1024];
  571. if (quickCopy != null) {
  572. quickCopy.check(inf, tmp, dataOffset, (int) dataLength);
  573. } else {
  574. long pos = dataOffset;
  575. long cnt = dataLength;
  576. while (cnt > 0) {
  577. final int n = (int) Math.min(cnt, buf.length);
  578. readFully(pos, buf, 0, n, ctx);
  579. crc1.update(buf, 0, n);
  580. inf.setInput(buf, 0, n);
  581. while (inf.inflate(tmp, 0, tmp.length) > 0)
  582. continue;
  583. pos += n;
  584. cnt -= n;
  585. }
  586. }
  587. if (!inf.finished() || inf.getBytesRead() != dataLength) {
  588. setCorrupt(src.offset);
  589. throw new EOFException(MessageFormat.format(
  590. JGitText.get().shortCompressedStreamAt,
  591. Long.valueOf(src.offset)));
  592. }
  593. expectedCRC = crc1.getValue();
  594. } else {
  595. expectedCRC = -1;
  596. }
  597. } catch (DataFormatException dataFormat) {
  598. setCorrupt(src.offset);
  599. CorruptObjectException corruptObject = new CorruptObjectException(
  600. MessageFormat.format(
  601. JGitText.get().objectAtHasBadZlibStream,
  602. Long.valueOf(src.offset), getFileName()));
  603. corruptObject.initCause(dataFormat);
  604. StoredObjectRepresentationNotAvailableException gone;
  605. gone = new StoredObjectRepresentationNotAvailableException(src);
  606. gone.initCause(corruptObject);
  607. throw gone;
  608. } catch (IOException ioError) {
  609. StoredObjectRepresentationNotAvailableException gone;
  610. gone = new StoredObjectRepresentationNotAvailableException(src);
  611. gone.initCause(ioError);
  612. throw gone;
  613. }
  614. if (quickCopy != null) {
  615. // The entire object fits into a single byte array window slice,
  616. // and we have it pinned. Write this out without copying.
  617. //
  618. out.writeHeader(src, inflatedLength);
  619. quickCopy.write(out, dataOffset, (int) dataLength);
  620. } else if (dataLength <= buf.length) {
  621. // Tiny optimization: Lots of objects are very small deltas or
  622. // deflated commits that are likely to fit in the copy buffer.
  623. //
  624. if (!validate) {
  625. long pos = dataOffset;
  626. long cnt = dataLength;
  627. while (cnt > 0) {
  628. final int n = (int) Math.min(cnt, buf.length);
  629. readFully(pos, buf, 0, n, ctx);
  630. pos += n;
  631. cnt -= n;
  632. }
  633. }
  634. out.writeHeader(src, inflatedLength);
  635. out.write(buf, 0, (int) dataLength);
  636. } else {
  637. // Now we are committed to sending the object. As we spool it out,
  638. // check its CRC32 code to make sure there wasn't corruption between
  639. // the verification we did above, and us actually outputting it.
  640. //
  641. out.writeHeader(src, inflatedLength);
  642. long pos = dataOffset;
  643. long cnt = dataLength;
  644. while (cnt > 0) {
  645. final int n = (int) Math.min(cnt, buf.length);
  646. readFully(pos, buf, 0, n, ctx);
  647. if (validate) {
  648. assert(crc2 != null);
  649. crc2.update(buf, 0, n);
  650. }
  651. out.write(buf, 0, n);
  652. pos += n;
  653. cnt -= n;
  654. }
  655. if (validate) {
  656. assert(crc2 != null);
  657. if (crc2.getValue() != expectedCRC) {
  658. throw new CorruptObjectException(MessageFormat.format(
  659. JGitText.get().objectAtHasBadZlibStream,
  660. Long.valueOf(src.offset), getFileName()));
  661. }
  662. }
  663. }
  664. }
  665. private IOException packfileIsTruncated() {
  666. invalid = true;
  667. return new IOException(MessageFormat.format(
  668. JGitText.get().packfileIsTruncated, getFileName()));
  669. }
  670. private void readFully(long position, byte[] dstbuf, int dstoff, int cnt,
  671. DfsReader ctx) throws IOException {
  672. if (ctx.copy(this, position, dstbuf, dstoff, cnt) != cnt)
  673. throw new EOFException();
  674. }
  675. DfsBlock getOrLoadBlock(long pos, DfsReader ctx) throws IOException {
  676. return cache.getOrLoad(this, pos, ctx, null);
  677. }
  678. ObjectLoader load(DfsReader ctx, long pos)
  679. throws IOException {
  680. try {
  681. final byte[] ib = ctx.tempId;
  682. Delta delta = null;
  683. byte[] data = null;
  684. int type = Constants.OBJ_BAD;
  685. boolean cached = false;
  686. SEARCH: for (;;) {
  687. readFully(pos, ib, 0, 20, ctx);
  688. int c = ib[0] & 0xff;
  689. final int typeCode = (c >> 4) & 7;
  690. long sz = c & 15;
  691. int shift = 4;
  692. int p = 1;
  693. while ((c & 0x80) != 0) {
  694. c = ib[p++] & 0xff;
  695. sz += ((long) (c & 0x7f)) << shift;
  696. shift += 7;
  697. }
  698. switch (typeCode) {
  699. case Constants.OBJ_COMMIT:
  700. case Constants.OBJ_TREE:
  701. case Constants.OBJ_BLOB:
  702. case Constants.OBJ_TAG: {
  703. if (delta != null) {
  704. data = decompress(pos + p, (int) sz, ctx);
  705. type = typeCode;
  706. break SEARCH;
  707. }
  708. if (sz < ctx.getStreamFileThreshold()) {
  709. data = decompress(pos + p, (int) sz, ctx);
  710. if (data != null)
  711. return new ObjectLoader.SmallObject(typeCode, data);
  712. }
  713. return new LargePackedWholeObject(typeCode, sz, pos, p, this, ctx.db);
  714. }
  715. case Constants.OBJ_OFS_DELTA: {
  716. c = ib[p++] & 0xff;
  717. long base = c & 127;
  718. while ((c & 128) != 0) {
  719. base += 1;
  720. c = ib[p++] & 0xff;
  721. base <<= 7;
  722. base += (c & 127);
  723. }
  724. base = pos - base;
  725. delta = new Delta(delta, pos, (int) sz, p, base);
  726. if (sz != delta.deltaSize)
  727. break SEARCH;
  728. DeltaBaseCache.Entry e = ctx.getDeltaBaseCache().get(key, base);
  729. if (e != null) {
  730. type = e.type;
  731. data = e.data;
  732. cached = true;
  733. break SEARCH;
  734. }
  735. pos = base;
  736. continue SEARCH;
  737. }
  738. case Constants.OBJ_REF_DELTA: {
  739. readFully(pos + p, ib, 0, 20, ctx);
  740. long base = findDeltaBase(ctx, ObjectId.fromRaw(ib));
  741. delta = new Delta(delta, pos, (int) sz, p + 20, base);
  742. if (sz != delta.deltaSize)
  743. break SEARCH;
  744. DeltaBaseCache.Entry e = ctx.getDeltaBaseCache().get(key, base);
  745. if (e != null) {
  746. type = e.type;
  747. data = e.data;
  748. cached = true;
  749. break SEARCH;
  750. }
  751. pos = base;
  752. continue SEARCH;
  753. }
  754. default:
  755. throw new IOException(MessageFormat.format(
  756. JGitText.get().unknownObjectType, Integer.valueOf(typeCode)));
  757. }
  758. }
  759. // At this point there is at least one delta to apply to data.
  760. // (Whole objects with no deltas to apply return early above.)
  761. if (data == null)
  762. throw new LargeObjectException();
  763. assert(delta != null);
  764. do {
  765. // Cache only the base immediately before desired object.
  766. if (cached)
  767. cached = false;
  768. else if (delta.next == null)
  769. ctx.getDeltaBaseCache().put(key, delta.basePos, type, data);
  770. pos = delta.deltaPos;
  771. byte[] cmds = decompress(pos + delta.hdrLen, delta.deltaSize, ctx);
  772. if (cmds == null) {
  773. data = null; // Discard base in case of OutOfMemoryError
  774. throw new LargeObjectException();
  775. }
  776. final long sz = BinaryDelta.getResultSize(cmds);
  777. if (Integer.MAX_VALUE <= sz)
  778. throw new LargeObjectException.ExceedsByteArrayLimit();
  779. final byte[] result;
  780. try {
  781. result = new byte[(int) sz];
  782. } catch (OutOfMemoryError tooBig) {
  783. data = null; // Discard base in case of OutOfMemoryError
  784. cmds = null;
  785. throw new LargeObjectException.OutOfMemory(tooBig);
  786. }
  787. BinaryDelta.apply(data, cmds, result);
  788. data = result;
  789. delta = delta.next;
  790. } while (delta != null);
  791. return new ObjectLoader.SmallObject(type, data);
  792. } catch (DataFormatException dfe) {
  793. CorruptObjectException coe = new CorruptObjectException(
  794. MessageFormat.format(
  795. JGitText.get().objectAtHasBadZlibStream, Long.valueOf(pos),
  796. getFileName()));
  797. coe.initCause(dfe);
  798. throw coe;
  799. }
  800. }
  801. private long findDeltaBase(DfsReader ctx, ObjectId baseId)
  802. throws IOException, MissingObjectException {
  803. long ofs = idx(ctx).findOffset(baseId);
  804. if (ofs < 0)
  805. throw new MissingObjectException(baseId,
  806. JGitText.get().missingDeltaBase);
  807. return ofs;
  808. }
  809. private static class Delta {
  810. /** Child that applies onto this object. */
  811. final Delta next;
  812. /** Offset of the delta object. */
  813. final long deltaPos;
  814. /** Size of the inflated delta stream. */
  815. final int deltaSize;
  816. /** Total size of the delta's pack entry header (including base). */
  817. final int hdrLen;
  818. /** Offset of the base object this delta applies onto. */
  819. final long basePos;
  820. Delta(Delta next, long ofs, int sz, int hdrLen, long baseOffset) {
  821. this.next = next;
  822. this.deltaPos = ofs;
  823. this.deltaSize = sz;
  824. this.hdrLen = hdrLen;
  825. this.basePos = baseOffset;
  826. }
  827. }
  828. byte[] getDeltaHeader(DfsReader wc, long pos)
  829. throws IOException, DataFormatException {
  830. // The delta stream starts as two variable length integers. If we
  831. // assume they are 64 bits each, we need 16 bytes to encode them,
  832. // plus 2 extra bytes for the variable length overhead. So 18 is
  833. // the longest delta instruction header.
  834. //
  835. final byte[] hdr = new byte[32];
  836. wc.inflate(this, pos, hdr, true /* header only */);
  837. return hdr;
  838. }
  839. int getObjectType(DfsReader ctx, long pos) throws IOException {
  840. final byte[] ib = ctx.tempId;
  841. for (;;) {
  842. readFully(pos, ib, 0, 20, ctx);
  843. int c = ib[0] & 0xff;
  844. final int type = (c >> 4) & 7;
  845. switch (type) {
  846. case Constants.OBJ_COMMIT:
  847. case Constants.OBJ_TREE:
  848. case Constants.OBJ_BLOB:
  849. case Constants.OBJ_TAG:
  850. return type;
  851. case Constants.OBJ_OFS_DELTA: {
  852. int p = 1;
  853. while ((c & 0x80) != 0)
  854. c = ib[p++] & 0xff;
  855. c = ib[p++] & 0xff;
  856. long ofs = c & 127;
  857. while ((c & 128) != 0) {
  858. ofs += 1;
  859. c = ib[p++] & 0xff;
  860. ofs <<= 7;
  861. ofs += (c & 127);
  862. }
  863. pos = pos - ofs;
  864. continue;
  865. }
  866. case Constants.OBJ_REF_DELTA: {
  867. int p = 1;
  868. while ((c & 0x80) != 0)
  869. c = ib[p++] & 0xff;
  870. readFully(pos + p, ib, 0, 20, ctx);
  871. pos = findDeltaBase(ctx, ObjectId.fromRaw(ib));
  872. continue;
  873. }
  874. default:
  875. throw new IOException(MessageFormat.format(
  876. JGitText.get().unknownObjectType, Integer.valueOf(type)));
  877. }
  878. }
  879. }
  880. long getObjectSize(DfsReader ctx, AnyObjectId id) throws IOException {
  881. final long offset = idx(ctx).findOffset(id);
  882. return 0 < offset ? getObjectSize(ctx, offset) : -1;
  883. }
  884. long getObjectSize(DfsReader ctx, long pos)
  885. throws IOException {
  886. final byte[] ib = ctx.tempId;
  887. readFully(pos, ib, 0, 20, ctx);
  888. int c = ib[0] & 0xff;
  889. final int type = (c >> 4) & 7;
  890. long sz = c & 15;
  891. int shift = 4;
  892. int p = 1;
  893. while ((c & 0x80) != 0) {
  894. c = ib[p++] & 0xff;
  895. sz += ((long) (c & 0x7f)) << shift;
  896. shift += 7;
  897. }
  898. long deltaAt;
  899. switch (type) {
  900. case Constants.OBJ_COMMIT:
  901. case Constants.OBJ_TREE:
  902. case Constants.OBJ_BLOB:
  903. case Constants.OBJ_TAG:
  904. return sz;
  905. case Constants.OBJ_OFS_DELTA:
  906. c = ib[p++] & 0xff;
  907. while ((c & 128) != 0)
  908. c = ib[p++] & 0xff;
  909. deltaAt = pos + p;
  910. break;
  911. case Constants.OBJ_REF_DELTA:
  912. deltaAt = pos + p + 20;
  913. break;
  914. default:
  915. throw new IOException(MessageFormat.format(
  916. JGitText.get().unknownObjectType, Integer.valueOf(type)));
  917. }
  918. try {
  919. return BinaryDelta.getResultSize(getDeltaHeader(ctx, deltaAt));
  920. } catch (DataFormatException dfe) {
  921. CorruptObjectException coe = new CorruptObjectException(
  922. MessageFormat.format(
  923. JGitText.get().objectAtHasBadZlibStream, Long.valueOf(pos),
  924. getFileName()));
  925. coe.initCause(dfe);
  926. throw coe;
  927. }
  928. }
  929. void representation(DfsObjectRepresentation r, final long pos,
  930. DfsReader ctx, PackReverseIndex rev)
  931. throws IOException {
  932. r.offset = pos;
  933. final byte[] ib = ctx.tempId;
  934. readFully(pos, ib, 0, 20, ctx);
  935. int c = ib[0] & 0xff;
  936. int p = 1;
  937. final int typeCode = (c >> 4) & 7;
  938. while ((c & 0x80) != 0)
  939. c = ib[p++] & 0xff;
  940. long len = rev.findNextOffset(pos, length - 20) - pos;
  941. switch (typeCode) {
  942. case Constants.OBJ_COMMIT:
  943. case Constants.OBJ_TREE:
  944. case Constants.OBJ_BLOB:
  945. case Constants.OBJ_TAG:
  946. r.format = StoredObjectRepresentation.PACK_WHOLE;
  947. r.baseId = null;
  948. r.length = len - p;
  949. return;
  950. case Constants.OBJ_OFS_DELTA: {
  951. c = ib[p++] & 0xff;
  952. long ofs = c & 127;
  953. while ((c & 128) != 0) {
  954. ofs += 1;
  955. c = ib[p++] & 0xff;
  956. ofs <<= 7;
  957. ofs += (c & 127);
  958. }
  959. r.format = StoredObjectRepresentation.PACK_DELTA;
  960. r.baseId = rev.findObject(pos - ofs);
  961. r.length = len - p;
  962. return;
  963. }
  964. case Constants.OBJ_REF_DELTA: {
  965. readFully(pos + p, ib, 0, 20, ctx);
  966. r.format = StoredObjectRepresentation.PACK_DELTA;
  967. r.baseId = ObjectId.fromRaw(ib);
  968. r.length = len - p - 20;
  969. return;
  970. }
  971. default:
  972. throw new IOException(MessageFormat.format(
  973. JGitText.get().unknownObjectType, Integer.valueOf(typeCode)));
  974. }
  975. }
  976. boolean isCorrupt(long offset) {
  977. LongList list = corruptObjects;
  978. if (list == null)
  979. return false;
  980. synchronized (list) {
  981. return list.contains(offset);
  982. }
  983. }
  984. private void setCorrupt(long offset) {
  985. LongList list = corruptObjects;
  986. if (list == null) {
  987. synchronized (initLock) {
  988. list = corruptObjects;
  989. if (list == null) {
  990. list = new LongList();
  991. corruptObjects = list;
  992. }
  993. }
  994. }
  995. synchronized (list) {
  996. list.add(offset);
  997. }
  998. }
  999. }