1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
15 * The Original Code is Mozilla FastLoad code.
17 * The Initial Developer of the Original Code is
18 * Netscape Communications Corporation.
19 * Portions created by the Initial Developer are Copyright (C) 2001
20 * the Initial Developer. All Rights Reserved.
23 * Brendan Eich <brendan@mozilla.org> (original author)
25 * Alternatively, the contents of this file may be used under the terms of
26 * either of the GNU General Public License Version 2 or later (the "GPL"),
27 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28 * in which case the provisions of the GPL or the LGPL are applicable instead
29 * of those above. If you wish to allow use of your version of this file only
30 * under the terms of either the GPL or the LGPL, and not to allow others to
31 * use your version of this file under the terms of the MPL, indicate your
32 * decision by deleting the provisions above and replace them with the notice
33 * and other provisions required by the GPL or the LGPL. If you do not delete
34 * the provisions above, a recipient may use your version of this file under
35 * the terms of any one of the MPL, the GPL or the LGPL.
37 * ***** END LICENSE BLOCK ***** */
39 #ifndef nsFastLoadFile_h___
40 #define nsFastLoadFile_h___
43 * Mozilla FastLoad file format and helper types.
49 #include "nsBinaryStream.h"
54 #include "nsVoidArray.h"
56 #include "nsIFastLoadFileControl.h"
57 #include "nsIFastLoadService.h"
58 #include "nsISeekableStream.h"
59 #include "nsISupportsArray.h"
62 * FastLoad file Object ID (OID) is an identifier for multiply and cyclicly
63 * connected objects in the serialized graph of all reachable objects.
65 * Holy Mixed Metaphors: JS, after Common Lisp, uses #n= to define a "sharp
66 * variable" naming an object that's multiply or cyclicly connected, and #n#
67 * to stand for a connection to an already-defined object. We too call any
68 * object with multiple references "sharp", and (here it comes) any object
69 * with only one reference "dull".
71 * Note that only sharp objects require a mapping from OID to FastLoad file
72 * offset and other information. Dull objects can be serialized _in situ_
73 * (where they are referenced) and deserialized when their (singular, shared)
76 * We also compress 16-byte XPCOM IDs into 32-bit dense identifiers to save
77 * space. See nsFastLoadFooter, below, for the mapping data structure used to
78 * compute an nsID given an NSFastLoadID.
80 typedef PRUint32 NSFastLoadID
; // nsFastLoadFooter::mIDMap index
81 typedef PRUint32 NSFastLoadOID
; // nsFastLoadFooter::mObjectMap index
84 * A Mozilla FastLoad file is an untagged (in general) stream of objects and
85 * primitive-type data. Small integers are fairly common, and could easily be
86 * confused for NSFastLoadIDs and NSFastLoadOIDs. To help catch bugs where
87 * reader and writer code fail to match, we XOR unlikely 32-bit numbers with
88 * NSFastLoad*IDs when storing and fetching. The following unlikely values are
89 * irrational numbers ((sqrt(5)-1)/2, sqrt(2)-1) represented in fixed point.
91 * The reader XORs, converts the ID to an index, and bounds-checks all array
92 * accesses that use the index. Array access code asserts that the index is in
93 * bounds, and returns a dummy array element if it isn't.
95 #define MFL_ID_XOR_KEY 0x9E3779B9 // key XOR'd with ID when serialized
96 #define MFL_OID_XOR_KEY 0x6A09E667 // key XOR'd with OID when serialized
99 * An OID can be tagged to introduce the serialized definition of the object,
100 * or to stand for a strong or weak reference to that object. Thus the high
101 * 29 bits actually identify the object, and the low three bits tell whether
102 * the object is being defined or just referenced -- and via what inheritance
103 * chain or inner object, if necessary.
105 * The MFL_QUERY_INTERFACE_TAG bit helps us cope with aggregation and multiple
106 * inheritance: object identity follows the XPCOM rule, but a deserializer may
107 * need to query for an interface not on the primary inheritance chain ending
108 * in the nsISupports whose address uniquely identifies the XPCOM object being
109 * referenced or defined.
111 #define MFL_OBJECT_TAG_BITS 3
112 #define MFL_OBJECT_TAG_MASK PR_BITMASK(MFL_OBJECT_TAG_BITS)
114 #define MFL_OBJECT_DEF_TAG 1U // object definition follows this OID
115 #define MFL_WEAK_REF_TAG 2U // OID weakly refers to a prior object
116 // NB: do not confuse with nsWeakPtr!
117 #define MFL_QUERY_INTERFACE_TAG 4U // QI object to the ID follows this OID
118 // NB: an NSFastLoadID, not an nsIID!
121 * The dull object identifier introduces the definition of all objects that
122 * have only one (necessarily strong) ref in the serialization. The definition
123 * appears at the point of reference.
125 #define MFL_DULL_OBJECT_OID MFL_OBJECT_DEF_TAG
128 * Convert an OID to an index into nsFastLoadFooter::mObjectMap.
130 #define MFL_OID_TO_SHARP_INDEX(oid) (((oid) >> MFL_OBJECT_TAG_BITS) - 1)
131 #define MFL_SHARP_INDEX_TO_OID(index) (((index) + 1) << MFL_OBJECT_TAG_BITS)
134 * Magic "number" at start of a FastLoad file. Inspired by the PNG "magic"
135 * string, which inspired XPCOM's typelib (.xpt) file magic. Guaranteed to be
136 * corrupted by FTP-as-ASCII and other likely errors, meaningful to clued-in
137 * humans, and ending in ^Z to terminate erroneous text input on Windows.
139 #define MFL_FILE_MAGIC "XPCOM\nMozFASL\r\n\032"
140 #define MFL_FILE_MAGIC_SIZE 16
142 #define MFL_FILE_VERSION_0 0
143 #define MFL_FILE_VERSION_1 1000
144 #define MFL_FILE_VERSION 5 // rev'ed to defend against unversioned
145 // XPCOM JS component fastload files
148 * Compute Fletcher's 16-bit checksum over aLength bytes starting at aBuffer,
149 * with the initial accumulators seeded from *aChecksum, and final checksum
150 * returned in *aChecksum. The return value is the number of unchecked bytes,
151 * which may be non-zero if aBuffer is misaligned or aLength is odd. Callers
152 * should copy any remaining bytes to the front of the next buffer.
154 * If aLastBuffer is false, do not check any bytes remaining due to misaligned
155 * aBuffer or odd aLength, instead returning the remaining byte count. But if
156 * aLastBuffer is true, treat aBuffer as the last buffer in the file and check
157 * every byte, returning 0. Here's a read-loop checksumming sketch:
160 * PRUint32 len, rem = 0;
161 * PRUint32 checksum = 0;
163 * while (NS_SUCCEEDED(rv = Read(buf + rem, sizeof buf - rem, &len)) && len) {
165 * rem = NS_AccumulateFastLoadChecksum(&checksum,
166 * reinterpret_cast<PRUint8*>(buf),
170 * memcpy(buf, buf + len - rem, rem);
174 * NS_AccumulateFastLoadChecksum(&checksum,
175 * reinterpret_cast<PRUint8*>(buf),
180 * After this, if NS_SUCCEEDED(rv), checksum contains a valid FastLoad sum.
183 NS_AccumulateFastLoadChecksum(PRUint32
*aChecksum
,
184 const PRUint8
* aBuffer
,
189 NS_AddFastLoadChecksums(PRUint32 sum1
, PRUint32 sum2
, PRUint32 sum2ByteCount
);
192 * Header at the start of a FastLoad file.
194 struct nsFastLoadHeader
{
195 char mMagic
[MFL_FILE_MAGIC_SIZE
];
198 PRUint32 mFooterOffset
;
203 * Footer prefix structure (footer header, ugh), after which come arrays of
204 * structures or strings counted by these members.
206 struct nsFastLoadFooterPrefix
{
208 PRUint32 mNumSharpObjects
;
209 PRUint32 mNumMuxedDocuments
;
210 PRUint32 mNumDependencies
;
213 struct nsFastLoadSharpObjectInfo
{
214 PRUint32 mCIDOffset
; // offset of object's NSFastLoadID and data
215 PRUint16 mStrongRefCnt
;
216 PRUint16 mWeakRefCnt
; // high bit is singleton flag, see below
219 #define MFL_SINGLETON_FLAG 0x8000
220 #define MFL_WEAK_REFCNT_MASK 0x7fff
222 #define MFL_GET_SINGLETON_FLAG(ip) ((ip)->mWeakRefCnt & MFL_SINGLETON_FLAG)
223 #define MFL_GET_WEAK_REFCNT(ip) ((ip)->mWeakRefCnt & MFL_WEAK_REFCNT_MASK)
225 #define MFL_SET_SINGLETON_FLAG(ip) \
226 ((ip)->mWeakRefCnt |= MFL_SINGLETON_FLAG)
227 #define MFL_SET_WEAK_REFCNT(ip,rc) \
228 ((ip)->mWeakRefCnt = (((ip)->mWeakRefCnt & MFL_SINGLETON_FLAG) | (rc)))
230 #define MFL_BUMP_WEAK_REFCNT(ip) (++(ip)->mWeakRefCnt)
231 #define MFL_DROP_WEAK_REFCNT(ip) (--(ip)->mWeakRefCnt)
233 struct nsFastLoadMuxedDocumentInfo
{
234 const char* mURISpec
;
235 PRUint32 mInitialSegmentOffset
;
238 // forward declarations of opaque types defined in nsFastLoadFile.cpp
239 struct nsDocumentMapReadEntry
;
240 struct nsDocumentMapWriteEntry
;
242 // So nsFastLoadFileUpdater can verify that its nsIObjectInputStream parameter
243 // is an nsFastLoadFileReader.
244 #define NS_FASTLOADFILEREADER_IID \
245 {0x7d37d1bb,0xcef3,0x4c5f,{0x97,0x68,0x0f,0x89,0x7f,0x1a,0xe1,0x40}}
247 struct nsIFastLoadFileReader
: public nsISupports
{
248 NS_DECLARE_STATIC_IID_ACCESSOR(NS_FASTLOADFILEREADER_IID
)
251 NS_DEFINE_STATIC_IID_ACCESSOR(nsIFastLoadFileReader
, NS_FASTLOADFILEREADER_IID
)
254 * Inherit from the concrete class nsBinaryInputStream, which inherits from
255 * abstract nsIObjectInputStream but does not implement its direct methods.
256 * Though the names are not as clear as I'd like, this seems to be the best
257 * way to share nsBinaryStream.cpp code.
259 class nsFastLoadFileReader
260 : public nsBinaryInputStream
,
261 public nsIFastLoadReadControl
,
262 public nsISeekableStream
,
263 public nsIFastLoadFileReader
266 nsFastLoadFileReader(nsIInputStream
*aStream
)
267 : mCurrentDocumentMapEntry(nsnull
) {
268 SetInputStream(aStream
);
269 MOZ_COUNT_CTOR(nsFastLoadFileReader
);
272 virtual ~nsFastLoadFileReader() {
273 MOZ_COUNT_DTOR(nsFastLoadFileReader
);
277 // nsISupports methods
278 NS_DECL_ISUPPORTS_INHERITED
280 // overridden nsIObjectInputStream methods
281 NS_IMETHOD
ReadObject(PRBool aIsStrongRef
, nsISupports
* *_retval
);
282 NS_IMETHOD
ReadID(nsID
*aResult
);
284 // nsIFastLoadFileControl methods
285 NS_DECL_NSIFASTLOADFILECONTROL
287 // nsIFastLoadReadControl methods
288 NS_DECL_NSIFASTLOADREADCONTROL
290 // nsISeekableStream methods
291 NS_DECL_NSISEEKABLESTREAM
293 // Override Read so we can demultiplex a document interleaved with others.
294 NS_IMETHOD
Read(char* aBuffer
, PRUint32 aCount
, PRUint32
*aBytesRead
);
296 // Override ReadSegments too, as nsBinaryInputStream::ReadSegments does
297 // not call through our overridden Read method -- it calls directly into
298 // the underlying input stream.
299 NS_IMETHODIMP
ReadSegments(nsWriteSegmentFun aWriter
, void* aClosure
,
300 PRUint32 aCount
, PRUint32
*aResult
);
302 // Override SetInputStream so we can update mSeekableInput
303 NS_IMETHOD
SetInputStream(nsIInputStream
* aInputStream
);
305 nsresult
ReadHeader(nsFastLoadHeader
*aHeader
);
308 * In-memory representation of an indexed nsFastLoadSharpObjectInfo record.
310 struct nsObjectMapEntry
: public nsFastLoadSharpObjectInfo
{
311 nsCOMPtr
<nsISupports
> mReadObject
;
313 PRUint16 mSaveStrongRefCnt
; // saved for an Update
314 PRUint16 mSaveWeakRefCnt
; // after a Read
318 * In-memory representation of the FastLoad file footer.
320 struct nsFastLoadFooter
: public nsFastLoadFooterPrefix
{
324 mDocumentMap
.ops
= mURIMap
.ops
= nsnull
;
327 ~nsFastLoadFooter() {
330 if (mDocumentMap
.ops
)
331 PL_DHashTableFinish(&mDocumentMap
);
333 PL_DHashTableFinish(&mURIMap
);
336 // These can't be static within GetID and GetSharpObjectEntry or the
337 // toolchains on HP-UX 10.20's, RH 7.0, and Mac OS X all barf at link
338 // time ("common symbols not allowed with MY_DHLIB output format", to
339 // quote the OS X rev of gcc).
340 static nsID gDummyID
;
341 static nsObjectMapEntry gDummySharpObjectEntry
;
343 const nsID
& GetID(NSFastLoadID aFastId
) const {
344 PRUint32 index
= aFastId
- 1;
345 NS_ASSERTION(index
< mNumIDs
, "aFastId out of range");
346 if (index
>= mNumIDs
)
348 return mIDMap
[index
];
352 GetSharpObjectEntry(NSFastLoadOID aOID
) const {
353 PRUint32 index
= MFL_OID_TO_SHARP_INDEX(aOID
);
354 NS_ASSERTION(index
< mNumSharpObjects
, "aOID out of range");
355 if (index
>= mNumSharpObjects
)
356 return gDummySharpObjectEntry
;
357 return mObjectMap
[index
];
360 // Map from dense, zero-based, uint32 NSFastLoadID to 16-byte nsID.
363 // Map from dense, zero-based MFL_OID_TO_SHARP_INDEX(oid) to sharp
364 // object offset and refcnt information.
365 nsObjectMapEntry
* mObjectMap
;
367 // Map from URI spec string to nsDocumentMapReadEntry, which helps us
368 // demultiplex a document's objects from among the interleaved object
369 // stream segments in the FastLoad file.
370 PLDHashTable mDocumentMap
;
372 // Fast mapping from URI object pointer to mDocumentMap entry, valid
373 // only while the muxed document is loading.
374 PLDHashTable mURIMap
;
376 // List of source filename dependencies that should trigger regeneration
377 // of the FastLoad file.
378 nsCOMPtr
<nsISupportsArray
> mDependencies
;
381 nsresult
ReadFooter(nsFastLoadFooter
*aFooter
);
382 nsresult
ReadFooterPrefix(nsFastLoadFooterPrefix
*aFooterPrefix
);
383 nsresult
ReadSlowID(nsID
*aID
);
384 nsresult
ReadFastID(NSFastLoadID
*aID
);
385 nsresult
ReadSharpObjectInfo(nsFastLoadSharpObjectInfo
*aInfo
);
386 nsresult
ReadMuxedDocumentInfo(nsFastLoadMuxedDocumentInfo
*aInfo
);
387 nsresult
DeserializeObject(nsISupports
* *aObject
);
393 // Kept in sync with mInputStream to avoid repeated QI
394 nsCOMPtr
<nsISeekableStream
> mSeekableInput
;
396 nsFastLoadHeader mHeader
;
397 nsFastLoadFooter mFooter
;
399 nsDocumentMapReadEntry
* mCurrentDocumentMapEntry
;
401 friend class nsFastLoadFileUpdater
;
405 NS_NewFastLoadFileReader(nsIObjectInputStream
* *aResult
,
406 nsIInputStream
* aSrcStream
);
409 * Inherit from the concrete class nsBinaryInputStream, which inherits from
410 * abstract nsIObjectInputStream but does not implement its direct methods.
411 * Though the names are not as clear as I'd like, this seems to be the best
412 * way to share nsBinaryStream.cpp code.
414 class nsFastLoadFileWriter
415 : public nsBinaryOutputStream
,
416 public nsIFastLoadWriteControl
,
417 public nsISeekableStream
420 nsFastLoadFileWriter(nsIOutputStream
*aStream
, nsIFastLoadFileIO
* aFileIO
)
421 : mCurrentDocumentMapEntry(nsnull
),
424 SetOutputStream(aStream
);
425 mHeader
.mChecksum
= 0;
426 mIDMap
.ops
= mObjectMap
.ops
= mDocumentMap
.ops
= mURIMap
.ops
= nsnull
;
427 mDependencyMap
.ops
= nsnull
;
428 MOZ_COUNT_CTOR(nsFastLoadFileWriter
);
431 virtual ~nsFastLoadFileWriter()
434 PL_DHashTableFinish(&mIDMap
);
436 PL_DHashTableFinish(&mObjectMap
);
437 if (mDocumentMap
.ops
)
438 PL_DHashTableFinish(&mDocumentMap
);
440 PL_DHashTableFinish(&mURIMap
);
441 if (mDependencyMap
.ops
)
442 PL_DHashTableFinish(&mDependencyMap
);
443 MOZ_COUNT_DTOR(nsFastLoadFileWriter
);
447 // nsISupports methods
448 NS_DECL_ISUPPORTS_INHERITED
450 // overridden nsIObjectOutputStream methods
451 NS_IMETHOD
WriteObject(nsISupports
* aObject
, PRBool aIsStrongRef
);
452 NS_IMETHOD
WriteSingleRefObject(nsISupports
* aObject
);
453 NS_IMETHOD
WriteCompoundObject(nsISupports
* aObject
,
455 PRBool aIsStrongRef
);
456 NS_IMETHOD
WriteID(const nsID
& aID
);
458 // Override SetOutputStream so we can update mSeekableOutput
459 NS_IMETHOD
SetOutputStream(nsIOutputStream
* aOutputStream
);
461 // nsIFastLoadFileControl methods
462 NS_DECL_NSIFASTLOADFILECONTROL
464 // nsIFastLoadWriteControl methods
465 NS_DECL_NSIFASTLOADWRITECONTROL
467 // nsISeekableStream methods
468 NS_DECL_NSISEEKABLESTREAM
470 nsresult
MapID(const nsID
& aSlowID
, NSFastLoadID
*aResult
);
472 nsresult
WriteHeader(nsFastLoadHeader
*aHeader
);
473 nsresult
WriteFooter();
474 nsresult
WriteFooterPrefix(const nsFastLoadFooterPrefix
& aFooterPrefix
);
475 nsresult
WriteSlowID(const nsID
& aID
);
476 nsresult
WriteFastID(NSFastLoadID aID
);
477 nsresult
WriteSharpObjectInfo(const nsFastLoadSharpObjectInfo
& aInfo
);
478 nsresult
WriteMuxedDocumentInfo(const nsFastLoadMuxedDocumentInfo
& aInfo
);
484 nsresult
WriteObjectCommon(nsISupports
* aObject
,
488 static PLDHashOperator PR_CALLBACK
489 IDMapEnumerate(PLDHashTable
*aTable
,
490 PLDHashEntryHdr
*aHdr
,
494 static PLDHashOperator PR_CALLBACK
495 ObjectMapEnumerate(PLDHashTable
*aTable
,
496 PLDHashEntryHdr
*aHdr
,
500 static PLDHashOperator PR_CALLBACK
501 DocumentMapEnumerate(PLDHashTable
*aTable
,
502 PLDHashEntryHdr
*aHdr
,
506 static PLDHashOperator PR_CALLBACK
507 DependencyMapEnumerate(PLDHashTable
*aTable
,
508 PLDHashEntryHdr
*aHdr
,
513 // Kept in sync with mOutputStream to avoid repeated QI
514 nsCOMPtr
<nsISeekableStream
> mSeekableOutput
;
516 nsFastLoadHeader mHeader
;
519 PLDHashTable mObjectMap
;
520 PLDHashTable mDocumentMap
;
521 PLDHashTable mURIMap
;
522 PLDHashTable mDependencyMap
;
524 nsDocumentMapWriteEntry
* mCurrentDocumentMapEntry
;
525 nsCOMPtr
<nsIFastLoadFileIO
> mFileIO
;
529 NS_NewFastLoadFileWriter(nsIObjectOutputStream
* *aResult
,
530 nsIOutputStream
* aDestStream
,
531 nsIFastLoadFileIO
* aFileIO
);
534 * Subclass of nsFastLoadFileWriter, friend of nsFastLoadFileReader which it
535 * wraps when a FastLoad file needs to be updated. The wrapped reader can be
536 * used to demulitplex data for documents already in the FastLoad file, while
537 * the updater writes new data over the old footer, then writes a new footer
538 * that maps all data on Close.
540 class nsFastLoadFileUpdater
541 : public nsFastLoadFileWriter
,
545 nsFastLoadFileUpdater(nsIOutputStream
* aOutputStream
)
546 : nsFastLoadFileWriter(aOutputStream
, nsnull
) {
547 MOZ_COUNT_CTOR(nsFastLoadFileUpdater
);
550 virtual ~nsFastLoadFileUpdater() {
551 MOZ_COUNT_DTOR(nsFastLoadFileUpdater
);
555 // nsISupports methods
556 NS_DECL_ISUPPORTS_INHERITED
558 // nsIFastLoadFileIO methods
559 NS_DECL_NSIFASTLOADFILEIO
561 nsresult
Open(nsFastLoadFileReader
* aReader
);
564 static PLDHashOperator PR_CALLBACK
565 CopyReadDocumentMapEntryToUpdater(PLDHashTable
*aTable
,
566 PLDHashEntryHdr
*aHdr
,
570 friend class nsFastLoadFileReader
;
573 nsCOMPtr
<nsIInputStream
> mInputStream
;
575 // Kept in sync with mInputStream to avoid repeated QI
576 nsCOMPtr
<nsISeekableStream
> mSeekableInput
;
580 NS_NewFastLoadFileUpdater(nsIObjectOutputStream
* *aResult
,
581 nsIOutputStream
* aOutputStream
,
582 nsIObjectInputStream
* aReaderAsStream
);
584 #endif // nsFastLoadFile_h___