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

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