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

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