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 30KB

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