VirtualBox

source: vbox/trunk/src/VBox/VMM/SSM.cpp@ 23779

Last change on this file since 23779 was 23779, checked in by vboxsync, 15 years ago

PATM: Converting to extended structure based deserialization.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 279.5 KB
Line 
1/* $Id: SSM.cpp 23779 2009-10-14 21:59:34Z vboxsync $ */
2/** @file
3 * SSM - Saved State Manager.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22
23/** @page pg_ssm SSM - The Saved State Manager
24 *
25 * The Saved State Manager (SSM) implements facilities for saving and loading a
26 * VM state in a structural manner using callbacks for named data units.
27 *
28 * At init time each of the VMM components, Devices, Drivers and one or two
29 * other things will register data units which they need to save and restore.
30 * Each unit have a unique name (ascii), instance number, and a set of callbacks
31 * associated with it. The name will be used to identify the unit during
32 * restore. The callbacks are for the two operations, save and restore. There
33 * are three callbacks for each of the two - a prepare, a execute and a complete
34 * - giving each component ample opportunity to perform actions both before and
35 * afterwards.
36 *
37 * The SSM provides a number of APIs for encoding and decoding the data: @see
38 * grp_ssm
39 *
40 *
41 *
42 * @section sec_ssm_live_snapshots Live Snapshots
43 *
44 * The live snapshots feature (LS) is similar to live migration (LM) and was a
45 * natural first step when implementing LM. The main differences between LS and
46 * LM are that after a live snapshot we will have a saved state file, disk image
47 * snapshots, and the VM will still be running.
48 *
49 * Compared to normal saved stated and snapshots, the difference is in that the
50 * VM is running while we do most of the saving. Prior to LS, there was only
51 * one round of callbacks during saving and the VM was paused during it. With
52 * LS there are 1 or more passes while the VM is still running and a final one
53 * after it has been paused. The runtime passes are executed on a dedicated
54 * thread running at at the same priority as the EMTs so that the saving doesn't
55 * starve or lose in scheduling questions (note: not implemented yet). The final
56 * pass is done on EMT(0).
57 *
58 * There are a couple of common reasons why LS and LM will fail:
59 * - Memory configuration changed (PCI memory mappings).
60 * - Takes too long (LM) / Too much output (LS).
61 *
62 *
63 * The live saving sequence is something like this:
64 *
65 * -# SSMR3LiveSave is called on EMT0. It returns a saved state
66 * handle.
67 * -# SSMR3LiveDoStep1 is called on a non-EMT. This will save the major
68 * parts of the state while the VM may still be running.
69 * -# The VM is suspended.
70 * -# SSMR3LiveDoStep2 is called on EMT0 to save the remainder of the state
71 * in the normal way.
72 * -# The client does any necessary reconfiguration of harddisks and
73 * similar.
74 * -# SSMR3LiveDone is called on EMT0 to close the handle.
75 * -# The VM is resumed or powered off and destroyed.
76 *
77 *
78 * @section sec_ssm_live_migration Live Migration
79 *
80 * As mentioned in the previous section, the main differences between this and
81 * live snapshots are in where the saved state is written and what state the
82 * local VM is in afterwards - at least from the VMM point of view. The
83 * necessary administrative work - establishing the connection to the remote
84 * machine, cloning the VM config on it and doing lowlevel saved state data
85 * transfer - is taken care of by layer above the VMM (i.e. Main).
86 *
87 * The SSM data format was made streamable for the purpose of live migration
88 * (v1.2 was the last non-streamable version).
89 *
90 *
91 * @section sec_ssm_format Saved State Format
92 *
93 * The stream format starts with a header (SSMFILEHDR) that indicates the
94 * version and such things, it is followed by zero or more saved state units
95 * (name + instance + pass), and the stream concludes with a footer
96 * (SSMFILEFTR) that contains unit counts and optionally a checksum for the
97 * entire file. (In version 1.2 and earlier, the checksum was in the header and
98 * there was no footer. This meant that the header was updated after the entire
99 * file was written.)
100 *
101 * The saved state units each starts with a variable sized header
102 * (SSMFILEUNITHDRV2) that contains the name, instance and pass. The data
103 * follows the header and is encoded as records with a 2-8 byte record header
104 * indicating the type, flags and size. The first byte in the record header
105 * indicates the type and flags:
106 *
107 * - bits 0..3: Record type:
108 * - type 0: Invalid.
109 * - type 1: Terminator with CRC-32 and unit size.
110 * - type 2: Raw data record.
111 * - type 3: Raw data compressed by LZF. The data is prefixed by a 8-bit
112 * field countining the length of the uncompressed data given in
113 * 1KB units.
114 * - type 4: Zero data. The record header is followed by a 8-bit field
115 * counting the length of the zero data given in 1KB units.
116 * - type 5: Named data - length prefixed name followed by the data. This
117 * type is not implemented yet as we're missing the API part, so
118 * the type assignment is tentative.
119 * - types 6 thru 15 are current undefined.
120 * - bit 4: Important (set), can be skipped (clear).
121 * - bit 5: Undefined flag, must be zero.
122 * - bit 6: Undefined flag, must be zero.
123 * - bit 7: "magic" bit, always set.
124 *
125 * Record header byte 2 (optionally thru 7) is the size of the following data
126 * encoded in UTF-8 style. To make buffering simpler and more efficient during
127 * the save operation, the strict checks enforcing optimal encoding has been
128 * relaxed for the 2 and 3 byte encodings.
129 *
130 * (In version 1.2 and earlier the unit data was compressed and not record
131 * based. The unit header contained the compressed size of the data, i.e. it
132 * needed updating after the data was written.)
133 *
134 *
135 * @section sec_ssm_future Future Changes
136 *
137 * There are plans to extend SSM to make it easier to be both backwards and
138 * (somewhat) forwards compatible. One of the new features will be being able
139 * to classify units and data items as unimportant (added to the format in
140 * v2.0). Another suggested feature is naming data items (also added to the
141 * format in v2.0), perhaps by extending the SSMR3PutStruct API. Both features
142 * will require API changes, the naming may possibly require both buffering of
143 * the stream as well as some helper managing them.
144 */
145
146
147/*******************************************************************************
148* Header Files *
149*******************************************************************************/
150#define LOG_GROUP LOG_GROUP_SSM
151#include <VBox/ssm.h>
152#include <VBox/dbgf.h>
153#include <VBox/mm.h>
154#include "SSMInternal.h"
155#include <VBox/vm.h>
156#include <VBox/err.h>
157#include <VBox/log.h>
158#include <VBox/version.h>
159
160#include <iprt/alloc.h>
161#include <iprt/assert.h>
162#include <iprt/crc32.h>
163#include <iprt/file.h>
164#include <iprt/param.h>
165#include <iprt/thread.h>
166#include <iprt/semaphore.h>
167#include <iprt/string.h>
168#include <iprt/uuid.h>
169#include <iprt/zip.h>
170
171
172/*******************************************************************************
173* Defined Constants And Macros *
174*******************************************************************************/
175/** The max length of a unit name. */
176#define SSM_MAX_NAME_SIZE 48
177
178/** Saved state file magic base string. */
179#define SSMFILEHDR_MAGIC_BASE "\177VirtualBox SavedState "
180/** Saved state file magic indicating version 1.x. */
181#define SSMFILEHDR_MAGIC_V1_X "\177VirtualBox SavedState V1."
182/** Saved state file v1.1 magic. */
183#define SSMFILEHDR_MAGIC_V1_1 "\177VirtualBox SavedState V1.1\n"
184/** Saved state file v1.2 magic. */
185#define SSMFILEHDR_MAGIC_V1_2 "\177VirtualBox SavedState V1.2\n\0\0\0"
186/** Saved state file v2.0 magic. */
187#define SSMFILEHDR_MAGIC_V2_0 "\177VirtualBox SavedState V2.0\n\0\0\0"
188
189/** @name SSMFILEHDR::fFlags
190 * @{ */
191/** The stream is checkesummed up to the footer using CRC-32. */
192#define SSMFILEHDR_FLAGS_STREAM_CRC32 RT_BIT_32(0)
193/** Indicates that the file was produced by a live save. */
194#define SSMFILEHDR_FLAGS_STREAM_LIVE_SAVE RT_BIT_32(1)
195/** @} */
196
197/** The directory magic. */
198#define SSMFILEDIR_MAGIC "\nDir\n\0\0"
199
200/** Saved state file v2.0 magic. */
201#define SSMFILEFTR_MAGIC "\nFooter"
202
203/** Data unit magic. */
204#define SSMFILEUNITHDR_MAGIC "\nUnit\n\0"
205/** Data end marker magic. */
206#define SSMFILEUNITHDR_END "\nTheEnd"
207
208
209/** @name Record Types (data unit)
210 * @{ */
211/** The record type mask. */
212#define SSM_REC_TYPE_MASK UINT8_C(0x0f)
213/** Invalid record. */
214#define SSM_REC_TYPE_INVALID 0
215/** Normal termination record, see SSMRECTERM. */
216#define SSM_REC_TYPE_TERM 1
217/** Raw data. The data follows the size field without further ado. */
218#define SSM_REC_TYPE_RAW 2
219/** Raw data compressed by LZF.
220 * The record header is followed by a 8-bit field containing the size of the
221 * uncompressed data in 1KB units. The compressed data is after it. */
222#define SSM_REC_TYPE_RAW_LZF 3
223/** Raw zero data.
224 * The record header is followed by a 8-bit field containing the size of the
225 * zero data in 1KB units. */
226#define SSM_REC_TYPE_RAW_ZERO 4
227/** Named data items.
228 * A length prefix zero terminated string (i.e. max 255) followed by the data. */
229#define SSM_REC_TYPE_NAMED 5
230/** Macro for validating the record type.
231 * This can be used with the flags+type byte, no need to mask out the type first. */
232#define SSM_REC_TYPE_IS_VALID(u8Type) ( ((u8Type) & SSM_REC_TYPE_MASK) > SSM_REC_TYPE_INVALID \
233 && ((u8Type) & SSM_REC_TYPE_MASK) <= SSM_REC_TYPE_NAMED )
234/** @} */
235
236/** The flag mask. */
237#define SSM_REC_FLAGS_MASK UINT8_C(0xf0)
238/** The record is important if this flag is set, if clear it can be omitted. */
239#define SSM_REC_FLAGS_IMPORTANT UINT8_C(0x10)
240/** This flag is always set. */
241#define SSM_REC_FLAGS_FIXED UINT8_C(0x80)
242/** Macro for validating the flags.
243 * No need to mask the flags out of the flags+type byte before invoking this macro. */
244#define SSM_REC_FLAGS_ARE_VALID(fFlags) ( ((fFlags) & UINT8_C(0xe0)) == UINT8_C(0x80) )
245
246/** Macro for validating the type and flags byte in a data record. */
247#define SSM_REC_ARE_TYPE_AND_FLAGS_VALID(u8) ( SSM_REC_FLAGS_ARE_VALID(u8) && SSM_REC_TYPE_IS_VALID(u8) )
248
249/** @name SSMRECTERM::fFlags
250 * @{ */
251/** There is a CRC-32 value for the stream. */
252#define SSMRECTERM_FLAGS_CRC32 UINT16_C(0x0001)
253/** @} */
254
255/** Start structure magic. (Isacc Asimov) */
256#define SSMR3STRUCT_BEGIN UINT32_C(0x19200102)
257/** End structure magic. (Isacc Asimov) */
258#define SSMR3STRUCT_END UINT32_C(0x19920406)
259
260
261/** Number of bytes to log in Log2 and Log4 statements. */
262#define SSM_LOG_BYTES 16
263
264/** SSMHANDLE::fCancelled value indicating that the operation has been
265 * cancelled. */
266#define SSMHANDLE_CANCELLED UINT32_C(0xdeadbeef)
267/** SSMHANDLE::fCancelled value indicating no cancellation. */
268#define SSMHANDLE_OK UINT32_C(0x77777777)
269
270
271/** Macro for checking the u32CRC field of a structure.
272 * The Msg can assume there are u32ActualCRC and u32CRC in the context. */
273#define SSM_CHECK_CRC32_RET(p, cb, Msg) \
274 do \
275 { \
276 uint32_t u32CRC = (p)->u32CRC; \
277 (p)->u32CRC = 0; \
278 uint32_t u32ActualCRC = RTCrc32((p), (cb)); \
279 (p)->u32CRC = u32CRC; \
280 AssertLogRelMsgReturn(u32ActualCRC == u32CRC, Msg, VERR_SSM_INTEGRITY_CRC); \
281 } while (0)
282
283/** The number of bytes to compress is one block.
284 * Must be a multiple of 1KB. */
285#define SSM_ZIP_BLOCK_SIZE _4K
286AssertCompile(SSM_ZIP_BLOCK_SIZE / _1K * _1K == SSM_ZIP_BLOCK_SIZE);
287
288
289/**
290 * Asserts that the handle is writable and returns with VERR_SSM_INVALID_STATE
291 * if it isn't.
292 */
293#define SSM_ASSERT_WRITEABLE_RET(pSSM) \
294 AssertMsgReturn( pSSM->enmOp == SSMSTATE_SAVE_EXEC \
295 || pSSM->enmOp == SSMSTATE_LIVE_EXEC,\
296 ("Invalid state %d\n", pSSM->enmOp), VERR_SSM_INVALID_STATE);
297
298/**
299 * Asserts that the handle is readable and returns with VERR_SSM_INVALID_STATE
300 * if it isn't.
301 */
302#define SSM_ASSERT_READABLE_RET(pSSM) \
303 AssertMsgReturn( pSSM->enmOp == SSMSTATE_LOAD_EXEC \
304 || pSSM->enmOp == SSMSTATE_OPEN_READ,\
305 ("Invalid state %d\n", pSSM->enmOp), VERR_SSM_INVALID_STATE);
306
307/** Checks for cancellation and returns if pending.
308 * Sets SSMHANDLE::rc to VERR_SSM_CANCELLED (if it still indicates success) and
309 * then returns SSMHANDLE::rc. (Debug logging only.) */
310#define SSM_CHECK_CANCELLED_RET(pSSM) \
311 do \
312 { \
313 if (RT_UNLIKELY(ASMAtomicUoReadU32(&(pSSM)->fCancelled) == SSMHANDLE_CANCELLED)) \
314 { \
315 LogFlow(("%Rfn: Cancelled -> VERR_SSM_CANCELLED\n", __PRETTY_FUNCTION__)); \
316 if (RT_SUCCESS((pSSM)->rc)) \
317 (pSSM)->rc = VERR_SSM_CANCELLED; \
318 return (pSSM)->rc; \
319 } \
320 } while (0)
321
322/**
323 * Asserts that the handle is somewhat valid. No returns as this is just a
324 * simple safeguard for catching bad API calls. */
325#define SSM_ASSERT_VALID_HANDLE(pSSM) \
326 do \
327 { \
328 AssertPtr(pSSM); \
329 Assert(pSSM->enmOp > SSMSTATE_INVALID && pSSM->enmOp < SSMSTATE_END); \
330 } while (0)
331
332
333/** @def SSM_HOST_IS_MSC_32
334 * Set to 1 if the host is 32-bit MSC, otherwise set to 0.
335 * */
336#if defined(_MSC_VER) && HC_ARCH_BITS == 32
337# define SSM_HOST_IS_MSC_32 1
338#else
339# define SSM_HOST_IS_MSC_32 0
340#endif
341
342
343
344/*******************************************************************************
345* Structures and Typedefs *
346*******************************************************************************/
347/** SSM state. */
348typedef enum SSMSTATE
349{
350 SSMSTATE_INVALID = 0,
351 SSMSTATE_LIVE_PREP,
352 SSMSTATE_LIVE_STEP1,
353 SSMSTATE_LIVE_EXEC,
354 SSMSTATE_LIVE_VOTE,
355 SSMSTATE_LIVE_STEP2,
356 SSMSTATE_SAVE_PREP,
357 SSMSTATE_SAVE_EXEC,
358 SSMSTATE_SAVE_DONE,
359 SSMSTATE_LOAD_PREP,
360 SSMSTATE_LOAD_EXEC,
361 SSMSTATE_LOAD_DONE,
362 SSMSTATE_OPEN_READ,
363 SSMSTATE_END
364} SSMSTATE;
365
366
367/** Pointer to a SSM stream buffer. */
368typedef struct SSMSTRMBUF *PSSMSTRMBUF;
369/**
370 * A SSM stream buffer.
371 */
372typedef struct SSMSTRMBUF
373{
374 /** The buffer data. */
375 uint8_t abData[_64K];
376
377 /** The stream position of this buffer. */
378 uint64_t offStream;
379 /** The amount of buffered data. */
380 uint32_t cb;
381 /** End of stream indicator (for read streams only). */
382 bool fEndOfStream;
383 /** Pointer to the next buffer in the chain. */
384 PSSMSTRMBUF volatile pNext;
385} SSMSTRMBUF;
386
387/**
388 * SSM stream.
389 *
390 * This is a typical producer / consumer setup with a dedicated I/O thread and
391 * fixed number of buffers for read ahead and write back.
392 */
393typedef struct SSMSTRM
394{
395 /** The stream method table. */
396 PCSSMSTRMOPS pOps;
397 /** The user argument for the stream methods.
398 * For file based streams, this is the file handle and not a pointer. */
399 void *pvUser;
400
401 /** Write (set) or read (clear) stream. */
402 bool fWrite;
403 /** Termination indicator. */
404 bool volatile fTerminating;
405 /** Indicates whether it is necessary to seek before the next buffer is
406 * read from the stream. This is used to avoid a seek in ssmR3StrmPeekAt. */
407 bool fNeedSeek;
408 /** Stream error status. */
409 int32_t volatile rc;
410 /** The handle of the I/O thread. This is set to nil when not active. */
411 RTTHREAD hIoThread;
412 /** Where to seek to. */
413 uint64_t offNeedSeekTo;
414
415 /** The head of the consumer queue.
416 * For save the consumer is the I/O thread. For load the I/O thread is the
417 * producer. */
418 PSSMSTRMBUF volatile pHead;
419 /** Chain of free buffers.
420 * The consumer/producer roles are the inverse of pHead. */
421 PSSMSTRMBUF volatile pFree;
422 /** Event that's signalled when pHead is updated. */
423 RTSEMEVENT hEvtHead;
424 /** Event that's signalled when pFree is updated. */
425 RTSEMEVENT hEvtFree;
426
427 /** List of pending buffers that has been dequeued from pHead and reversed. */
428 PSSMSTRMBUF pPending;
429 /** Pointer to the current buffer. */
430 PSSMSTRMBUF pCur;
431 /** The stream offset of the current buffer. */
432 uint64_t offCurStream;
433 /** The current buffer offset. */
434 uint32_t off;
435 /** Whether we're checksumming reads/writes. */
436 bool fChecksummed;
437 /** The stream CRC if fChecksummed is set. */
438 uint32_t u32StreamCRC;
439 /** How far into the buffer u32StreamCRC is up-to-date.
440 * This may lag behind off as it's desirable to checksum as large blocks as
441 * possible. */
442 uint32_t offStreamCRC;
443} SSMSTRM;
444/** Pointer to a SSM stream. */
445typedef SSMSTRM *PSSMSTRM;
446
447
448/**
449 * Handle structure.
450 */
451typedef struct SSMHANDLE
452{
453 /** Stream/buffer manager. */
454 SSMSTRM Strm;
455
456 /** The VM handle. */
457 PVM pVM;
458 /** The current operation. */
459 SSMSTATE enmOp;
460 /** What to do after save completes. (move the enum) */
461 SSMAFTER enmAfter;
462 /** Flag indicating that the operation has been cancelled. */
463 uint32_t volatile fCancelled;
464 /** The current rc of the save operation. */
465 int32_t rc;
466 /** Number of compressed bytes left in the current data unit (V1). */
467 uint64_t cbUnitLeftV1;
468 /** The current uncompressed offset into the data unit. */
469 uint64_t offUnit;
470 /** Indicates that this is a live save or restore operation. */
471 bool fLiveSave;
472
473 /** Pointer to the progress callback function. */
474 PFNVMPROGRESS pfnProgress;
475 /** User specified arguemnt to the callback function. */
476 void *pvUser;
477 /** Next completion percentage. (corresponds to offEstProgress) */
478 unsigned uPercent;
479 /** The position of the next progress callback in the estimated file. */
480 uint64_t offEstProgress;
481 /** The estimated total byte count.
482 * (Only valid after the prep.) */
483 uint64_t cbEstTotal;
484 /** Current position in the estimated file. */
485 uint64_t offEst;
486 /** End of current unit in the estimated file. */
487 uint64_t offEstUnitEnd;
488 /** the amount of % we reserve for the 'prepare' phase */
489 unsigned uPercentPrepare;
490 /** the amount of % we reserve for the 'done' stage */
491 unsigned uPercentDone;
492 /** The filename, NULL if remote stream. */
493 const char *pszFilename;
494
495 union
496 {
497 /** Write data. */
498 struct
499 {
500 /** Offset into the databuffer. */
501 uint32_t offDataBuffer;
502 /** Space for the record header. */
503 uint8_t abRecHdr[1+7];
504 /** Data buffer. */
505 uint8_t abDataBuffer[4096];
506 } Write;
507
508 /** Read data. */
509 struct
510 {
511 /** V1: The decompressor of the current data unit. */
512 PRTZIPDECOMP pZipDecompV1;
513 /** The major format version number. */
514 uint32_t uFmtVerMajor;
515 /** The minor format version number. */
516 uint32_t uFmtVerMinor;
517
518 /** V2: Unread bytes in the current record. */
519 uint32_t cbRecLeft;
520 /** V2: Bytes in the data buffer. */
521 uint32_t cbDataBuffer;
522 /** V2: Current buffer position. */
523 uint32_t offDataBuffer;
524 /** V2: End of data indicator. */
525 bool fEndOfData;
526 /** V2: The type and flags byte fo the current record. */
527 uint8_t u8TypeAndFlags;
528
529 /** RTGCPHYS size in bytes. (Only applicable when loading/reading.) */
530 unsigned cbGCPhys;
531 /** RTGCPTR size in bytes. (Only applicable when loading/reading.) */
532 unsigned cbGCPtr;
533 /** Whether cbGCPtr is fixed or settable. */
534 bool fFixedGCPtrSize;
535
536 /** 32-bit MSC saved this? */
537 bool fIsHostMsc32;
538
539 /** @name Header info (set by ssmR3ValidateFile)
540 * @{ */
541 /** The size of the file header. */
542 size_t cbFileHdr;
543 /** The major version number. */
544 uint16_t u16VerMajor;
545 /** The minor version number. */
546 uint16_t u16VerMinor;
547 /** The build number. */
548 uint32_t u32VerBuild;
549 /** The SVN revision. */
550 uint32_t u32SvnRev;
551 /** 32 or 64 depending on the host. */
552 uint8_t cHostBits;
553 /** Whether the stream is checksummed (SSMFILEHDR_FLAGS_STREAM_CRC32). */
554 bool fStreamCrc32;
555 /** The CRC of the loaded file. */
556 uint32_t u32LoadCRC;
557 /** The size of the load file. */
558 uint64_t cbLoadFile;
559 /** @} */
560
561 /** V2: Data buffer.
562 * @remarks Be extremely careful when changing the size of this buffer! */
563 uint8_t abDataBuffer[4096];
564
565 /** V2: Decompression buffer for when we cannot use the stream buffer. */
566 uint8_t abComprBuffer[4096];
567 } Read;
568 } u;
569} SSMHANDLE;
570
571
572/**
573 * Header of the saved state file.
574 *
575 * Added in r5xxxx on 2009-07-2?, VirtualBox v3.0.51.
576 */
577typedef struct SSMFILEHDR
578{
579 /** Magic string which identifies this file as a version of VBox saved state
580 * file format (SSMFILEHDR_MAGIC_V2_0). */
581 char szMagic[32];
582 /** The major version number. */
583 uint16_t u16VerMajor;
584 /** The minor version number. */
585 uint16_t u16VerMinor;
586 /** The build number. */
587 uint32_t u32VerBuild;
588 /** The SVN revision. */
589 uint32_t u32SvnRev;
590 /** 32 or 64 depending on the host. */
591 uint8_t cHostBits;
592 /** The size of RTGCPHYS. */
593 uint8_t cbGCPhys;
594 /** The size of RTGCPTR. */
595 uint8_t cbGCPtr;
596 /** Reserved header space - must be zero. */
597 uint8_t u8Reserved;
598 /** The number of units that (may) have stored data in the file. */
599 uint32_t cUnits;
600 /** Flags, see SSMFILEHDR_FLAGS_XXX. */
601 uint32_t fFlags;
602 /** The maximum size of decompressed data. */
603 uint32_t cbMaxDecompr;
604 /** The checksum of this header.
605 * This field is set to zero when calculating the checksum. */
606 uint32_t u32CRC;
607} SSMFILEHDR;
608AssertCompileSize(SSMFILEHDR, 64);
609AssertCompileMemberOffset(SSMFILEHDR, u32CRC, 60);
610AssertCompileMemberSize(SSMFILEHDR, szMagic, sizeof(SSMFILEHDR_MAGIC_V2_0));
611/** Pointer to a saved state file header. */
612typedef SSMFILEHDR *PSSMFILEHDR;
613/** Pointer to a const saved state file header. */
614typedef SSMFILEHDR const *PCSSMFILEHDR;
615
616
617/**
618 * Header of the saved state file.
619 *
620 * Added in r40980 on 2008-12-15, VirtualBox v2.0.51.
621 *
622 * @remarks This is a superset of SSMFILEHDRV11.
623 */
624typedef struct SSMFILEHDRV12
625{
626 /** Magic string which identifies this file as a version of VBox saved state
627 * file format (SSMFILEHDR_MAGIC_V1_2). */
628 char achMagic[32];
629 /** The size of this file. Used to check
630 * whether the save completed and that things are fine otherwise. */
631 uint64_t cbFile;
632 /** File checksum. The actual calculation skips past the u32CRC field. */
633 uint32_t u32CRC;
634 /** Padding. */
635 uint32_t u32Reserved;
636 /** The machine UUID. (Ignored if NIL.) */
637 RTUUID MachineUuid;
638
639 /** The major version number. */
640 uint16_t u16VerMajor;
641 /** The minor version number. */
642 uint16_t u16VerMinor;
643 /** The build number. */
644 uint32_t u32VerBuild;
645 /** The SVN revision. */
646 uint32_t u32SvnRev;
647
648 /** 32 or 64 depending on the host. */
649 uint8_t cHostBits;
650 /** The size of RTGCPHYS. */
651 uint8_t cbGCPhys;
652 /** The size of RTGCPTR. */
653 uint8_t cbGCPtr;
654 /** Padding. */
655 uint8_t au8Reserved;
656} SSMFILEHDRV12;
657AssertCompileSize(SSMFILEHDRV12, 64+16);
658AssertCompileMemberOffset(SSMFILEHDRV12, u32CRC, 40);
659AssertCompileMemberSize(SSMFILEHDRV12, achMagic, sizeof(SSMFILEHDR_MAGIC_V1_2));
660/** Pointer to a saved state file header. */
661typedef SSMFILEHDRV12 *PSSMFILEHDRV12;
662
663
664/**
665 * Header of the saved state file, version 1.1.
666 *
667 * Added in r23677 on 2007-08-17, VirtualBox v1.4.1.
668 */
669typedef struct SSMFILEHDRV11
670{
671 /** Magic string which identifies this file as a version of VBox saved state
672 * file format (SSMFILEHDR_MAGIC_V1_1). */
673 char achMagic[32];
674 /** The size of this file. Used to check
675 * whether the save completed and that things are fine otherwise. */
676 uint64_t cbFile;
677 /** File checksum. The actual calculation skips past the u32CRC field. */
678 uint32_t u32CRC;
679 /** Padding. */
680 uint32_t u32Reserved;
681 /** The machine UUID. (Ignored if NIL.) */
682 RTUUID MachineUuid;
683} SSMFILEHDRV11;
684AssertCompileSize(SSMFILEHDRV11, 64);
685AssertCompileMemberOffset(SSMFILEHDRV11, u32CRC, 40);
686/** Pointer to a saved state file header. */
687typedef SSMFILEHDRV11 *PSSMFILEHDRV11;
688
689
690/**
691 * Data unit header.
692 */
693typedef struct SSMFILEUNITHDRV2
694{
695 /** Magic (SSMFILEUNITHDR_MAGIC or SSMFILEUNITHDR_END). */
696 char szMagic[8];
697 /** The offset in the saved state stream of the start of this unit.
698 * This is mainly intended for sanity checking. */
699 uint64_t offStream;
700 /** The CRC-in-progress value this unit starts at. */
701 uint32_t u32CurStreamCRC;
702 /** The checksum of this structure, including the whole name.
703 * Calculated with this field set to zero. */
704 uint32_t u32CRC;
705 /** Data version. */
706 uint32_t u32Version;
707 /** Instance number. */
708 uint32_t u32Instance;
709 /** Data pass number. */
710 uint32_t u32Pass;
711 /** Flags reserved for future extensions. Must be zero. */
712 uint32_t fFlags;
713 /** Size of the data unit name including the terminator. (bytes) */
714 uint32_t cbName;
715 /** Data unit name, variable size. */
716 char szName[SSM_MAX_NAME_SIZE];
717} SSMFILEUNITHDRV2;
718AssertCompileMemberOffset(SSMFILEUNITHDRV2, szName, 44);
719AssertCompileMemberSize(SSMFILEUNITHDRV2, szMagic, sizeof(SSMFILEUNITHDR_MAGIC));
720AssertCompileMemberSize(SSMFILEUNITHDRV2, szMagic, sizeof(SSMFILEUNITHDR_END));
721/** Pointer to SSMFILEUNITHDRV2. */
722typedef SSMFILEUNITHDRV2 *PSSMFILEUNITHDRV2;
723
724
725/**
726 * Data unit header.
727 *
728 * This is used by v1.0, v1.1 and v1.2 of the format.
729 */
730typedef struct SSMFILEUNITHDRV1
731{
732 /** Magic (SSMFILEUNITHDR_MAGIC or SSMFILEUNITHDR_END). */
733 char achMagic[8];
734 /** Number of bytes in this data unit including the header. */
735 uint64_t cbUnit;
736 /** Data version. */
737 uint32_t u32Version;
738 /** Instance number. */
739 uint32_t u32Instance;
740 /** Size of the data unit name including the terminator. (bytes) */
741 uint32_t cchName;
742 /** Data unit name. */
743 char szName[1];
744} SSMFILEUNITHDRV1;
745/** Pointer to SSMFILEUNITHDR. */
746typedef SSMFILEUNITHDRV1 *PSSMFILEUNITHDRV1;
747
748
749/**
750 * Termination data record.
751 */
752typedef struct SSMRECTERM
753{
754 uint8_t u8TypeAndFlags;
755 /** The record size (sizeof(SSMRECTERM) - 2). */
756 uint8_t cbRec;
757 /** Flags, see SSMRECTERM_FLAGS_CRC32. */
758 uint16_t fFlags;
759 /** The checksum of the stream up to fFlags (exclusive). */
760 uint32_t u32StreamCRC;
761 /** The length of this data unit in bytes (including this record). */
762 uint64_t cbUnit;
763} SSMRECTERM;
764AssertCompileSize(SSMRECTERM, 16);
765AssertCompileMemberAlignment(SSMRECTERM, cbUnit, 8);
766/** Pointer to a termination record. */
767typedef SSMRECTERM *PSSMRECTERM;
768/** Pointer to a const termination record. */
769typedef SSMRECTERM const *PCSSMRECTERM;
770
771
772/**
773 * Directory entry.
774 */
775typedef struct SSMFILEDIRENTRY
776{
777 /** The offset of the data unit. */
778 uint64_t off;
779 /** The instance number. */
780 uint32_t u32Instance;
781 /** The CRC-32 of the name excluding the terminator. (lazy bird) */
782 uint32_t u32NameCRC;
783} SSMFILEDIRENTRY;
784AssertCompileSize(SSMFILEDIRENTRY, 16);
785/** Pointer to a directory entry. */
786typedef SSMFILEDIRENTRY *PSSMFILEDIRENTRY;
787/** Pointer to a const directory entry. */
788typedef SSMFILEDIRENTRY const *PCSSMFILEDIRENTRY;
789
790/**
791 * Directory for the data units from the final pass.
792 *
793 * This is used to speed up SSMR3Seek (it would have to decompress and parse the
794 * whole stream otherwise).
795 */
796typedef struct SSMFILEDIR
797{
798 /** Magic string (SSMFILEDIR_MAGIC). */
799 char szMagic[8];
800 /** The CRC-32 for the whole directory.
801 * Calculated with this field set to zero. */
802 uint32_t u32CRC;
803 /** The number of directory entries. */
804 uint32_t cEntries;
805 /** The directory entries (variable size). */
806 SSMFILEDIRENTRY aEntries[1];
807} SSMFILEDIR;
808AssertCompileSize(SSMFILEDIR, 32);
809/** Pointer to a directory. */
810typedef SSMFILEDIR *PSSMFILEDIR;
811/** Pointer to a const directory. */
812typedef SSMFILEDIR *PSSMFILEDIR;
813
814
815/**
816 * Footer structure
817 */
818typedef struct SSMFILEFTR
819{
820 /** Magic string (SSMFILEFTR_MAGIC). */
821 char szMagic[8];
822 /** The offset of this record in the stream. */
823 uint64_t offStream;
824 /** The CRC for the stream.
825 * This is set to zero if SSMFILEHDR_FLAGS_STREAM_CRC32 is clear. */
826 uint32_t u32StreamCRC;
827 /** Number directory entries. */
828 uint32_t cDirEntries;
829 /** Reserved footer space - must be zero. */
830 uint32_t u32Reserved;
831 /** The CRC-32 for this structure.
832 * Calculated with this field set to zero. */
833 uint32_t u32CRC;
834} SSMFILEFTR;
835AssertCompileSize(SSMFILEFTR, 32);
836/** Pointer to a footer. */
837typedef SSMFILEFTR *PSSMFILEFTR;
838/** Pointer to a const footer. */
839typedef SSMFILEFTR const *PCSSMFILEFTR;
840
841
842/*******************************************************************************
843* Internal Functions *
844*******************************************************************************/
845static int ssmR3LazyInit(PVM pVM);
846static DECLCALLBACK(int) ssmR3SelfLiveExec(PVM pVM, PSSMHANDLE pSSM, uint32_t uPass);
847static DECLCALLBACK(int) ssmR3SelfSaveExec(PVM pVM, PSSMHANDLE pSSM);
848static DECLCALLBACK(int) ssmR3SelfLoadExec(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass);
849static int ssmR3Register(PVM pVM, const char *pszName, uint32_t uInstance, uint32_t uVersion, size_t cbGuess, const char *pszBefore, PSSMUNIT *ppUnit);
850
851static int ssmR3StrmWriteBuffers(PSSMSTRM pStrm);
852static int ssmR3StrmReadMore(PSSMSTRM pStrm);
853
854static int ssmR3DataFlushBuffer(PSSMHANDLE pSSM);
855static int ssmR3DataReadRecHdrV2(PSSMHANDLE pSSM);
856
857
858
859/**
860 * Cleans up resources allocated by SSM on VM termination.
861 *
862 * @param pVM The VM handle.
863 */
864VMMR3_INT_DECL(void) SSMR3Term(PVM pVM)
865{
866 if (pVM->ssm.s.fInitialized)
867 {
868 pVM->ssm.s.fInitialized = false;
869 RTCritSectDelete(&pVM->ssm.s.CancelCritSect);
870 }
871}
872
873
874/**
875 * Performs lazy initialization of the SSM.
876 *
877 * @returns VBox status code.
878 * @param pVM The VM.
879 */
880static int ssmR3LazyInit(PVM pVM)
881{
882 /*
883 * Register a saved state unit which we use to put the VirtualBox version,
884 * revision and similar stuff in.
885 */
886 pVM->ssm.s.fInitialized = true;
887 int rc = SSMR3RegisterInternal(pVM, "SSM", 0 /*uInstance*/, 1 /*uVersion*/, 64 /*cbGuess*/,
888 NULL /*pfnLivePrep*/, ssmR3SelfLiveExec, NULL /*pfnLiveVote*/,
889 NULL /*pfnSavePrep*/, ssmR3SelfSaveExec, NULL /*pfnSaveDone*/,
890 NULL /*pfnSavePrep*/, ssmR3SelfLoadExec, NULL /*pfnSaveDone*/);
891
892 /*
893 * Initialize the cancellation critsect now.
894 */
895 if (RT_SUCCESS(rc))
896 rc = RTCritSectInit(&pVM->ssm.s.CancelCritSect);
897
898 pVM->ssm.s.fInitialized = RT_SUCCESS(rc);
899 return rc;
900}
901
902
903/**
904 * Do ssmR3SelfSaveExec in pass 0.
905 *
906 * @returns VBox status code.
907 * @param pVM Pointer to the shared VM structure.
908 * @param pSSM The SSM handle.
909 * @param uPass The data pass number.
910 */
911static DECLCALLBACK(int) ssmR3SelfLiveExec(PVM pVM, PSSMHANDLE pSSM, uint32_t uPass)
912{
913 if (uPass == 0)
914 {
915 int rc = ssmR3SelfSaveExec(pVM, pSSM);
916 if (RT_SUCCESS(rc))
917 rc = VINF_SSM_DONT_CALL_AGAIN;
918 return rc;
919 }
920 AssertFailed();
921 return VERR_INTERNAL_ERROR_3;
922}
923
924
925/**
926 * For saving usful things without having to go thru the tedious process of
927 * adding it to the header.
928 *
929 * @returns VBox status code.
930 * @param pVM Pointer to the shared VM structure.
931 * @param pSSM The SSM handle.
932 */
933static DECLCALLBACK(int) ssmR3SelfSaveExec(PVM pVM, PSSMHANDLE pSSM)
934{
935 /*
936 * String table containg pairs of variable and value string.
937 * Terminated by two empty strings.
938 */
939 SSMR3PutStrZ(pSSM, "Build Type");
940 SSMR3PutStrZ(pSSM, KBUILD_TYPE);
941 SSMR3PutStrZ(pSSM, "Host OS");
942 SSMR3PutStrZ(pSSM, KBUILD_TARGET "." KBUILD_TARGET_ARCH);
943#ifdef VBOX_OSE
944 SSMR3PutStrZ(pSSM, "OSE");
945 SSMR3PutStrZ(pSSM, "true");
946#endif
947
948 /* terminator */
949 SSMR3PutStrZ(pSSM, "");
950 return SSMR3PutStrZ(pSSM, "");
951}
952
953
954/**
955 * For load the version + revision and stuff.
956 *
957 * @returns VBox status code.
958 * @param pVM Pointer to the shared VM structure.
959 * @param pSSM The SSM handle.
960 * @param uVersion The version (1).
961 * @param uPass The pass.
962 */
963static DECLCALLBACK(int) ssmR3SelfLoadExec(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
964{
965 AssertLogRelMsgReturn(uVersion == 1, ("%d", uVersion), VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION);
966
967 /*
968 * The first and last passes contains a {name, value} string table that is
969 * terminated by two emptry strings. It contains useful informal build
970 * info and can be very handy when something goes wrong after restore.
971 */
972 if ( uPass == 0
973 || uPass == SSM_PASS_FINAL)
974 {
975 for (unsigned i = 0; ; i++)
976 {
977 char szVar[128];
978 char szValue[1024];
979 int rc = SSMR3GetStrZ(pSSM, szVar, sizeof(szVar));
980 AssertRCReturn(rc, rc);
981 rc = SSMR3GetStrZ(pSSM, szValue, sizeof(szValue));
982 AssertRCReturn(rc, rc);
983 if (!szVar[0] && !szValue[0])
984 break;
985 if (i == 0)
986 LogRel(("SSM: Saved state info:\n"));
987 LogRel(("SSM: %s: %s\n", szVar, szValue));
988
989 /*
990 * Detect 32-bit MSC for handling SSMFIELD_ENTRY_PAD_MSC32_AUTO.
991 */
992 if (!strcmp(szVar, "Host OS"))
993 {
994 bool fIsHostMsc32 = !strcmp(szValue, "win.x86");
995 if (fIsHostMsc32 != pSSM->u.Read.fIsHostMsc32)
996 {
997 LogRel(("SSM: (fIsHostMsc32 %RTbool => %RTbool)\n", pSSM->u.Read.fIsHostMsc32, fIsHostMsc32));
998 pSSM->u.Read.fIsHostMsc32 = fIsHostMsc32;
999 }
1000 }
1001 }
1002 }
1003 return VINF_SUCCESS;
1004}
1005
1006
1007/**
1008 * Internal registration worker.
1009 *
1010 * @returns VBox status code.
1011 * @param pVM The VM handle.
1012 * @param pszName Data unit name.
1013 * @param uInstance The instance id.
1014 * @param uVersion The data unit version.
1015 * @param cbGuess The guessed data unit size.
1016 * @param pszBefore Name of data unit to be placed in front of.
1017 * Optional.
1018 * @param ppUnit Where to store the insterted unit node.
1019 * Caller must fill in the missing details.
1020 */
1021static int ssmR3Register(PVM pVM, const char *pszName, uint32_t uInstance,
1022 uint32_t uVersion, size_t cbGuess, const char *pszBefore, PSSMUNIT *ppUnit)
1023{
1024 /*
1025 * Validate input.
1026 */
1027 AssertPtr(pszName);
1028 AssertReturn(*pszName, VERR_INVALID_PARAMETER);
1029 size_t cchName = strlen(pszName);
1030 AssertMsgReturn(cchName < SSM_MAX_NAME_SIZE, ("%zu >= %u: %s\n", cchName, SSM_MAX_NAME_SIZE, pszName), VERR_OUT_OF_RANGE);
1031
1032 AssertReturn(!pszBefore || *pszBefore, VERR_INVALID_PARAMETER);
1033 size_t cchBefore = pszBefore ? strlen(pszBefore) : 0;
1034 AssertMsgReturn(cchBefore < SSM_MAX_NAME_SIZE, ("%zu >= %u: %s\n", cchBefore, SSM_MAX_NAME_SIZE, pszBefore), VERR_OUT_OF_RANGE);
1035
1036 /*
1037 * Lazy init.
1038 */
1039 if (!pVM->ssm.s.fInitialized)
1040 {
1041 int rc = ssmR3LazyInit(pVM);
1042 AssertRCReturn(rc, rc);
1043 }
1044
1045 /*
1046 * Walk to the end of the list checking for duplicates as we go.
1047 */
1048 PSSMUNIT pUnitBeforePrev = NULL;
1049 PSSMUNIT pUnitBefore = NULL;
1050 PSSMUNIT pUnitPrev = NULL;
1051 PSSMUNIT pUnit = pVM->ssm.s.pHead;
1052 while (pUnit)
1053 {
1054 if ( pUnit->u32Instance == uInstance
1055 && pUnit->cchName == cchName
1056 && !memcmp(pUnit->szName, pszName, cchName))
1057 {
1058 AssertMsgFailed(("Duplicate registration %s\n", pszName));
1059 return VERR_SSM_UNIT_EXISTS;
1060 }
1061 if ( pUnit->cchName == cchBefore
1062 && !pUnitBefore
1063 && !memcmp(pUnit->szName, pszBefore, cchBefore))
1064 {
1065 pUnitBeforePrev = pUnitPrev;
1066 pUnitBefore = pUnit;
1067 }
1068
1069 /* next */
1070 pUnitPrev = pUnit;
1071 pUnit = pUnit->pNext;
1072 }
1073
1074 /*
1075 * Allocate new node.
1076 */
1077 pUnit = (PSSMUNIT)MMR3HeapAllocZ(pVM, MM_TAG_SSM, RT_OFFSETOF(SSMUNIT, szName[cchName + 1]));
1078 if (!pUnit)
1079 return VERR_NO_MEMORY;
1080
1081 /*
1082 * Fill in (some) data. (Stuff is zero'ed.)
1083 */
1084 pUnit->u32Version = uVersion;
1085 pUnit->u32Instance = uInstance;
1086 pUnit->cbGuess = cbGuess;
1087 pUnit->cchName = cchName;
1088 memcpy(pUnit->szName, pszName, cchName);
1089
1090 /*
1091 * Insert
1092 */
1093 if (pUnitBefore)
1094 {
1095 pUnit->pNext = pUnitBefore;
1096 if (pUnitBeforePrev)
1097 pUnitBeforePrev->pNext = pUnit;
1098 else
1099 pVM->ssm.s.pHead = pUnit;
1100 }
1101 else if (pUnitPrev)
1102 pUnitPrev->pNext = pUnit;
1103 else
1104 pVM->ssm.s.pHead = pUnit;
1105 pVM->ssm.s.cUnits++;
1106
1107 *ppUnit = pUnit;
1108 return VINF_SUCCESS;
1109}
1110
1111
1112/**
1113 * Register a PDM Devices data unit.
1114 *
1115 * @returns VBox status.
1116 *
1117 * @param pVM The VM handle.
1118 * @param pDevIns Device instance.
1119 * @param pszName Data unit name.
1120 * @param uInstance The instance identifier of the data unit.
1121 * This must together with the name be unique.
1122 * @param uVersion Data layout version number.
1123 * @param cbGuess The approximate amount of data in the unit.
1124 * Only for progress indicators.
1125 * @param pszBefore Name of data unit which we should be put in front
1126 * of. Optional (NULL).
1127 *
1128 * @param pfnLivePrep Prepare live save callback, optional.
1129 * @param pfnLiveExec Execute live save callback, optional.
1130 * @param pfnLiveVote Vote live save callback, optional.
1131 *
1132 * @param pfnSavePrep Prepare save callback, optional.
1133 * @param pfnSaveExec Execute save callback, optional.
1134 * @param pfnSaveDone Done save callback, optional.
1135 *
1136 * @param pfnLoadPrep Prepare load callback, optional.
1137 * @param pfnLoadExec Execute load callback, optional.
1138 * @param pfnLoadDone Done load callback, optional.
1139 */
1140VMMR3DECL(int) SSMR3RegisterDevice(PVM pVM, PPDMDEVINS pDevIns, const char *pszName, uint32_t uInstance, uint32_t uVersion, size_t cbGuess, const char *pszBefore,
1141 PFNSSMDEVLIVEPREP pfnLivePrep, PFNSSMDEVLIVEEXEC pfnLiveExec, PFNSSMDEVLIVEVOTE pfnLiveVote,
1142 PFNSSMDEVSAVEPREP pfnSavePrep, PFNSSMDEVSAVEEXEC pfnSaveExec, PFNSSMDEVSAVEDONE pfnSaveDone,
1143 PFNSSMDEVLOADPREP pfnLoadPrep, PFNSSMDEVLOADEXEC pfnLoadExec, PFNSSMDEVLOADDONE pfnLoadDone)
1144{
1145 PSSMUNIT pUnit;
1146 int rc = ssmR3Register(pVM, pszName, uInstance, uVersion, cbGuess, pszBefore, &pUnit);
1147 if (RT_SUCCESS(rc))
1148 {
1149 pUnit->enmType = SSMUNITTYPE_DEV;
1150 pUnit->u.Dev.pfnLivePrep = pfnLivePrep;
1151 pUnit->u.Dev.pfnLiveExec = pfnLiveExec;
1152 pUnit->u.Dev.pfnLiveVote = pfnLiveVote;
1153 pUnit->u.Dev.pfnSavePrep = pfnSavePrep;
1154 pUnit->u.Dev.pfnSaveExec = pfnSaveExec;
1155 pUnit->u.Dev.pfnSaveDone = pfnSaveDone;
1156 pUnit->u.Dev.pfnLoadPrep = pfnLoadPrep;
1157 pUnit->u.Dev.pfnLoadExec = pfnLoadExec;
1158 pUnit->u.Dev.pfnLoadDone = pfnLoadDone;
1159 pUnit->u.Dev.pDevIns = pDevIns;
1160 }
1161 return rc;
1162}
1163
1164
1165/**
1166 * Register a PDM driver data unit.
1167 *
1168 * @returns VBox status.
1169 *
1170 * @param pVM The VM handle.
1171 * @param pDrvIns Driver instance.
1172 * @param pszName Data unit name.
1173 * @param uInstance The instance identifier of the data unit.
1174 * This must together with the name be unique.
1175 * @param uVersion Data layout version number.
1176 * @param cbGuess The approximate amount of data in the unit.
1177 * Only for progress indicators.
1178 *
1179 * @param pfnLivePrep Prepare live save callback, optional.
1180 * @param pfnLiveExec Execute live save callback, optional.
1181 * @param pfnLiveVote Vote live save callback, optional.
1182 *
1183 * @param pfnSavePrep Prepare save callback, optional.
1184 * @param pfnSaveExec Execute save callback, optional.
1185 * @param pfnSaveDone Done save callback, optional.
1186 *
1187 * @param pfnLoadPrep Prepare load callback, optional.
1188 * @param pfnLoadExec Execute load callback, optional.
1189 * @param pfnLoadDone Done load callback, optional.
1190 */
1191VMMR3DECL(int) SSMR3RegisterDriver(PVM pVM, PPDMDRVINS pDrvIns, const char *pszName, uint32_t uInstance, uint32_t uVersion, size_t cbGuess,
1192 PFNSSMDRVLIVEPREP pfnLivePrep, PFNSSMDRVLIVEEXEC pfnLiveExec, PFNSSMDRVLIVEVOTE pfnLiveVote,
1193 PFNSSMDRVSAVEPREP pfnSavePrep, PFNSSMDRVSAVEEXEC pfnSaveExec, PFNSSMDRVSAVEDONE pfnSaveDone,
1194 PFNSSMDRVLOADPREP pfnLoadPrep, PFNSSMDRVLOADEXEC pfnLoadExec, PFNSSMDRVLOADDONE pfnLoadDone)
1195{
1196 PSSMUNIT pUnit;
1197 int rc = ssmR3Register(pVM, pszName, uInstance, uVersion, cbGuess, NULL, &pUnit);
1198 if (RT_SUCCESS(rc))
1199 {
1200 pUnit->enmType = SSMUNITTYPE_DRV;
1201 pUnit->u.Drv.pfnSavePrep = pfnSavePrep;
1202 pUnit->u.Drv.pfnSaveExec = pfnSaveExec;
1203 pUnit->u.Drv.pfnSaveDone = pfnSaveDone;
1204 pUnit->u.Drv.pfnLoadPrep = pfnLoadPrep;
1205 pUnit->u.Drv.pfnLoadExec = pfnLoadExec;
1206 pUnit->u.Drv.pfnLoadDone = pfnLoadDone;
1207 pUnit->u.Drv.pDrvIns = pDrvIns;
1208 }
1209 return rc;
1210}
1211
1212
1213/**
1214 * Register a internal data unit.
1215 *
1216 * @returns VBox status.
1217 *
1218 * @param pVM The VM handle.
1219 * @param pszName Data unit name.
1220 * @param uInstance The instance identifier of the data unit.
1221 * This must together with the name be unique.
1222 * @param uVersion Data layout version number.
1223 * @param cbGuess The approximate amount of data in the unit.
1224 * Only for progress indicators.
1225 *
1226 * @param pfnLivePrep Prepare live save callback, optional.
1227 * @param pfnLiveExec Execute live save callback, optional.
1228 * @param pfnLiveVote Vote live save callback, optional.
1229 *
1230 * @param pfnSavePrep Prepare save callback, optional.
1231 * @param pfnSaveExec Execute save callback, optional.
1232 * @param pfnSaveDone Done save callback, optional.
1233 *
1234 * @param pfnLoadPrep Prepare load callback, optional.
1235 * @param pfnLoadExec Execute load callback, optional.
1236 * @param pfnLoadDone Done load callback, optional.
1237 */
1238VMMR3DECL(int) SSMR3RegisterInternal(PVM pVM, const char *pszName, uint32_t uInstance, uint32_t uVersion, size_t cbGuess,
1239 PFNSSMINTLIVEPREP pfnLivePrep, PFNSSMINTLIVEEXEC pfnLiveExec, PFNSSMINTLIVEVOTE pfnLiveVote,
1240 PFNSSMINTSAVEPREP pfnSavePrep, PFNSSMINTSAVEEXEC pfnSaveExec, PFNSSMINTSAVEDONE pfnSaveDone,
1241 PFNSSMINTLOADPREP pfnLoadPrep, PFNSSMINTLOADEXEC pfnLoadExec, PFNSSMINTLOADDONE pfnLoadDone)
1242{
1243 PSSMUNIT pUnit;
1244 int rc = ssmR3Register(pVM, pszName, uInstance, uVersion, cbGuess, NULL, &pUnit);
1245 if (RT_SUCCESS(rc))
1246 {
1247 pUnit->enmType = SSMUNITTYPE_INTERNAL;
1248 pUnit->u.Internal.pfnLivePrep = pfnLivePrep;
1249 pUnit->u.Internal.pfnLiveExec = pfnLiveExec;
1250 pUnit->u.Internal.pfnLiveVote = pfnLiveVote;
1251 pUnit->u.Internal.pfnSavePrep = pfnSavePrep;
1252 pUnit->u.Internal.pfnSaveExec = pfnSaveExec;
1253 pUnit->u.Internal.pfnSaveDone = pfnSaveDone;
1254 pUnit->u.Internal.pfnLoadPrep = pfnLoadPrep;
1255 pUnit->u.Internal.pfnLoadExec = pfnLoadExec;
1256 pUnit->u.Internal.pfnLoadDone = pfnLoadDone;
1257 }
1258 return rc;
1259}
1260
1261
1262/**
1263 * Register an external data unit.
1264 *
1265 * @returns VBox status.
1266 *
1267 * @param pVM The VM handle.
1268 * @param pszName Data unit name.
1269 * @param uInstance The instance identifier of the data unit.
1270 * This must together with the name be unique.
1271 * @param uVersion Data layout version number.
1272 * @param cbGuess The approximate amount of data in the unit.
1273 * Only for progress indicators.
1274 *
1275 * @param pfnLivePrep Prepare live save callback, optional.
1276 * @param pfnLiveExec Execute live save callback, optional.
1277 * @param pfnLiveVote Vote live save callback, optional.
1278 *
1279 * @param pfnSavePrep Prepare save callback, optional.
1280 * @param pfnSaveExec Execute save callback, optional.
1281 * @param pfnSaveDone Done save callback, optional.
1282 *
1283 * @param pfnLoadPrep Prepare load callback, optional.
1284 * @param pfnLoadExec Execute load callback, optional.
1285 * @param pfnLoadDone Done load callback, optional.
1286 * @param pvUser User argument.
1287 */
1288VMMR3DECL(int) SSMR3RegisterExternal(PVM pVM, const char *pszName, uint32_t uInstance, uint32_t uVersion, size_t cbGuess,
1289 PFNSSMEXTLIVEPREP pfnLivePrep, PFNSSMEXTLIVEEXEC pfnLiveExec, PFNSSMEXTLIVEVOTE pfnLiveVote,
1290 PFNSSMEXTSAVEPREP pfnSavePrep, PFNSSMEXTSAVEEXEC pfnSaveExec, PFNSSMEXTSAVEDONE pfnSaveDone,
1291 PFNSSMEXTLOADPREP pfnLoadPrep, PFNSSMEXTLOADEXEC pfnLoadExec, PFNSSMEXTLOADDONE pfnLoadDone, void *pvUser)
1292{
1293 PSSMUNIT pUnit;
1294 int rc = ssmR3Register(pVM, pszName, uInstance, uVersion, cbGuess, NULL, &pUnit);
1295 if (RT_SUCCESS(rc))
1296 {
1297 pUnit->enmType = SSMUNITTYPE_EXTERNAL;
1298 pUnit->u.External.pfnLivePrep = pfnLivePrep;
1299 pUnit->u.External.pfnLiveExec = pfnLiveExec;
1300 pUnit->u.External.pfnLiveVote = pfnLiveVote;
1301 pUnit->u.External.pfnSavePrep = pfnSavePrep;
1302 pUnit->u.External.pfnSaveExec = pfnSaveExec;
1303 pUnit->u.External.pfnSaveDone = pfnSaveDone;
1304 pUnit->u.External.pfnLoadPrep = pfnLoadPrep;
1305 pUnit->u.External.pfnLoadExec = pfnLoadExec;
1306 pUnit->u.External.pfnLoadDone = pfnLoadDone;
1307 pUnit->u.External.pvUser = pvUser;
1308 }
1309 return rc;
1310}
1311
1312
1313/**
1314 * Deregister one or more PDM Device data units.
1315 *
1316 * @returns VBox status.
1317 *
1318 * @param pVM The VM handle.
1319 * @param pDevIns Device instance.
1320 * @param pszName Data unit name.
1321 * Use NULL to deregister all data units for that device instance.
1322 * @param uInstance The instance identifier of the data unit.
1323 * This must together with the name be unique.
1324 * @remark Only for dynmaic data units and dynamic unloaded modules.
1325 */
1326VMMR3_INT_DECL(int) SSMR3DeregisterDevice(PVM pVM, PPDMDEVINS pDevIns, const char *pszName, uint32_t uInstance)
1327{
1328 /*
1329 * Validate input.
1330 */
1331 if (!pDevIns)
1332 {
1333 AssertMsgFailed(("pDevIns is NULL!\n"));
1334 return VERR_INVALID_PARAMETER;
1335 }
1336
1337 /*
1338 * Search the list.
1339 */
1340 size_t cchName = pszName ? strlen(pszName) : 0;
1341 int rc = pszName ? VERR_SSM_UNIT_NOT_FOUND : VINF_SUCCESS;
1342 PSSMUNIT pUnitPrev = NULL;
1343 PSSMUNIT pUnit = pVM->ssm.s.pHead;
1344 while (pUnit)
1345 {
1346 if ( pUnit->enmType == SSMUNITTYPE_DEV
1347 && ( !pszName
1348 || ( pUnit->cchName == cchName
1349 && !memcmp(pUnit->szName, pszName, cchName)))
1350 && pUnit->u32Instance == uInstance
1351 )
1352 {
1353 if (pUnit->u.Dev.pDevIns == pDevIns)
1354 {
1355 /*
1356 * Unlink it, advance pointer, and free the node.
1357 */
1358 PSSMUNIT pFree = pUnit;
1359 pUnit = pUnit->pNext;
1360 if (pUnitPrev)
1361 pUnitPrev->pNext = pUnit;
1362 else
1363 pVM->ssm.s.pHead = pUnit;
1364 pVM->ssm.s.cUnits--;
1365 Log(("SSM: Removed data unit '%s' (pdm dev).\n", pFree->szName));
1366 MMR3HeapFree(pFree);
1367
1368 if (pszName)
1369 return VINF_SUCCESS;
1370 rc = VINF_SUCCESS;
1371 continue;
1372 }
1373 else if (pszName)
1374 {
1375 AssertMsgFailed(("Caller is not owner! Owner=%p Caller=%p %s\n",
1376 pUnit->u.Dev.pDevIns, pDevIns, pszName));
1377 return VERR_SSM_UNIT_NOT_OWNER;
1378 }
1379 }
1380
1381 /* next */
1382 pUnitPrev = pUnit;
1383 pUnit = pUnit->pNext;
1384 }
1385
1386 return rc;
1387}
1388
1389
1390/**
1391 * Deregister one ore more PDM Driver data units.
1392 *
1393 * @returns VBox status.
1394 * @param pVM The VM handle.
1395 * @param pDrvIns Driver instance.
1396 * @param pszName Data unit name.
1397 * Use NULL to deregister all data units for that driver instance.
1398 * @param uInstance The instance identifier of the data unit.
1399 * This must together with the name be unique. Ignored if pszName is NULL.
1400 * @remark Only for dynmaic data units and dynamic unloaded modules.
1401 */
1402VMMR3_INT_DECL(int) SSMR3DeregisterDriver(PVM pVM, PPDMDRVINS pDrvIns, const char *pszName, uint32_t uInstance)
1403{
1404 /*
1405 * Validate input.
1406 */
1407 if (!pDrvIns)
1408 {
1409 AssertMsgFailed(("pDrvIns is NULL!\n"));
1410 return VERR_INVALID_PARAMETER;
1411 }
1412
1413 /*
1414 * Search the list.
1415 */
1416 size_t cchName = pszName ? strlen(pszName) : 0;
1417 int rc = pszName ? VERR_SSM_UNIT_NOT_FOUND : VINF_SUCCESS;
1418 PSSMUNIT pUnitPrev = NULL;
1419 PSSMUNIT pUnit = pVM->ssm.s.pHead;
1420 while (pUnit)
1421 {
1422 if ( pUnit->enmType == SSMUNITTYPE_DRV
1423 && ( !pszName
1424 || ( pUnit->cchName == cchName
1425 && !memcmp(pUnit->szName, pszName, cchName)
1426 && pUnit->u32Instance == uInstance))
1427 )
1428 {
1429 if (pUnit->u.Drv.pDrvIns == pDrvIns)
1430 {
1431 /*
1432 * Unlink it, advance pointer, and free the node.
1433 */
1434 PSSMUNIT pFree = pUnit;
1435 pUnit = pUnit->pNext;
1436 if (pUnitPrev)
1437 pUnitPrev->pNext = pUnit;
1438 else
1439 pVM->ssm.s.pHead = pUnit;
1440 pVM->ssm.s.cUnits--;
1441 Log(("SSM: Removed data unit '%s' (pdm drv).\n", pFree->szName));
1442 MMR3HeapFree(pFree);
1443
1444 if (pszName)
1445 return VINF_SUCCESS;
1446 rc = VINF_SUCCESS;
1447 continue;
1448 }
1449 else if (pszName)
1450 {
1451 AssertMsgFailed(("Caller is not owner! Owner=%p Caller=%p %s\n",
1452 pUnit->u.Drv.pDrvIns, pDrvIns, pszName));
1453 return VERR_SSM_UNIT_NOT_OWNER;
1454 }
1455 }
1456
1457 /* next */
1458 pUnitPrev = pUnit;
1459 pUnit = pUnit->pNext;
1460 }
1461
1462 return rc;
1463}
1464
1465
1466/**
1467 * Deregister a data unit.
1468 *
1469 * @returns VBox status.
1470 * @param pVM The VM handle.
1471 * @param enmType Unit type
1472 * @param pszName Data unit name.
1473 * @remark Only for dynmaic data units.
1474 */
1475static int ssmR3DeregisterByNameAndType(PVM pVM, const char *pszName, SSMUNITTYPE enmType)
1476{
1477 /*
1478 * Validate input.
1479 */
1480 if (!pszName)
1481 {
1482 AssertMsgFailed(("pszName is NULL!\n"));
1483 return VERR_INVALID_PARAMETER;
1484 }
1485
1486 /*
1487 * Search the list.
1488 */
1489 size_t cchName = strlen(pszName);
1490 int rc = VERR_SSM_UNIT_NOT_FOUND;
1491 PSSMUNIT pUnitPrev = NULL;
1492 PSSMUNIT pUnit = pVM->ssm.s.pHead;
1493 while (pUnit)
1494 {
1495 if ( pUnit->enmType == enmType
1496 && pUnit->cchName == cchName
1497 && !memcmp(pUnit->szName, pszName, cchName))
1498 {
1499 /*
1500 * Unlink it, advance pointer, and free the node.
1501 */
1502 PSSMUNIT pFree = pUnit;
1503 pUnit = pUnit->pNext;
1504 if (pUnitPrev)
1505 pUnitPrev->pNext = pUnit;
1506 else
1507 pVM->ssm.s.pHead = pUnit;
1508 pVM->ssm.s.cUnits--;
1509 Log(("SSM: Removed data unit '%s' (type=%d).\n", pFree->szName, enmType));
1510 MMR3HeapFree(pFree);
1511 return VINF_SUCCESS;
1512 }
1513
1514 /* next */
1515 pUnitPrev = pUnit;
1516 pUnit = pUnit->pNext;
1517 }
1518
1519 return rc;
1520}
1521
1522
1523/**
1524 * Deregister an internal data unit.
1525 *
1526 * @returns VBox status.
1527 * @param pVM The VM handle.
1528 * @param pszName Data unit name.
1529 * @remark Only for dynmaic data units.
1530 */
1531VMMR3DECL(int) SSMR3DeregisterInternal(PVM pVM, const char *pszName)
1532{
1533 return ssmR3DeregisterByNameAndType(pVM, pszName, SSMUNITTYPE_INTERNAL);
1534}
1535
1536
1537/**
1538 * Deregister an external data unit.
1539 *
1540 * @returns VBox status.
1541 * @param pVM The VM handle.
1542 * @param pszName Data unit name.
1543 * @remark Only for dynmaic data units.
1544 */
1545VMMR3DECL(int) SSMR3DeregisterExternal(PVM pVM, const char *pszName)
1546{
1547 return ssmR3DeregisterByNameAndType(pVM, pszName, SSMUNITTYPE_EXTERNAL);
1548}
1549
1550
1551/**
1552 * Initializes the stream after/before opening the file/whatever.
1553 *
1554 * @returns VINF_SUCCESS or VERR_NO_MEMORY.
1555 * @param pStrm The stream handle.
1556 * @param fChecksummed Whether the stream is to be checksummed while
1557 * written/read.
1558 * @param cBuffers The number of buffers.
1559 */
1560static int ssmR3StrmInitInternal(PSSMSTRM pStrm, bool fChecksummed, uint32_t cBuffers)
1561{
1562 Assert(cBuffers > 0);
1563
1564 /*
1565 * Init the common data members.
1566 */
1567 pStrm->fTerminating = false;
1568 pStrm->fNeedSeek = false;
1569 pStrm->rc = VINF_SUCCESS;
1570 pStrm->hIoThread = NIL_RTTHREAD;
1571 pStrm->offNeedSeekTo= UINT64_MAX;
1572
1573 pStrm->pHead = NULL;
1574 pStrm->pFree = NULL;
1575 pStrm->hEvtHead = NIL_RTSEMEVENT;
1576 pStrm->hEvtFree = NIL_RTSEMEVENT;
1577
1578 pStrm->pPending = NULL;
1579 pStrm->pCur = NULL;
1580 pStrm->offCurStream = 0;
1581 pStrm->off = 0;
1582 pStrm->fChecksummed = fChecksummed;
1583 pStrm->u32StreamCRC = fChecksummed ? RTCrc32Start() : 0;
1584 pStrm->offStreamCRC = 0;
1585
1586 /*
1587 * Allocate the buffers. Page align them in case that makes the kernel
1588 * and/or cpu happier in some way.
1589 */
1590 int rc = VINF_SUCCESS;
1591 for (uint32_t i = 0; i < cBuffers; i++)
1592 {
1593 PSSMSTRMBUF pBuf = (PSSMSTRMBUF)RTMemPageAllocZ(sizeof(*pBuf));
1594 if (!pBuf)
1595 {
1596 if (i > 2)
1597 {
1598 LogRel(("ssmR3StrmAllocBuffer: WARNING: Could only get %d stream buffers.\n", i));
1599 break;
1600 }
1601 LogRel(("ssmR3StrmAllocBuffer: Failed to allocate stream buffers. (i=%d)\n", i));
1602 return VERR_NO_MEMORY;
1603 }
1604
1605 /* link it */
1606 pBuf->pNext = pStrm->pFree;
1607 pStrm->pFree = pBuf;
1608 }
1609
1610 /*
1611 * Create the event semaphores.
1612 */
1613 rc = RTSemEventCreate(&pStrm->hEvtHead);
1614 if (RT_FAILURE(rc))
1615 return rc;
1616 rc = RTSemEventCreate(&pStrm->hEvtFree);
1617 if (RT_FAILURE(rc))
1618 return rc;
1619
1620 return VINF_SUCCESS;
1621}
1622
1623
1624/**
1625 * Destroys a list of buffers.
1626 *
1627 * @param pHead Pointer to the head.
1628 */
1629static void ssmR3StrmDestroyBufList(PSSMSTRMBUF pHead)
1630{
1631 while (pHead)
1632 {
1633 PSSMSTRMBUF pCur = pHead;
1634 pHead = pCur->pNext;
1635 pCur->pNext = NULL;
1636 RTMemPageFree(pCur);
1637 }
1638}
1639
1640
1641/**
1642 * Cleans up a stream after ssmR3StrmInitInternal has been called (regardless of
1643 * it succeeded or not).
1644 *
1645 * @param pStrm The stream handle.
1646 */
1647static void ssmR3StrmDelete(PSSMSTRM pStrm)
1648{
1649 RTMemPageFree(pStrm->pCur);
1650 pStrm->pCur = NULL;
1651 ssmR3StrmDestroyBufList(pStrm->pHead);
1652 pStrm->pHead = NULL;
1653 ssmR3StrmDestroyBufList(pStrm->pPending);
1654 pStrm->pPending = NULL;
1655 ssmR3StrmDestroyBufList(pStrm->pFree);
1656 pStrm->pFree = NULL;
1657
1658 RTSemEventDestroy(pStrm->hEvtHead);
1659 pStrm->hEvtHead = NIL_RTSEMEVENT;
1660
1661 RTSemEventDestroy(pStrm->hEvtFree);
1662 pStrm->hEvtFree = NIL_RTSEMEVENT;
1663}
1664
1665
1666/**
1667 * Initializes a stream that uses a method table.
1668 *
1669 * @returns VBox status code.
1670 * @param pStrm The stream manager structure.
1671 * @param pStreamOps The stream method table.
1672 * @param pvUser The user argument for the stream methods.
1673 * @param fWrite Whether to open for writing or reading.
1674 * @param fChecksummed Whether the stream is to be checksummed while
1675 * written/read.
1676 * @param cBuffers The number of buffers.
1677 */
1678static int ssmR3StrmInit(PSSMSTRM pStrm, PCSSMSTRMOPS pStreamOps, void *pvUser, bool fWrite, bool fChecksummed, uint32_t cBuffers)
1679{
1680 int rc = ssmR3StrmInitInternal(pStrm, fChecksummed, cBuffers);
1681 if (RT_SUCCESS(rc))
1682 {
1683 pStrm->pOps = pStreamOps;
1684 pStrm->pvUser = pvUser;
1685 pStrm->fWrite = fWrite;
1686 return VINF_SUCCESS;
1687 }
1688
1689 ssmR3StrmDelete(pStrm);
1690 pStrm->rc = rc;
1691 return rc;
1692}
1693
1694
1695/**
1696 * @copydoc SSMSTRMOPS::pfnWrite
1697 */
1698static DECLCALLBACK(int) ssmR3FileWrite(void *pvUser, uint64_t offStream, const void *pvBuf, size_t cbToWrite)
1699{
1700 Assert(RTFileTell((RTFILE)(uintptr_t)pvUser) == offStream); NOREF(offStream);
1701 return RTFileWriteAt((RTFILE)(uintptr_t)pvUser, offStream, pvBuf, cbToWrite, NULL); /** @todo use RTFileWrite */
1702}
1703
1704
1705/**
1706 * @copydoc SSMSTRMOPS::pfnRead
1707 */
1708static DECLCALLBACK(int) ssmR3FileRead(void *pvUser, uint64_t offStream, void *pvBuf, size_t cbToRead, size_t *pcbRead)
1709{
1710 Assert(RTFileTell((RTFILE)(uintptr_t)pvUser) == offStream); NOREF(offStream);
1711 return RTFileRead((RTFILE)(uintptr_t)pvUser, pvBuf, cbToRead, pcbRead);
1712}
1713
1714
1715/**
1716 * @copydoc SSMSTRMOPS::pfnSeek
1717 */
1718static DECLCALLBACK(int) ssmR3FileSeek(void *pvUser, int64_t offSeek, unsigned uMethod, uint64_t *poffActual)
1719{
1720 return RTFileSeek((RTFILE)(uintptr_t)pvUser, offSeek, uMethod, poffActual);
1721}
1722
1723
1724/**
1725 * @copydoc SSMSTRMOPS::pfnTell
1726 */
1727static DECLCALLBACK(uint64_t) ssmR3FileTell(void *pvUser)
1728{
1729 return RTFileTell((RTFILE)(uintptr_t)pvUser);
1730}
1731
1732
1733/**
1734 * @copydoc SSMSTRMOPS::pfnSize
1735 */
1736static DECLCALLBACK(int) ssmR3FileSize(void *pvUser, uint64_t *pcb)
1737{
1738 return RTFileGetSize((RTFILE)(uintptr_t)pvUser, pcb);
1739}
1740
1741
1742/**
1743 * @copydoc SSMSTRMOPS::pfnClose
1744 */
1745static DECLCALLBACK(int) ssmR3FileClose(void *pvUser)
1746{
1747 return RTFileClose((RTFILE)(uintptr_t)pvUser);
1748}
1749
1750
1751/**
1752 * Method table for a file based stream.
1753 */
1754static SSMSTRMOPS const g_ssmR3FileOps =
1755{
1756 SSMSTRMOPS_VERSION,
1757 ssmR3FileWrite,
1758 ssmR3FileRead,
1759 ssmR3FileSeek,
1760 ssmR3FileTell,
1761 ssmR3FileSize,
1762 ssmR3FileClose,
1763 SSMSTRMOPS_VERSION
1764};
1765
1766
1767/**
1768 * Opens a file stream.
1769 *
1770 * @returns VBox status code.
1771 * @param pStrm The stream manager structure.
1772 * @param pszFilename The file to open or create.
1773 * @param fWrite Whether to open for writing or reading.
1774 * @param fChecksummed Whether the stream is to be checksummed while
1775 * written/read.
1776 * @param cBuffers The number of buffers.
1777 */
1778static int ssmR3StrmOpenFile(PSSMSTRM pStrm, const char *pszFilename, bool fWrite, bool fChecksummed, uint32_t cBuffers)
1779{
1780 int rc = ssmR3StrmInitInternal(pStrm, fChecksummed, cBuffers);
1781 if (RT_SUCCESS(rc))
1782 {
1783 uint32_t fFlags = fWrite
1784 ? RTFILE_O_READWRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_WRITE
1785 : RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE;
1786 RTFILE hFile;
1787 rc = RTFileOpen(&hFile, pszFilename, fFlags);
1788 if (RT_SUCCESS(rc))
1789 {
1790 pStrm->pOps = &g_ssmR3FileOps;
1791 pStrm->pvUser = (void *)(uintptr_t)hFile;
1792 pStrm->fWrite = fWrite;
1793 return VINF_SUCCESS;
1794 }
1795 }
1796
1797 ssmR3StrmDelete(pStrm);
1798 pStrm->rc = rc;
1799 return rc;
1800}
1801
1802
1803/**
1804 * Raise an error condition on the stream.
1805 *
1806 * @returns true if we raised the error condition, false if the stream already
1807 * had an error condition set.
1808 *
1809 * @param pStrm The stream handle.
1810 * @param rc The VBox error status code.
1811 *
1812 * @thread Any.
1813 */
1814DECLINLINE(bool) ssmR3StrmSetError(PSSMSTRM pStrm, int rc)
1815{
1816 Assert(RT_FAILURE_NP(rc));
1817 return ASMAtomicCmpXchgS32(&pStrm->rc, rc, VINF_SUCCESS);
1818}
1819
1820
1821/**
1822 * Puts a buffer into the free list.
1823 *
1824 * @param pStrm The stream handle.
1825 * @param pBuf The buffer.
1826 *
1827 * @thread The consumer.
1828 */
1829static void ssmR3StrmPutFreeBuf(PSSMSTRM pStrm, PSSMSTRMBUF pBuf)
1830{
1831 for (;;)
1832 {
1833 PSSMSTRMBUF pCurFreeHead = (PSSMSTRMBUF)ASMAtomicUoReadPtr((void * volatile *)&pStrm->pFree);
1834 ASMAtomicUoWritePtr((void * volatile *)&pBuf->pNext, pCurFreeHead);
1835 if (ASMAtomicCmpXchgPtr((void * volatile *)&pStrm->pFree, pBuf, pCurFreeHead))
1836 {
1837 int rc = RTSemEventSignal(pStrm->hEvtFree);
1838 AssertRC(rc);
1839 return;
1840 }
1841 }
1842}
1843
1844
1845/**
1846 * Gets a free buffer, waits for one if necessary.
1847 *
1848 * @returns Pointer to the buffer on success. NULL if we're terminating.
1849 * @param pStrm The stream handle.
1850 *
1851 * @thread The producer.
1852 */
1853static PSSMSTRMBUF ssmR3StrmGetFreeBuf(PSSMSTRM pStrm)
1854{
1855 for (;;)
1856 {
1857 PSSMSTRMBUF pMine = (PSSMSTRMBUF)ASMAtomicUoReadPtr((void * volatile *)&pStrm->pFree);
1858 if (!pMine)
1859 {
1860 if (pStrm->fTerminating)
1861 return NULL;
1862 if (RT_FAILURE(pStrm->rc))
1863 return NULL;
1864 if ( pStrm->fWrite
1865 && pStrm->hIoThread == NIL_RTTHREAD)
1866 {
1867 int rc = ssmR3StrmWriteBuffers(pStrm);
1868 if (RT_FAILURE(rc))
1869 return NULL;
1870 }
1871 int rc = RTSemEventWaitNoResume(pStrm->hEvtFree, 30000);
1872 if ( rc == VERR_SEM_DESTROYED
1873 || pStrm->fTerminating)
1874 return NULL;
1875 continue;
1876 }
1877
1878 if (ASMAtomicCmpXchgPtr((void * volatile *)&pStrm->pFree, pMine->pNext, pMine))
1879 {
1880 pMine->offStream = UINT64_MAX;
1881 pMine->cb = 0;
1882 pMine->pNext = NULL;
1883 pMine->fEndOfStream = false;
1884 return pMine;
1885 }
1886 }
1887}
1888
1889
1890/**
1891 * Puts a buffer onto the queue.
1892 *
1893 * @param pBuf The buffer.
1894 *
1895 * @thread The producer.
1896 */
1897static void ssmR3StrmPutBuf(PSSMSTRM pStrm, PSSMSTRMBUF pBuf)
1898{
1899 for (;;)
1900 {
1901 PSSMSTRMBUF pCurHead = (PSSMSTRMBUF)ASMAtomicUoReadPtr((void * volatile *)&pStrm->pHead);
1902 ASMAtomicUoWritePtr((void * volatile *)&pBuf->pNext, pCurHead);
1903 if (ASMAtomicCmpXchgPtr((void * volatile *)&pStrm->pHead, pBuf, pCurHead))
1904 {
1905 int rc = RTSemEventSignal(pStrm->hEvtHead);
1906 AssertRC(rc);
1907 return;
1908 }
1909 }
1910}
1911
1912
1913/**
1914 * Reverses the list.
1915 *
1916 * @returns The head of the reversed list.
1917 * @param pHead The head of the list to reverse.
1918 */
1919static PSSMSTRMBUF ssmR3StrmReverseList(PSSMSTRMBUF pHead)
1920{
1921 PSSMSTRMBUF pRevHead = NULL;
1922 while (pHead)
1923 {
1924 PSSMSTRMBUF pCur = pHead;
1925 pHead = pCur->pNext;
1926 pCur->pNext = pRevHead;
1927 pRevHead = pCur;
1928 }
1929 return pRevHead;
1930}
1931
1932
1933/**
1934 * Gets one buffer from the queue, will wait for one to become ready if
1935 * necessary.
1936 *
1937 * @returns Pointer to the buffer on success. NULL if we're terminating.
1938 * @param pBuf The buffer.
1939 *
1940 * @thread The consumer.
1941 */
1942static PSSMSTRMBUF ssmR3StrmGetBuf(PSSMSTRM pStrm)
1943{
1944 for (;;)
1945 {
1946 PSSMSTRMBUF pMine = pStrm->pPending;
1947 if (pMine)
1948 {
1949 pStrm->pPending = pMine->pNext;
1950 pMine->pNext = NULL;
1951 return pMine;
1952 }
1953
1954 pMine = (PSSMSTRMBUF)ASMAtomicXchgPtr((void * volatile *)&pStrm->pHead, NULL);
1955 if (pMine)
1956 pStrm->pPending = ssmR3StrmReverseList(pMine);
1957 else
1958 {
1959 if (pStrm->fTerminating)
1960 return NULL;
1961 if (RT_FAILURE(pStrm->rc))
1962 return NULL;
1963 if ( !pStrm->fWrite
1964 && pStrm->hIoThread == NIL_RTTHREAD)
1965 {
1966 int rc = ssmR3StrmReadMore(pStrm);
1967 if (RT_FAILURE(rc))
1968 return NULL;
1969 continue;
1970 }
1971
1972 int rc = RTSemEventWaitNoResume(pStrm->hEvtHead, 30000);
1973 if ( rc == VERR_SEM_DESTROYED
1974 || pStrm->fTerminating)
1975 return NULL;
1976 }
1977 }
1978}
1979
1980
1981/**
1982 * Flushes the current buffer (both write and read streams).
1983 *
1984 * @param pStrm The stream handle.
1985 */
1986static void ssmR3StrmFlushCurBuf(PSSMSTRM pStrm)
1987{
1988 if (pStrm->pCur)
1989 {
1990 PSSMSTRMBUF pBuf = pStrm->pCur;
1991 pStrm->pCur = NULL;
1992
1993 if (pStrm->fWrite)
1994 {
1995 uint32_t cb = pStrm->off;
1996 pBuf->cb = cb;
1997 pBuf->offStream = pStrm->offCurStream;
1998 if ( pStrm->fChecksummed
1999 && pStrm->offStreamCRC < cb)
2000 pStrm->u32StreamCRC = RTCrc32Process(pStrm->u32StreamCRC,
2001 &pBuf->abData[pStrm->offStreamCRC],
2002 cb - pStrm->offStreamCRC);
2003 pStrm->offCurStream += cb;
2004 pStrm->off = 0;
2005 pStrm->offStreamCRC = 0;
2006
2007 ssmR3StrmPutBuf(pStrm, pBuf);
2008 }
2009 else
2010 {
2011 uint32_t cb = pBuf->cb;
2012 if ( pStrm->fChecksummed
2013 && pStrm->offStreamCRC < cb)
2014 pStrm->u32StreamCRC = RTCrc32Process(pStrm->u32StreamCRC,
2015 &pBuf->abData[pStrm->offStreamCRC],
2016 cb - pStrm->offStreamCRC);
2017 pStrm->offCurStream += cb;
2018 pStrm->off = 0;
2019 pStrm->offStreamCRC = 0;
2020
2021 ssmR3StrmPutFreeBuf(pStrm, pBuf);
2022 }
2023 }
2024}
2025
2026
2027/**
2028 * Flush buffered data.
2029 *
2030 * @returns VBox status code. Returns VINF_EOF if we encounter a buffer with the
2031 * fEndOfStream indicator set.
2032 * @param pStrm The stream handle.
2033 *
2034 * @thread The producer thread.
2035 */
2036static int ssmR3StrmWriteBuffers(PSSMSTRM pStrm)
2037{
2038 Assert(pStrm->fWrite);
2039
2040 /*
2041 * Just return if the stream has a pending error condition.
2042 */
2043 int rc = pStrm->rc;
2044 if (RT_FAILURE(rc))
2045 return rc;
2046
2047 /*
2048 * Grab the pending list and write it out.
2049 */
2050 PSSMSTRMBUF pHead = (PSSMSTRMBUF)ASMAtomicXchgPtr((void * volatile *)&pStrm->pHead, NULL);
2051 if (!pHead)
2052 return VINF_SUCCESS;
2053 pHead = ssmR3StrmReverseList(pHead);
2054
2055 while (pHead)
2056 {
2057 /* pop */
2058 PSSMSTRMBUF pCur = pHead;
2059 pHead = pCur->pNext;
2060
2061 /* flush */
2062 int rc = pStrm->pOps->pfnWrite(pStrm->pvUser, pCur->offStream, &pCur->abData[0], pCur->cb);
2063 if ( RT_FAILURE(rc)
2064 && ssmR3StrmSetError(pStrm, rc))
2065 LogRel(("ssmR3StrmWriteBuffers: RTFileWriteAt failed with rc=%Rrc at offStream=%#llx\n", rc, pCur->offStream));
2066
2067 /* free */
2068 bool fEndOfStream = pCur->fEndOfStream;
2069 ssmR3StrmPutFreeBuf(pStrm, pCur);
2070 if (fEndOfStream)
2071 {
2072 Assert(!pHead);
2073 return VINF_EOF;
2074 }
2075 }
2076
2077 return pStrm->rc;
2078}
2079
2080
2081/**
2082 * Closes the stream after first flushing any pending write.
2083 *
2084 * @returns VBox status code.
2085 * @param pStrm The stream handle.
2086 */
2087static int ssmR3StrmClose(PSSMSTRM pStrm)
2088{
2089 /*
2090 * Flush, terminate the I/O thread, and close the stream.
2091 */
2092 if (pStrm->fWrite)
2093 {
2094 ssmR3StrmFlushCurBuf(pStrm);
2095 if (pStrm->hIoThread == NIL_RTTHREAD)
2096 ssmR3StrmWriteBuffers(pStrm);
2097 }
2098
2099 if (pStrm->hIoThread != NIL_RTTHREAD)
2100 ASMAtomicWriteBool(&pStrm->fTerminating, true);
2101
2102 int rc;
2103 if (pStrm->fWrite)
2104 {
2105 if (pStrm->hIoThread != NIL_RTTHREAD)
2106 {
2107 int rc2 = RTSemEventSignal(pStrm->hEvtFree);
2108 AssertLogRelRC(rc2);
2109 int rc3 = RTThreadWait(pStrm->hIoThread, RT_INDEFINITE_WAIT, NULL);
2110 AssertLogRelRC(rc3);
2111 pStrm->hIoThread = NIL_RTTHREAD;
2112 }
2113
2114 rc = pStrm->pOps->pfnClose(pStrm->pvUser);
2115 if (RT_FAILURE(rc))
2116 ssmR3StrmSetError(pStrm, rc);
2117 }
2118 else
2119 {
2120 rc = pStrm->pOps->pfnClose(pStrm->pvUser);
2121 if (RT_FAILURE(rc))
2122 ssmR3StrmSetError(pStrm, rc);
2123
2124 if (pStrm->hIoThread != NIL_RTTHREAD)
2125 {
2126 int rc2 = RTSemEventSignal(pStrm->hEvtFree);
2127 AssertLogRelRC(rc2);
2128 int rc3 = RTThreadWait(pStrm->hIoThread, RT_INDEFINITE_WAIT, NULL);
2129 AssertLogRelRC(rc3);
2130 pStrm->hIoThread = NIL_RTTHREAD;
2131 }
2132 }
2133
2134 pStrm->pOps = NULL;
2135 pStrm->pvUser = NULL;
2136
2137 rc = pStrm->rc;
2138 ssmR3StrmDelete(pStrm);
2139
2140 return rc;
2141}
2142
2143
2144/**
2145 * Stream output routine.
2146 *
2147 * @returns VBox status code.
2148 * @param pStrm The stream handle.
2149 * @param pvBuf What to write.
2150 * @param cbToWrite How much to write.
2151 *
2152 * @thread The producer in a write stream (never the I/O thread).
2153 */
2154static int ssmR3StrmWrite(PSSMSTRM pStrm, const void *pvBuf, size_t cbToWrite)
2155{
2156 AssertReturn(cbToWrite > 0, VINF_SUCCESS);
2157 Assert(pStrm->fWrite);
2158
2159 /*
2160 * Squeeze as much as possible into the current buffer.
2161 */
2162 PSSMSTRMBUF pBuf = pStrm->pCur;
2163 if (RT_LIKELY(pBuf))
2164 {
2165 uint32_t cbLeft = RT_SIZEOFMEMB(SSMSTRMBUF, abData) - pStrm->off;
2166 if (RT_LIKELY(cbLeft >= cbToWrite))
2167 {
2168 memcpy(&pBuf->abData[pStrm->off], pvBuf, cbToWrite);
2169 pStrm->off += (uint32_t)cbToWrite;
2170 return VINF_SUCCESS;
2171 }
2172
2173 if (cbLeft > 0)
2174 {
2175 memcpy(&pBuf->abData[pStrm->off], pvBuf, cbLeft);
2176 pStrm->off += cbLeft;
2177 cbToWrite -= cbLeft;
2178 pvBuf = (uint8_t const *)pvBuf + cbLeft;
2179 }
2180 Assert(pStrm->off == RT_SIZEOFMEMB(SSMSTRMBUF, abData));
2181 }
2182
2183 /*
2184 * Need one or more new buffers.
2185 */
2186 do
2187 {
2188 /*
2189 * Flush the current buffer and replace it with a new one.
2190 */
2191 ssmR3StrmFlushCurBuf(pStrm);
2192 pBuf = ssmR3StrmGetFreeBuf(pStrm);
2193 if (!pBuf)
2194 break;
2195 pStrm->pCur = pBuf;
2196 Assert(pStrm->off == 0);
2197
2198 /*
2199 * Copy data to the buffer.
2200 */
2201 uint32_t cbCopy = RT_SIZEOFMEMB(SSMSTRMBUF, abData);
2202 if (cbCopy > cbToWrite)
2203 cbCopy = (uint32_t)cbToWrite;
2204 memcpy(&pBuf->abData[0], pvBuf, cbCopy);
2205 pStrm->off = cbCopy;
2206 cbToWrite -= cbCopy;
2207 pvBuf = (uint8_t const *)pvBuf + cbCopy;
2208 } while (cbToWrite > 0);
2209
2210 return pStrm->rc;
2211}
2212
2213
2214/**
2215 * Reserves space in the current buffer so the caller can write directly to the
2216 * buffer instead of doing double buffering.
2217 *
2218 * @returns VBox status code
2219 * @param pStrm The stream handle.
2220 * @param cb The amount of buffer space to reserve.
2221 * @param ppb Where to return the pointer.
2222 */
2223static int ssmR3StrmReserveWriteBufferSpace(PSSMSTRM pStrm, size_t cb, uint8_t **ppb)
2224{
2225 Assert(pStrm->fWrite);
2226 Assert(RT_SIZEOFMEMB(SSMSTRMBUF, abData) / 4 >= cb);
2227
2228 /*
2229 * Check if there is room in the current buffer, it not flush it.
2230 */
2231 PSSMSTRMBUF pBuf = pStrm->pCur;
2232 if (pBuf)
2233 {
2234 uint32_t cbLeft = RT_SIZEOFMEMB(SSMSTRMBUF, abData) - pStrm->off;
2235 if (cbLeft >= cb)
2236 {
2237 *ppb = &pBuf->abData[pStrm->off];
2238 return VINF_SUCCESS;
2239 }
2240
2241 ssmR3StrmFlushCurBuf(pStrm);
2242 }
2243
2244 /*
2245 * Get a fresh buffer and return a pointer into it.
2246 */
2247 pBuf = ssmR3StrmGetFreeBuf(pStrm);
2248 if (pBuf)
2249 {
2250 pStrm->pCur = pBuf;
2251 Assert(pStrm->off == 0);
2252 *ppb = &pBuf->abData[0];
2253 }
2254 else
2255 *ppb = NULL; /* make gcc happy. */
2256 return pStrm->rc;
2257}
2258
2259
2260/**
2261 * Commits buffer space reserved by ssmR3StrmReserveWriteBufferSpace.
2262 *
2263 * @returns VBox status code.
2264 * @param pStrm The stream handle.
2265 * @param cb The amount of buffer space to commit. This can be less
2266 * that what was reserved initially.
2267 */
2268static int ssmR3StrmCommitWriteBufferSpace(PSSMSTRM pStrm, size_t cb)
2269{
2270 Assert(pStrm->pCur);
2271 Assert(pStrm->off + cb <= RT_SIZEOFMEMB(SSMSTRMBUF, abData));
2272 pStrm->off += cb;
2273 return VINF_SUCCESS;
2274}
2275
2276
2277/**
2278 * Marks the end of the stream.
2279 *
2280 * This will cause the I/O thread to quit waiting for more buffers.
2281 *
2282 * @returns VBox status code.
2283 * @param pStrm The stream handle.
2284 */
2285static int ssmR3StrmSetEnd(PSSMSTRM pStrm)
2286{
2287 Assert(pStrm->fWrite);
2288 PSSMSTRMBUF pBuf = pStrm->pCur;
2289 if (RT_UNLIKELY(!pStrm->pCur))
2290 {
2291 pBuf = ssmR3StrmGetFreeBuf(pStrm);
2292 if (!pBuf)
2293 return pStrm->rc;
2294 pStrm->pCur = pBuf;
2295 Assert(pStrm->off == 0);
2296 }
2297 pBuf->fEndOfStream = true;
2298 ssmR3StrmFlushCurBuf(pStrm);
2299 return VINF_SUCCESS;
2300}
2301
2302
2303/**
2304 * Read more from the stream.
2305 *
2306 * @returns VBox status code. VERR_EOF gets translated into VINF_EOF.
2307 * @param pStrm The stream handle.
2308 *
2309 * @thread The I/O thread when we got one, otherwise the stream user.
2310 */
2311static int ssmR3StrmReadMore(PSSMSTRM pStrm)
2312{
2313 int rc;
2314 Log6(("ssmR3StrmReadMore:\n"));
2315
2316 /*
2317 * Undo seek done by ssmR3StrmPeekAt.
2318 */
2319 if (pStrm->fNeedSeek)
2320 {
2321 rc = pStrm->pOps->pfnSeek(pStrm->pvUser, pStrm->offNeedSeekTo, RTFILE_SEEK_BEGIN, NULL);
2322 if (RT_FAILURE(rc))
2323 {
2324 if (ssmR3StrmSetError(pStrm, rc))
2325 LogRel(("ssmR3StrmReadMore: RTFileSeek(,%#llx,) failed with rc=%Rrc\n", pStrm->offNeedSeekTo, rc));
2326 return rc;
2327 }
2328 pStrm->fNeedSeek = false;
2329 pStrm->offNeedSeekTo = UINT64_MAX;
2330 }
2331
2332 /*
2333 * Get a free buffer and try fill it up.
2334 */
2335 PSSMSTRMBUF pBuf = ssmR3StrmGetFreeBuf(pStrm);
2336 if (!pBuf)
2337 return pStrm->rc;
2338
2339 pBuf->offStream = pStrm->pOps->pfnTell(pStrm->pvUser);
2340 size_t cbRead = sizeof(pBuf->abData);
2341 rc = pStrm->pOps->pfnRead(pStrm->pvUser, pBuf->offStream, &pBuf->abData[0], cbRead, &cbRead);
2342 if ( RT_SUCCESS(rc)
2343 && cbRead > 0)
2344 {
2345 pBuf->cb = (uint32_t)cbRead;
2346 pBuf->fEndOfStream = false;
2347 Log6(("ssmR3StrmReadMore: %#010llx %#x\n", pBuf->offStream, pBuf->cb));
2348 ssmR3StrmPutBuf(pStrm, pBuf);
2349 }
2350 else if ( ( RT_SUCCESS_NP(rc)
2351 && cbRead == 0)
2352 || rc == VERR_EOF)
2353 {
2354 pBuf->cb = 0;
2355 pBuf->fEndOfStream = true;
2356 Log6(("ssmR3StrmReadMore: %#010llx 0 EOF!\n", pBuf->offStream));
2357 ssmR3StrmPutBuf(pStrm, pBuf);
2358 rc = VINF_EOF;
2359 }
2360 else
2361 {
2362 Log6(("ssmR3StrmReadMore: %#010llx rc=%Rrc!\n", pBuf->offStream, rc));
2363 if (ssmR3StrmSetError(pStrm, rc))
2364 LogRel(("ssmR3StrmReadMore: RTFileRead(,,%#x,) -> %Rrc at offset %#llx\n",
2365 sizeof(pBuf->abData), rc, pBuf->offStream));
2366 ssmR3StrmPutFreeBuf(pStrm, pBuf);
2367 }
2368 return rc;
2369}
2370
2371
2372/**
2373 * Stream input routine.
2374 *
2375 * @returns VBox status code.
2376 * @param pStrm The stream handle.
2377 * @param pvBuf Where to put what we read.
2378 * @param cbToRead How much to read.
2379 */
2380static int ssmR3StrmRead(PSSMSTRM pStrm, void *pvBuf, size_t cbToRead)
2381{
2382 AssertReturn(cbToRead > 0, VINF_SUCCESS);
2383 Assert(!pStrm->fWrite);
2384
2385 /*
2386 * Read from the current buffer if we got one.
2387 */
2388 PSSMSTRMBUF pBuf = pStrm->pCur;
2389 if (RT_LIKELY(pBuf))
2390 {
2391 Assert(pStrm->off <= pBuf->cb);
2392 uint32_t cbLeft = pBuf->cb - pStrm->off;
2393 if (cbLeft >= cbToRead)
2394 {
2395 memcpy(pvBuf, &pBuf->abData[pStrm->off], cbToRead);
2396 pStrm->off += (uint32_t)cbToRead;
2397 Assert(pStrm->off <= pBuf->cb);
2398 return VINF_SUCCESS;
2399 }
2400 if (cbLeft)
2401 {
2402 memcpy(pvBuf, &pBuf->abData[pStrm->off], cbLeft);
2403 pStrm->off += cbLeft;
2404 cbToRead -= cbLeft;
2405 pvBuf = (uint8_t *)pvBuf + cbLeft;
2406 }
2407 else if (pBuf->fEndOfStream)
2408 return VERR_EOF;
2409 Assert(pStrm->off == pBuf->cb);
2410 }
2411
2412 /*
2413 * Get more buffers from the stream.
2414 */
2415 int rc = VINF_SUCCESS;
2416 do
2417 {
2418 /*
2419 * Check for EOF first - never flush the EOF buffer.
2420 */
2421 if ( pBuf
2422 && pBuf->fEndOfStream)
2423 return VERR_EOF;
2424
2425 /*
2426 * Flush the current buffer and get the next one.
2427 */
2428 ssmR3StrmFlushCurBuf(pStrm);
2429 PSSMSTRMBUF pBuf = ssmR3StrmGetBuf(pStrm);
2430 if (!pBuf)
2431 {
2432 rc = pStrm->rc;
2433 break;
2434 }
2435 pStrm->pCur = pBuf;
2436 Assert(pStrm->off == 0);
2437 Assert(pStrm->offCurStream == pBuf->offStream);
2438 if (!pBuf->cb)
2439 {
2440 Assert(pBuf->fEndOfStream);
2441 return VERR_EOF;
2442 }
2443
2444 /*
2445 * Read data from the buffer.
2446 */
2447 uint32_t cbCopy = pBuf->cb;
2448 if (cbCopy > cbToRead)
2449 cbCopy = (uint32_t)cbToRead;
2450 memcpy(pvBuf, &pBuf->abData[0], cbCopy);
2451 pStrm->off = cbCopy;
2452 cbToRead -= cbCopy;
2453 pvBuf = (uint8_t *)pvBuf + cbCopy;
2454 Assert(!pStrm->pCur || pStrm->off <= pStrm->pCur->cb);
2455 } while (cbToRead > 0);
2456
2457 return rc;
2458}
2459
2460
2461/**
2462 * Reads data from the stream but instead of copying it to some output buffer
2463 * the caller gets a pointer to into the current stream buffer.
2464 *
2465 * The returned pointer becomes invalid after the next stream operation!
2466 *
2467 * @returns Pointer to the read data residing in the stream buffer. NULL is
2468 * returned if the request amount of data isn't available in the
2469 * buffer. The caller must fall back on ssmR3StrmRead when this
2470 * happens.
2471 *
2472 * @param pStrm The stream handle.
2473 * @param cbToRead The number of bytes to tread.
2474 */
2475static uint8_t const *ssmR3StrmReadDirect(PSSMSTRM pStrm, size_t cbToRead)
2476{
2477 AssertReturn(cbToRead > 0, VINF_SUCCESS);
2478 Assert(!pStrm->fWrite);
2479
2480 /*
2481 * Too lazy to fetch more data for the odd case that we're
2482 * exactly at the boundrary between two buffers.
2483 */
2484 PSSMSTRMBUF pBuf = pStrm->pCur;
2485 if (RT_LIKELY(pBuf))
2486 {
2487 Assert(pStrm->off <= pBuf->cb);
2488 uint32_t cbLeft = pBuf->cb - pStrm->off;
2489 if (cbLeft >= cbToRead)
2490 {
2491 uint8_t const *pb = &pBuf->abData[pStrm->off];
2492 pStrm->off += (uint32_t)cbToRead;
2493 Assert(pStrm->off <= pBuf->cb);
2494 return pb;
2495 }
2496 }
2497 return NULL;
2498}
2499
2500
2501/**
2502 * Tell current stream position.
2503 *
2504 * @returns stream position.
2505 * @param pStrm The stream handle.
2506 */
2507static uint64_t ssmR3StrmTell(PSSMSTRM pStrm)
2508{
2509 return pStrm->offCurStream + pStrm->off;
2510}
2511
2512
2513/**
2514 * Gets the intermediate stream CRC up to the current position.
2515 *
2516 * @returns CRC.
2517 * @param pStrm The stream handle.
2518 */
2519static uint32_t ssmR3StrmCurCRC(PSSMSTRM pStrm)
2520{
2521 if (!pStrm->fChecksummed)
2522 return 0;
2523 if (pStrm->offStreamCRC < pStrm->off)
2524 {
2525 PSSMSTRMBUF pBuf = pStrm->pCur; Assert(pBuf);
2526 pStrm->u32StreamCRC = RTCrc32Process(pStrm->u32StreamCRC, &pBuf->abData[pStrm->offStreamCRC], pStrm->off - pStrm->offStreamCRC);
2527 pStrm->offStreamCRC = pStrm->off;
2528 }
2529 else
2530 Assert(pStrm->offStreamCRC == pStrm->off);
2531 return pStrm->u32StreamCRC;
2532}
2533
2534
2535/**
2536 * Gets the final stream CRC up to the current position.
2537 *
2538 * @returns CRC.
2539 * @param pStrm The stream handle.
2540 */
2541static uint32_t ssmR3StrmFinalCRC(PSSMSTRM pStrm)
2542{
2543 if (!pStrm->fChecksummed)
2544 return 0;
2545 return RTCrc32Finish(ssmR3StrmCurCRC(pStrm));
2546}
2547
2548
2549/**
2550 * Disables checksumming of the stream.
2551 *
2552 * @param pStrm The stream handle.
2553 */
2554static void ssmR3StrmDisableChecksumming(PSSMSTRM pStrm)
2555{
2556 pStrm->fChecksummed = false;
2557}
2558
2559
2560/**
2561 * Used by SSMR3Seek to position the stream at the new unit.
2562 *
2563 * @returns VBox stutus code.
2564 * @param pStrm The strem handle.
2565 * @param off The seek offset.
2566 * @param uMethod The seek method.
2567 * @param u32CurCRC The current CRC at the seek position.
2568 */
2569static int ssmR3StrmSeek(PSSMSTRM pStrm, int64_t off, uint32_t uMethod, uint32_t u32CurCRC)
2570{
2571 AssertReturn(!pStrm->fWrite, VERR_NOT_SUPPORTED);
2572 AssertReturn(pStrm->hIoThread == NIL_RTTHREAD, VERR_WRONG_ORDER);
2573
2574 uint64_t offStream;
2575 int rc = pStrm->pOps->pfnSeek(pStrm->pvUser, off, uMethod, &offStream);
2576 if (RT_SUCCESS(rc))
2577 {
2578 pStrm->fNeedSeek = false;
2579 pStrm->offNeedSeekTo= UINT64_MAX;
2580 pStrm->offCurStream = offStream;
2581 pStrm->off = 0;
2582 pStrm->offStreamCRC = 0;
2583 if (pStrm->fChecksummed)
2584 pStrm->u32StreamCRC = u32CurCRC;
2585 if (pStrm->pCur)
2586 {
2587 ssmR3StrmPutFreeBuf(pStrm, pStrm->pCur);
2588 pStrm->pCur = NULL;
2589 }
2590 }
2591 return rc;
2592}
2593
2594
2595/**
2596 * Skip some bytes in the stream.
2597 *
2598 * This is only used if someone didn't read all of their data in the V1 format,
2599 * so don't bother making this very efficient yet.
2600 *
2601 * @returns VBox status code.
2602 * @param pStrm The stream handle.
2603 * @param offDst The destination offset.
2604 */
2605static int ssmR3StrmSkipTo(PSSMSTRM pStrm, uint64_t offDst)
2606{
2607 /* dead simple - lazy bird! */
2608 for (;;)
2609 {
2610 uint64_t offCur = ssmR3StrmTell(pStrm);
2611 AssertReturn(offCur <= offDst, VERR_INTERNAL_ERROR_4);
2612 if (offCur == offDst)
2613 return VINF_SUCCESS;
2614
2615 uint8_t abBuf[4096];
2616 size_t cbToRead = RT_MIN(sizeof(abBuf), offDst - offCur);
2617 int rc = ssmR3StrmRead(pStrm, abBuf, cbToRead);
2618 if (RT_FAILURE(rc))
2619 return rc;
2620 }
2621}
2622
2623
2624/**
2625 * Get the size of the file.
2626 *
2627 * This does not work for non-file streams!
2628 *
2629 * @returns The file size, or UINT64_MAX if not a file stream.
2630 * @param pStrm The stream handle.
2631 */
2632static uint64_t ssmR3StrmGetSize(PSSMSTRM pStrm)
2633{
2634 uint64_t cbFile;
2635 int rc = pStrm->pOps->pfnSize(pStrm->pvUser, &cbFile);
2636 AssertLogRelRCReturn(rc, UINT64_MAX);
2637 return cbFile;
2638}
2639
2640
2641/***
2642 * Tests if the stream is a file stream or not.
2643 *
2644 * @returns true / false.
2645 * @param pStrm The stream handle.
2646 */
2647static bool ssmR3StrmIsFile(PSSMSTRM pStrm)
2648{
2649 return pStrm->pOps == &g_ssmR3FileOps;
2650}
2651
2652
2653/**
2654 * Peeks at data in a file stream without buffering anything (or upsetting
2655 * the buffering for that matter).
2656 *
2657 * @returns VBox status code.
2658 * @param pStrm The stream handle
2659 * @param off The offset to start peeking at. Use a negative offset to
2660 * peek at something relative to the end of the file.
2661 * @param pvBuf Output buffer.
2662 * @param cbToRead How much to read.
2663 * @param poff Where to optionally store the position. Useful when
2664 * using a negative off.
2665 *
2666 * @remarks Failures occuring while peeking will not be raised on the stream.
2667 */
2668static int ssmR3StrmPeekAt(PSSMSTRM pStrm, RTFOFF off, void *pvBuf, size_t cbToRead, uint64_t *poff)
2669{
2670 AssertReturn(!pStrm->fWrite, VERR_NOT_SUPPORTED);
2671 AssertReturn(pStrm->hIoThread == NIL_RTTHREAD, VERR_WRONG_ORDER);
2672
2673 if (!pStrm->fNeedSeek)
2674 {
2675 pStrm->fNeedSeek = true;
2676 pStrm->offNeedSeekTo = pStrm->offCurStream + (pStrm->pCur ? pStrm->pCur->cb : 0);
2677 }
2678 uint64_t offActual;
2679 int rc = pStrm->pOps->pfnSeek(pStrm->pvUser, off, off >= 0 ? RTFILE_SEEK_BEGIN : RTFILE_SEEK_END, &offActual);
2680 if (RT_SUCCESS(rc))
2681 {
2682 if (poff)
2683 *poff = offActual;
2684 rc = pStrm->pOps->pfnRead(pStrm->pvUser, offActual, pvBuf, cbToRead, NULL);
2685 }
2686
2687 return rc;
2688}
2689
2690
2691/**
2692 * The I/O thread.
2693 *
2694 * @returns VINF_SUCCESS (ignored).
2695 * @param hSelf The thread handle.
2696 * @param pvStrm The stream handle.
2697 */
2698static DECLCALLBACK(int) ssmR3StrmIoThread(RTTHREAD hSelf, void *pvStrm)
2699{
2700 PSSMSTRM pStrm = (PSSMSTRM)pvStrm;
2701 ASMAtomicWriteHandle(&pStrm->hIoThread, hSelf); /* paranoia */
2702
2703 Log(("ssmR3StrmIoThread: starts working\n"));
2704 if (pStrm->fWrite)
2705 {
2706 /*
2707 * Write until error or terminated.
2708 */
2709 for (;;)
2710 {
2711 int rc = ssmR3StrmWriteBuffers(pStrm);
2712 if ( RT_FAILURE(rc)
2713 || rc == VINF_EOF)
2714 {
2715 Log(("ssmR3StrmIoThread: quitting writing with rc=%Rrc.\n", rc));
2716 break;
2717 }
2718 if (RT_FAILURE(pStrm->rc))
2719 {
2720 Log(("ssmR3StrmIoThread: quitting writing with stream rc=%Rrc\n", pStrm->rc));
2721 break;
2722 }
2723
2724 if (ASMAtomicReadBool(&pStrm->fTerminating))
2725 {
2726 if (!ASMAtomicReadPtr((void * volatile *)&pStrm->pHead))
2727 {
2728 Log(("ssmR3StrmIoThread: quitting writing because of pending termination.\n"));
2729 break;
2730 }
2731 Log(("ssmR3StrmIoThread: postponing termination because of pending buffers.\n"));
2732 }
2733 else if (!ASMAtomicReadPtr((void * volatile *)&pStrm->pHead))
2734 {
2735 rc = RTSemEventWait(pStrm->hEvtHead, RT_INDEFINITE_WAIT);
2736 AssertLogRelRC(rc);
2737 }
2738 }
2739 }
2740 else
2741 {
2742 /*
2743 * Read until end of file, error or termination.
2744 */
2745 for (;;)
2746 {
2747 if (ASMAtomicReadBool(&pStrm->fTerminating))
2748 {
2749 Log(("ssmR3StrmIoThread: quitting reading because of pending termination.\n"));
2750 break;
2751 }
2752
2753 int rc = ssmR3StrmReadMore(pStrm);
2754 if ( RT_FAILURE(rc)
2755 || rc == VINF_EOF)
2756 {
2757 Log(("ssmR3StrmIoThread: quitting reading with rc=%Rrc\n", rc));
2758 break;
2759 }
2760 if (RT_FAILURE(pStrm->rc))
2761 {
2762 Log(("ssmR3StrmIoThread: quitting reading with stream rc=%Rrc\n", pStrm->rc));
2763 break;
2764 }
2765 }
2766 }
2767
2768 return VINF_SUCCESS;
2769}
2770
2771
2772/**
2773 * Starts the I/O thread for the specified stream.
2774 *
2775 * @param pStrm The stream handle.
2776 */
2777static void ssmR3StrmStartIoThread(PSSMSTRM pStrm)
2778{
2779 Assert(pStrm->hIoThread == NIL_RTTHREAD);
2780
2781 RTTHREAD hThread;
2782 int rc = RTThreadCreate(&hThread, ssmR3StrmIoThread, pStrm, 0, RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "SSM-IO");
2783 AssertRCReturnVoid(rc);
2784 ASMAtomicWriteHandle(&pStrm->hIoThread, hThread); /* paranoia */
2785}
2786
2787
2788/**
2789 * Works the progress calculation.
2790 *
2791 * @param pSSM The SSM handle.
2792 * @param cbAdvance Number of bytes to advance
2793 */
2794static void ssmR3Progress(PSSMHANDLE pSSM, uint64_t cbAdvance)
2795{
2796 /* Can't advance it beyond the estimated end of the unit. */
2797 uint64_t cbLeft = pSSM->offEstUnitEnd - pSSM->offEst;
2798 if (cbAdvance > cbLeft)
2799 cbAdvance = cbLeft;
2800 pSSM->offEst += cbAdvance;
2801
2802 /* uPercentPrepare% prepare, xx% exec, uPercentDone% done+crc */
2803 while ( pSSM->offEst >= pSSM->offEstProgress
2804 && pSSM->uPercent <= 100-pSSM->uPercentDone)
2805 {
2806 if (pSSM->pfnProgress)
2807 pSSM->pfnProgress(pSSM->pVM, pSSM->uPercent, pSSM->pvUser);
2808 pSSM->uPercent++;
2809 pSSM->offEstProgress = (pSSM->uPercent - pSSM->uPercentPrepare) * pSSM->cbEstTotal
2810 / (100 - pSSM->uPercentDone - pSSM->uPercentPrepare);
2811 }
2812}
2813
2814
2815/**
2816 * Makes the SSM operation cancellable or not (via SSMR3Cancel).
2817 *
2818 * @param pVM The VM handle.
2819 * @param pSSM The saved state handle. (SSMHANDLE::rc may be set.)
2820 * @param fCancellable The new state.
2821 */
2822static void ssmR3SetCancellable(PVM pVM, PSSMHANDLE pSSM, bool fCancellable)
2823{
2824 RTCritSectEnter(&pVM->ssm.s.CancelCritSect);
2825 if (fCancellable)
2826 {
2827 Assert(!pVM->ssm.s.pSSM);
2828 pVM->ssm.s.pSSM = pSSM;
2829 }
2830 else
2831 {
2832 if (pVM->ssm.s.pSSM == pSSM)
2833 pVM->ssm.s.pSSM = NULL;
2834
2835 uint32_t fCancelled = ASMAtomicUoReadU32(&pSSM->fCancelled);
2836 if ( fCancelled == SSMHANDLE_CANCELLED
2837 && RT_SUCCESS(pSSM->rc))
2838 pSSM->rc = VERR_SSM_CANCELLED;
2839 }
2840
2841 RTCritSectLeave(&pVM->ssm.s.CancelCritSect);
2842}
2843
2844
2845/**
2846 * Gets the host bit count of the saved state.
2847 *
2848 * Works for on both save and load handles.
2849 *
2850 * @returns 32 or 64.
2851 * @param pSSM The saved state handle.
2852 */
2853DECLINLINE(uint32_t) ssmR3GetHostBits(PSSMHANDLE pSSM)
2854{
2855 if (pSSM->enmOp >= SSMSTATE_LOAD_PREP)
2856 {
2857 uint32_t cBits = pSSM->u.Read.cHostBits;
2858 if (cBits)
2859 return cBits;
2860 }
2861 return HC_ARCH_BITS;
2862}
2863
2864
2865/**
2866 * Saved state origins on a host using 32-bit MSC?
2867 *
2868 * Works for on both save and load handles.
2869 *
2870 * @returns true/false.
2871 * @param pSSM The saved state handle.
2872 */
2873DECLINLINE(bool) ssmR3IsHostMsc32(PSSMHANDLE pSSM)
2874{
2875 if (pSSM->enmOp >= SSMSTATE_LOAD_PREP)
2876 return pSSM->u.Read.fIsHostMsc32;
2877 return SSM_HOST_IS_MSC_32;
2878}
2879
2880
2881/**
2882 * Finishes a data unit.
2883 * All buffers and compressor instances are flushed and destroyed.
2884 *
2885 * @returns VBox status.
2886 * @param pSSM The saved state handle.
2887 */
2888static int ssmR3DataWriteFinish(PSSMHANDLE pSSM)
2889{
2890 //Log2(("ssmR3DataWriteFinish: %#010llx start\n", ssmR3StrmTell(&pSSM->Strm)));
2891 int rc = ssmR3DataFlushBuffer(pSSM);
2892 if (RT_SUCCESS(rc))
2893 {
2894 pSSM->offUnit = UINT64_MAX;
2895 return VINF_SUCCESS;
2896 }
2897
2898 if (RT_SUCCESS(pSSM->rc))
2899 pSSM->rc = rc;
2900 Log2(("ssmR3DataWriteFinish: failure rc=%Rrc\n", rc));
2901 return rc;
2902}
2903
2904
2905/**
2906 * Begins writing the data of a data unit.
2907 *
2908 * Errors are signalled via pSSM->rc.
2909 *
2910 * @param pSSM The saved state handle.
2911 */
2912static void ssmR3DataWriteBegin(PSSMHANDLE pSSM)
2913{
2914 pSSM->offUnit = 0;
2915}
2916
2917
2918/**
2919 * Writes a record to the current data item in the saved state file.
2920 *
2921 * @returns VBox status code. Sets pSSM->rc on failure.
2922 * @param pSSM The saved state handle.
2923 * @param pvBuf The bits to write.
2924 * @param cbBuf The number of bytes to write.
2925 */
2926static int ssmR3DataWriteRaw(PSSMHANDLE pSSM, const void *pvBuf, size_t cbBuf)
2927{
2928 Log2(("ssmR3DataWriteRaw: %08llx|%08llx: pvBuf=%p cbBuf=%#x %.*Rhxs%s\n",
2929 ssmR3StrmTell(&pSSM->Strm), pSSM->offUnit, pvBuf, cbBuf, RT_MIN(cbBuf, SSM_LOG_BYTES), pvBuf, cbBuf > SSM_LOG_BYTES ? "..." : ""));
2930
2931 /*
2932 * Check that everything is fine.
2933 */
2934 if (RT_FAILURE(pSSM->rc))
2935 return pSSM->rc;
2936
2937 /*
2938 * Write the data item in 1MB chunks for progress indicator reasons.
2939 */
2940 while (cbBuf > 0)
2941 {
2942 size_t cbChunk = RT_MIN(cbBuf, _1M);
2943 int rc = ssmR3StrmWrite(&pSSM->Strm, pvBuf, cbChunk);
2944 if (RT_FAILURE(rc))
2945 return rc;
2946 pSSM->offUnit += cbChunk;
2947 cbBuf -= cbChunk;
2948 pvBuf = (char *)pvBuf + cbChunk;
2949 }
2950
2951 return VINF_SUCCESS;
2952}
2953
2954
2955/**
2956 * Writes a record header for the specified amount of data.
2957 *
2958 * @returns VBox status code. Sets pSSM->rc on failure.
2959 * @param pSSM The saved state handle
2960 * @param cb The amount of data.
2961 * @param u8TypeAndFlags The record type and flags.
2962 */
2963static int ssmR3DataWriteRecHdr(PSSMHANDLE pSSM, size_t cb, uint8_t u8TypeAndFlags)
2964{
2965 size_t cbHdr;
2966 uint8_t abHdr[8];
2967 abHdr[0] = u8TypeAndFlags;
2968 if (cb < 0x80)
2969 {
2970 cbHdr = 2;
2971 abHdr[1] = (uint8_t)cb;
2972 }
2973 else if (cb < 0x00000800)
2974 {
2975 cbHdr = 3;
2976 abHdr[1] = (uint8_t)(0xc0 | (cb >> 6));
2977 abHdr[2] = (uint8_t)(0x80 | (cb & 0x3f));
2978 }
2979 else if (cb < 0x00010000)
2980 {
2981 cbHdr = 4;
2982 abHdr[1] = (uint8_t)(0xe0 | (cb >> 12));
2983 abHdr[2] = (uint8_t)(0x80 | ((cb >> 6) & 0x3f));
2984 abHdr[3] = (uint8_t)(0x80 | (cb & 0x3f));
2985 }
2986 else if (cb < 0x00200000)
2987 {
2988 cbHdr = 5;
2989 abHdr[1] = (uint8_t)(0xf0 | (cb >> 18));
2990 abHdr[2] = (uint8_t)(0x80 | ((cb >> 12) & 0x3f));
2991 abHdr[3] = (uint8_t)(0x80 | ((cb >> 6) & 0x3f));
2992 abHdr[4] = (uint8_t)(0x80 | (cb & 0x3f));
2993 }
2994 else if (cb < 0x04000000)
2995 {
2996 cbHdr = 6;
2997 abHdr[1] = (uint8_t)(0xf8 | (cb >> 24));
2998 abHdr[2] = (uint8_t)(0x80 | ((cb >> 18) & 0x3f));
2999 abHdr[3] = (uint8_t)(0x80 | ((cb >> 12) & 0x3f));
3000 abHdr[4] = (uint8_t)(0x80 | ((cb >> 6) & 0x3f));
3001 abHdr[5] = (uint8_t)(0x80 | (cb & 0x3f));
3002 }
3003 else if (cb <= 0x7fffffff)
3004 {
3005 cbHdr = 7;
3006 abHdr[1] = (uint8_t)(0xfc | (cb >> 30));
3007 abHdr[2] = (uint8_t)(0x80 | ((cb >> 24) & 0x3f));
3008 abHdr[3] = (uint8_t)(0x80 | ((cb >> 18) & 0x3f));
3009 abHdr[4] = (uint8_t)(0x80 | ((cb >> 12) & 0x3f));
3010 abHdr[5] = (uint8_t)(0x80 | ((cb >> 6) & 0x3f));
3011 abHdr[6] = (uint8_t)(0x80 | (cb & 0x3f));
3012 }
3013 else
3014 AssertLogRelMsgFailedReturn(("cb=%#x\n", cb), pSSM->rc = VERR_INTERNAL_ERROR);
3015
3016 Log3(("ssmR3DataWriteRecHdr: %08llx|%08llx/%08x: Type=%02x fImportant=%RTbool cbHdr=%u\n",
3017 ssmR3StrmTell(&pSSM->Strm) + cbHdr, pSSM->offUnit + cbHdr, cb, u8TypeAndFlags & SSM_REC_TYPE_MASK, !!(u8TypeAndFlags & SSM_REC_FLAGS_IMPORTANT), cbHdr));
3018
3019 return ssmR3DataWriteRaw(pSSM, &abHdr[0], cbHdr);
3020}
3021
3022
3023/**
3024 * Worker that flushes the buffered data.
3025 *
3026 * @returns VBox status code. Will set pSSM->rc on error.
3027 * @param pSSM The saved state handle.
3028 */
3029static int ssmR3DataFlushBuffer(PSSMHANDLE pSSM)
3030{
3031 /*
3032 * Check how much there current is in the buffer.
3033 */
3034 uint32_t cb = pSSM->u.Write.offDataBuffer;
3035 if (!cb)
3036 return pSSM->rc;
3037 pSSM->u.Write.offDataBuffer = 0;
3038
3039 /*
3040 * Write a record header and then the data.
3041 * (No need for fancy optimizations here any longer since the stream is
3042 * fully buffered.)
3043 */
3044 int rc = ssmR3DataWriteRecHdr(pSSM, cb, SSM_REC_FLAGS_FIXED | SSM_REC_FLAGS_IMPORTANT | SSM_REC_TYPE_RAW);
3045 if (RT_SUCCESS(rc))
3046 rc = ssmR3DataWriteRaw(pSSM, pSSM->u.Write.abDataBuffer, cb);
3047 ssmR3Progress(pSSM, cb);
3048 return rc;
3049}
3050
3051
3052/**
3053 * ssmR3DataWrite worker that writes big stuff.
3054 *
3055 * @returns VBox status code
3056 * @param pSSM The saved state handle.
3057 * @param pvBuf The bits to write.
3058 * @param cbBuf The number of bytes to write.
3059 */
3060static int ssmR3DataWriteBig(PSSMHANDLE pSSM, const void *pvBuf, size_t cbBuf)
3061{
3062 int rc = ssmR3DataFlushBuffer(pSSM);
3063 if (RT_SUCCESS(rc))
3064 {
3065 /*
3066 * Split it up into compression blocks.
3067 */
3068 for (;;)
3069 {
3070 AssertCompile(SSM_ZIP_BLOCK_SIZE == PAGE_SIZE);
3071 if ( cbBuf >= SSM_ZIP_BLOCK_SIZE
3072 && ( ((uintptr_t)pvBuf & 0xf)
3073 || !ASMMemIsZeroPage(pvBuf))
3074 )
3075 {
3076 /*
3077 * Compress it.
3078 */
3079 AssertCompile(1 + 3 + 1 + SSM_ZIP_BLOCK_SIZE < 0x00010000);
3080 uint8_t *pb;
3081 rc = ssmR3StrmReserveWriteBufferSpace(&pSSM->Strm, 1 + 3 + 1 + SSM_ZIP_BLOCK_SIZE, &pb);
3082 if (RT_FAILURE(rc))
3083 break;
3084 size_t cbRec = SSM_ZIP_BLOCK_SIZE - (SSM_ZIP_BLOCK_SIZE / 16);
3085 rc = RTZipBlockCompress(RTZIPTYPE_LZF, RTZIPLEVEL_FAST, 0 /*fFlags*/,
3086 pvBuf, SSM_ZIP_BLOCK_SIZE,
3087 pb + 1 + 3 + 1, cbRec, &cbRec);
3088 if (RT_SUCCESS(rc))
3089 {
3090 pb[0] = SSM_REC_FLAGS_FIXED | SSM_REC_FLAGS_IMPORTANT | SSM_REC_TYPE_RAW_LZF;
3091 pb[4] = SSM_ZIP_BLOCK_SIZE / _1K;
3092 cbRec += 1;
3093 }
3094 else
3095 {
3096 pb[0] = SSM_REC_FLAGS_FIXED | SSM_REC_FLAGS_IMPORTANT | SSM_REC_TYPE_RAW;
3097 memcpy(&pb[4], pvBuf, SSM_ZIP_BLOCK_SIZE);
3098 cbRec = SSM_ZIP_BLOCK_SIZE;
3099 }
3100 pb[1] = (uint8_t)(0xe0 | ( cbRec >> 12));
3101 pb[2] = (uint8_t)(0x80 | ((cbRec >> 6) & 0x3f));
3102 pb[3] = (uint8_t)(0x80 | ( cbRec & 0x3f));
3103 cbRec += 1 + 3;
3104 rc = ssmR3StrmCommitWriteBufferSpace(&pSSM->Strm, cbRec);
3105 if (RT_FAILURE(rc))
3106 break;
3107
3108 pSSM->offUnit += cbRec;
3109 ssmR3Progress(pSSM, SSM_ZIP_BLOCK_SIZE);
3110
3111 /* advance */
3112 if (cbBuf == SSM_ZIP_BLOCK_SIZE)
3113 return VINF_SUCCESS;
3114 cbBuf -= SSM_ZIP_BLOCK_SIZE;
3115 pvBuf = (uint8_t const*)pvBuf + SSM_ZIP_BLOCK_SIZE;
3116 }
3117 else if (cbBuf >= SSM_ZIP_BLOCK_SIZE)
3118 {
3119 /*
3120 * Zero block.
3121 */
3122 uint8_t abRec[3];
3123 abRec[0] = SSM_REC_FLAGS_FIXED | SSM_REC_FLAGS_IMPORTANT | SSM_REC_TYPE_RAW_ZERO;
3124 abRec[1] = 1;
3125 abRec[2] = SSM_ZIP_BLOCK_SIZE / _1K;
3126 Log3(("ssmR3DataWriteBig: %08llx|%08llx/%08x: ZERO\n", ssmR3StrmTell(&pSSM->Strm) + 2, pSSM->offUnit + 2, 1));
3127 rc = ssmR3DataWriteRaw(pSSM, &abRec[0], sizeof(abRec));
3128 if (RT_FAILURE(rc))
3129 break;
3130
3131 /* advance */
3132 ssmR3Progress(pSSM, SSM_ZIP_BLOCK_SIZE);
3133 if (cbBuf == SSM_ZIP_BLOCK_SIZE)
3134 return VINF_SUCCESS;
3135 cbBuf -= SSM_ZIP_BLOCK_SIZE;
3136 pvBuf = (uint8_t const*)pvBuf + SSM_ZIP_BLOCK_SIZE;
3137 }
3138 else
3139 {
3140 /*
3141 * Less than one block left, store it the simple way.
3142 */
3143 rc = ssmR3DataWriteRecHdr(pSSM, cbBuf, SSM_REC_FLAGS_FIXED | SSM_REC_FLAGS_IMPORTANT | SSM_REC_TYPE_RAW);
3144 if (RT_SUCCESS(rc))
3145 rc = ssmR3DataWriteRaw(pSSM, pvBuf, cbBuf);
3146 ssmR3Progress(pSSM, cbBuf);
3147 break;
3148 }
3149 }
3150 }
3151 return rc;
3152}
3153
3154
3155/**
3156 * ssmR3DataWrite worker that is called when there isn't enough room in the
3157 * buffer for the current chunk of data.
3158 *
3159 * This will first flush the buffer and then add the new bits to it.
3160 *
3161 * @returns VBox status code
3162 * @param pSSM The saved state handle.
3163 * @param pvBuf The bits to write.
3164 * @param cbBuf The number of bytes to write.
3165 */
3166static int ssmR3DataWriteFlushAndBuffer(PSSMHANDLE pSSM, const void *pvBuf, size_t cbBuf)
3167{
3168 int rc = ssmR3DataFlushBuffer(pSSM);
3169 if (RT_SUCCESS(rc))
3170 {
3171 memcpy(&pSSM->u.Write.abDataBuffer[0], pvBuf, cbBuf);
3172 pSSM->u.Write.offDataBuffer = (uint32_t)cbBuf;
3173 }
3174 return rc;
3175}
3176
3177
3178/**
3179 * Writes data to the current data unit.
3180 *
3181 * This is an inlined wrapper that optimizes the small writes that so many of
3182 * the APIs make.
3183 *
3184 * @returns VBox status code
3185 * @param pSSM The saved state handle.
3186 * @param pvBuf The bits to write.
3187 * @param cbBuf The number of bytes to write.
3188 */
3189DECLINLINE(int) ssmR3DataWrite(PSSMHANDLE pSSM, const void *pvBuf, size_t cbBuf)
3190{
3191 if (cbBuf > sizeof(pSSM->u.Write.abDataBuffer) / 8)
3192 return ssmR3DataWriteBig(pSSM, pvBuf, cbBuf);
3193 if (!cbBuf)
3194 return VINF_SUCCESS;
3195
3196 uint32_t off = pSSM->u.Write.offDataBuffer;
3197 if (RT_UNLIKELY(cbBuf + off > sizeof(pSSM->u.Write.abDataBuffer)))
3198 return ssmR3DataWriteFlushAndBuffer(pSSM, pvBuf, cbBuf);
3199
3200 memcpy(&pSSM->u.Write.abDataBuffer[off], pvBuf, cbBuf);
3201 pSSM->u.Write.offDataBuffer = off + (uint32_t)cbBuf;
3202 return VINF_SUCCESS;
3203}
3204
3205
3206/**
3207 * Puts a structure.
3208 *
3209 * @returns VBox status code.
3210 * @param pSSM The saved state handle.
3211 * @param pvStruct The structure address.
3212 * @param paFields The array of structure fields descriptions.
3213 * The array must be terminated by a SSMFIELD_ENTRY_TERM().
3214 */
3215VMMR3DECL(int) SSMR3PutStruct(PSSMHANDLE pSSM, const void *pvStruct, PCSSMFIELD paFields)
3216{
3217 SSM_ASSERT_WRITEABLE_RET(pSSM);
3218 SSM_CHECK_CANCELLED_RET(pSSM);
3219 AssertPtr(pvStruct);
3220 AssertPtr(paFields);
3221
3222 /* begin marker. */
3223 int rc = SSMR3PutU32(pSSM, SSMR3STRUCT_BEGIN);
3224 if (RT_FAILURE(rc))
3225 return rc;
3226
3227 /* put the fields */
3228 for (PCSSMFIELD pCur = paFields;
3229 pCur->cb != UINT32_MAX && pCur->off != UINT32_MAX;
3230 pCur++)
3231 {
3232 uint8_t const *pbField = (uint8_t const *)pvStruct + pCur->off;
3233 switch ((uintptr_t)pCur->pfnGetPutOrTransformer)
3234 {
3235 case SSMFIELDTRANS_NO_TRANSFORMATION:
3236 rc = ssmR3DataWrite(pSSM, pbField, pCur->cb);
3237 break;
3238
3239 case SSMFIELDTRANS_GCPTR:
3240 AssertMsgReturn(pCur->cb == sizeof(RTGCPTR), ("%#x (%s)\n", pCur->cb, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
3241 rc = SSMR3PutGCPtr(pSSM, *(PRTGCPTR)pbField);
3242 break;
3243
3244 case SSMFIELDTRANS_GCPHYS:
3245 AssertMsgReturn(pCur->cb == sizeof(RTGCPHYS), ("%#x (%s)\n", pCur->cb, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
3246 rc = SSMR3PutGCPhys(pSSM, *(PRTGCPHYS)pbField);
3247 break;
3248
3249 case SSMFIELDTRANS_RCPTR:
3250 AssertMsgReturn(pCur->cb == sizeof(RTRCPTR), ("%#x (%s)\n", pCur->cb, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
3251 rc = SSMR3PutRCPtr(pSSM, *(PRTRCPTR)pbField);
3252 break;
3253
3254 case SSMFIELDTRANS_RCPTR_ARRAY:
3255 {
3256 uint32_t const cEntries = pCur->cb / sizeof(RTRCPTR);
3257 AssertMsgReturn(pCur->cb == cEntries * sizeof(RTRCPTR) && cEntries, ("%#x (%s)\n", pCur->cb, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
3258 rc = VINF_SUCCESS;
3259 for (uint32_t i = 0; i < cEntries && RT_SUCCESS(rc); i++)
3260 rc = SSMR3PutRCPtr(pSSM, ((PRTRCPTR)pbField)[i]);
3261 break;
3262 }
3263
3264 default:
3265 AssertMsgFailedReturn(("%#x\n", pCur->pfnGetPutOrTransformer), VERR_SSM_FIELD_COMPLEX);
3266 }
3267 if (RT_FAILURE(rc))
3268 return rc;
3269 }
3270
3271 /* end marker */
3272 return SSMR3PutU32(pSSM, SSMR3STRUCT_END);
3273}
3274
3275
3276/**
3277 * SSMR3PutStructEx helper that puts a HCPTR that is used as a NULL indicator.
3278 *
3279 * @returns VBox status code.
3280 *
3281 * @param pSSM The saved state handle.
3282 * @param pv The value to put.
3283 * @param fFlags SSMSTRUCT_FLAGS_XXX.
3284 */
3285DECLINLINE(int) ssmR3PutHCPtrNI(PSSMHANDLE pSSM, void *pv, uint32_t fFlags)
3286{
3287 int rc;
3288 if (fFlags & SSMSTRUCT_FLAGS_DONT_IGNORE)
3289 rc = ssmR3DataWrite(pSSM, &pv, sizeof(void *));
3290 else
3291 rc = SSMR3PutBool(pSSM, pv != NULL);
3292 return rc;
3293}
3294
3295
3296/**
3297 * Puts a structure, extended API.
3298 *
3299 * @returns VBox status code.
3300 * @param pSSM The saved state handle.
3301 * @param pvStruct The structure address.
3302 * @param cbStruct The size of the struct (use for validation only).
3303 * @param fFlags Combination of SSMSTRUCT_FLAGS_XXX defines.
3304 * @param paFields The array of structure fields descriptions. The
3305 * array must be terminated by a SSMFIELD_ENTRY_TERM().
3306 * @param pvUser User argument for any callbacks that paFields might
3307 * contain.
3308 */
3309VMMR3DECL(int) SSMR3PutStructEx(PSSMHANDLE pSSM, const void *pvStruct, size_t cbStruct,
3310 uint32_t fFlags, PCSSMFIELD paFields, void *pvUser)
3311{
3312 static uint8_t const s_abZero[_1K] = {0};
3313 int rc;
3314
3315 /*
3316 * Validation.
3317 */
3318 SSM_ASSERT_WRITEABLE_RET(pSSM);
3319 SSM_CHECK_CANCELLED_RET(pSSM);
3320 AssertMsgReturn(!(fFlags & ~SSMSTRUCT_FLAGS_VALID_MASK), ("%#x\n", fFlags), VERR_INVALID_PARAMETER);
3321 AssertPtr(pvStruct);
3322 AssertPtr(paFields);
3323
3324
3325 /*
3326 * Begin marker.
3327 */
3328 if (!(fFlags & SSMSTRUCT_FLAGS_NO_MARKERS))
3329 {
3330 rc = SSMR3PutU32(pSSM, SSMR3STRUCT_BEGIN);
3331 if (RT_FAILURE(rc))
3332 return rc;
3333 }
3334
3335 /*
3336 * Put the fields
3337 */
3338 uint32_t off = 0;
3339 for (PCSSMFIELD pCur = paFields;
3340 pCur->cb != UINT32_MAX && pCur->off != UINT32_MAX;
3341 pCur++)
3342 {
3343 uint32_t const offField = !SSMFIELDTRANS_IS_PADDING(pCur->pfnGetPutOrTransformer) || pCur->off != UINT32_MAX / 2
3344 ? pCur->off
3345 : off;
3346 uint32_t const cbField = !SSMFIELDTRANS_IS_PADDING(pCur->pfnGetPutOrTransformer)
3347 ? pCur->cb
3348 : RT_HIWORD(pCur->cb);
3349 AssertMsgReturn( cbField <= cbStruct
3350 && offField + cbField <= cbStruct
3351 && offField + cbField >= offField,
3352 ("off=%#x cb=%#x cbStruct=%#x (%s)\n", cbField, offField, cbStruct, pCur->pszName),
3353 VERR_SSM_FIELD_OUT_OF_BOUNDS);
3354 AssertMsgReturn( !(fFlags & SSMSTRUCT_FLAGS_FULL_STRUCT)
3355 || off == offField,
3356 ("off=%#x offField=%#x (%s)\n", off, offField, pCur->pszName),
3357 VERR_SSM_FIELD_NOT_CONSECUTIVE);
3358
3359 uint8_t const *pbField = (uint8_t const *)pvStruct + offField;
3360 switch ((uintptr_t)pCur->pfnGetPutOrTransformer)
3361 {
3362 case SSMFIELDTRANS_NO_TRANSFORMATION:
3363 rc = ssmR3DataWrite(pSSM, pbField, cbField);
3364 break;
3365
3366 case SSMFIELDTRANS_GCPTR:
3367 AssertMsgReturn(cbField == sizeof(RTGCPTR), ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
3368 rc = SSMR3PutGCPtr(pSSM, *(PRTGCPTR)pbField);
3369 break;
3370
3371 case SSMFIELDTRANS_GCPHYS:
3372 AssertMsgReturn(cbField == sizeof(RTGCPHYS), ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
3373 rc = SSMR3PutGCPhys(pSSM, *(PRTGCPHYS)pbField);
3374 break;
3375
3376 case SSMFIELDTRANS_RCPTR:
3377 AssertMsgReturn(cbField == sizeof(RTRCPTR), ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
3378 rc = SSMR3PutRCPtr(pSSM, *(PRTRCPTR)pbField);
3379 break;
3380
3381 case SSMFIELDTRANS_RCPTR_ARRAY:
3382 {
3383 uint32_t const cEntries = cbField / sizeof(RTRCPTR);
3384 AssertMsgReturn(cbField == cEntries * sizeof(RTRCPTR) && cEntries, ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
3385 rc = VINF_SUCCESS;
3386 for (uint32_t i = 0; i < cEntries && RT_SUCCESS(rc); i++)
3387 rc = SSMR3PutRCPtr(pSSM, ((PRTRCPTR)pbField)[i]);
3388 break;
3389 }
3390
3391 case SSMFIELDTRANS_HCPTR_NI:
3392 AssertMsgReturn(cbField == sizeof(void *), ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
3393 rc = ssmR3PutHCPtrNI(pSSM, *(void * const *)pbField, fFlags);
3394 break;
3395
3396 case SSMFIELDTRANS_HCPTR_NI_ARRAY:
3397 {
3398 uint32_t const cEntries = cbField / sizeof(void *);
3399 AssertMsgReturn(cbField == cEntries * sizeof(void *) && cEntries, ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
3400 rc = VINF_SUCCESS;
3401 for (uint32_t i = 0; i < cEntries && RT_SUCCESS(rc); i++)
3402 rc = ssmR3PutHCPtrNI(pSSM, ((void * const *)pbField)[i], fFlags);
3403 break;
3404 }
3405
3406 case SSMFIELDTRANS_IGNORE:
3407 if (fFlags & SSMSTRUCT_FLAGS_DONT_IGNORE)
3408 {
3409 uint32_t cb;
3410 for (uint32_t cbLeft = cbField; cbLeft > 0 && RT_SUCCESS(rc); cbLeft -= cb)
3411 {
3412 cb = RT_MIN(sizeof(s_abZero), cbLeft);
3413 rc = ssmR3DataWrite(pSSM, s_abZero, cb);
3414 }
3415 }
3416 break;
3417
3418 case SSMFIELDTRANS_IGN_RCPTR:
3419 AssertMsgReturn(cbField == sizeof(RTRCPTR), ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
3420 if (fFlags & SSMSTRUCT_FLAGS_DONT_IGNORE)
3421 rc = ssmR3DataWrite(pSSM, s_abZero, sizeof(RTRCPTR));
3422 break;
3423
3424 case SSMFIELDTRANS_IGN_HCPTR:
3425 AssertMsgReturn(cbField == sizeof(void *), ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
3426 if (fFlags & SSMSTRUCT_FLAGS_DONT_IGNORE)
3427 rc = ssmR3DataWrite(pSSM, s_abZero, sizeof(void *));
3428 break;
3429
3430 case SSMFIELDTRANS_PAD_HC:
3431 case SSMFIELDTRANS_PAD_HC32:
3432 case SSMFIELDTRANS_PAD_HC64:
3433 case SSMFIELDTRANS_PAD_HC_AUTO:
3434 case SSMFIELDTRANS_PAD_MSC32_AUTO:
3435 {
3436 uint32_t cb32 = RT_BYTE1(pCur->cb);
3437 uint32_t cb64 = RT_BYTE2(pCur->cb);
3438 uint32_t cbCtx = HC_ARCH_BITS == 64
3439 || ( (uintptr_t)pCur->pfnGetPutOrTransformer == SSMFIELDTRANS_PAD_MSC32_AUTO
3440 && !SSM_HOST_IS_MSC_32)
3441 ? cb64 : cb32;
3442 uint32_t cbSaved = ssmR3GetHostBits(pSSM) == 64
3443 || ( (uintptr_t)pCur->pfnGetPutOrTransformer == SSMFIELDTRANS_PAD_MSC32_AUTO
3444 && !ssmR3IsHostMsc32(pSSM))
3445 ? cb64 : cb32;
3446 AssertMsgReturn( cbField == cbCtx
3447 && ( ( pCur->off == UINT32_MAX / 2
3448 && ( cbField == 0
3449 || (uintptr_t)pCur->pfnGetPutOrTransformer == SSMFIELDTRANS_PAD_HC_AUTO
3450 || (uintptr_t)pCur->pfnGetPutOrTransformer == SSMFIELDTRANS_PAD_MSC32_AUTO
3451 )
3452 )
3453 || (pCur->off != UINT32_MAX / 2 && cbField != 0)
3454 )
3455 , ("cbField=%#x cb32=%#x cb64=%#x HC_ARCH_BITS=%u cbCtx=%#x cbSaved=%#x off=%#x\n",
3456 cbField, cb32, cb64, HC_ARCH_BITS, cbCtx, cbSaved, pCur->off),
3457 VERR_SSM_FIELD_INVALID_PADDING_SIZE);
3458 if (fFlags & SSMSTRUCT_FLAGS_DONT_IGNORE)
3459 {
3460 uint32_t cb;
3461 for (uint32_t cbLeft = cbSaved; cbLeft > 0 && RT_SUCCESS(rc); cbLeft -= cb)
3462 {
3463 cb = RT_MIN(sizeof(s_abZero), cbLeft);
3464 rc = ssmR3DataWrite(pSSM, s_abZero, cb);
3465 }
3466 }
3467 break;
3468 }
3469
3470 default:
3471 AssertPtrReturn(pCur->pfnGetPutOrTransformer, VERR_SSM_FIELD_INVALID_CALLBACK);
3472 rc = pCur->pfnGetPutOrTransformer(pSSM, pCur, (void *)pvStruct, fFlags, false /*fGetOrPut*/, pvUser);
3473 break;
3474 }
3475 if (RT_FAILURE(rc))
3476 return rc;
3477
3478 off = offField + cbField;
3479 }
3480 AssertMsgReturn( !(fFlags & SSMSTRUCT_FLAGS_FULL_STRUCT)
3481 || off == cbStruct,
3482 ("off=%#x cbStruct=%#x\n", off, cbStruct),
3483 VERR_SSM_FIELD_NOT_CONSECUTIVE);
3484
3485 /*
3486 * End marker
3487 */
3488 if (!(fFlags & SSMSTRUCT_FLAGS_NO_MARKERS))
3489 {
3490 rc = SSMR3PutU32(pSSM, SSMR3STRUCT_END);
3491 if (RT_FAILURE(rc))
3492 return rc;
3493 }
3494
3495 return VINF_SUCCESS;
3496}
3497
3498
3499/**
3500 * Saves a boolean item to the current data unit.
3501 *
3502 * @returns VBox status.
3503 * @param pSSM The saved state handle.
3504 * @param fBool Item to save.
3505 */
3506VMMR3DECL(int) SSMR3PutBool(PSSMHANDLE pSSM, bool fBool)
3507{
3508 SSM_ASSERT_WRITEABLE_RET(pSSM);
3509 SSM_CHECK_CANCELLED_RET(pSSM);
3510 uint8_t u8 = fBool; /* enforce 1 byte size */
3511 return ssmR3DataWrite(pSSM, &u8, sizeof(u8));
3512}
3513
3514
3515/**
3516 * Saves a 8-bit unsigned integer item to the current data unit.
3517 *
3518 * @returns VBox status.
3519 * @param pSSM The saved state handle.
3520 * @param u8 Item to save.
3521 */
3522VMMR3DECL(int) SSMR3PutU8(PSSMHANDLE pSSM, uint8_t u8)
3523{
3524 SSM_ASSERT_WRITEABLE_RET(pSSM);
3525 SSM_CHECK_CANCELLED_RET(pSSM);
3526 return ssmR3DataWrite(pSSM, &u8, sizeof(u8));
3527}
3528
3529
3530/**
3531 * Saves a 8-bit signed integer item to the current data unit.
3532 *
3533 * @returns VBox status.
3534 * @param pSSM The saved state handle.
3535 * @param i8 Item to save.
3536 */
3537VMMR3DECL(int) SSMR3PutS8(PSSMHANDLE pSSM, int8_t i8)
3538{
3539 SSM_ASSERT_WRITEABLE_RET(pSSM);
3540 SSM_CHECK_CANCELLED_RET(pSSM);
3541 return ssmR3DataWrite(pSSM, &i8, sizeof(i8));
3542}
3543
3544
3545/**
3546 * Saves a 16-bit unsigned integer item to the current data unit.
3547 *
3548 * @returns VBox status.
3549 * @param pSSM The saved state handle.
3550 * @param u16 Item to save.
3551 */
3552VMMR3DECL(int) SSMR3PutU16(PSSMHANDLE pSSM, uint16_t u16)
3553{
3554 SSM_ASSERT_WRITEABLE_RET(pSSM);
3555 SSM_CHECK_CANCELLED_RET(pSSM);
3556 return ssmR3DataWrite(pSSM, &u16, sizeof(u16));
3557}
3558
3559
3560/**
3561 * Saves a 16-bit signed integer item to the current data unit.
3562 *
3563 * @returns VBox status.
3564 * @param pSSM The saved state handle.
3565 * @param i16 Item to save.
3566 */
3567VMMR3DECL(int) SSMR3PutS16(PSSMHANDLE pSSM, int16_t i16)
3568{
3569 SSM_ASSERT_WRITEABLE_RET(pSSM);
3570 SSM_CHECK_CANCELLED_RET(pSSM);
3571 return ssmR3DataWrite(pSSM, &i16, sizeof(i16));
3572}
3573
3574
3575/**
3576 * Saves a 32-bit unsigned integer item to the current data unit.
3577 *
3578 * @returns VBox status.
3579 * @param pSSM The saved state handle.
3580 * @param u32 Item to save.
3581 */
3582VMMR3DECL(int) SSMR3PutU32(PSSMHANDLE pSSM, uint32_t u32)
3583{
3584 SSM_ASSERT_WRITEABLE_RET(pSSM);
3585 SSM_CHECK_CANCELLED_RET(pSSM);
3586 return ssmR3DataWrite(pSSM, &u32, sizeof(u32));
3587}
3588
3589
3590/**
3591 * Saves a 32-bit signed integer item to the current data unit.
3592 *
3593 * @returns VBox status.
3594 * @param pSSM The saved state handle.
3595 * @param i32 Item to save.
3596 */
3597VMMR3DECL(int) SSMR3PutS32(PSSMHANDLE pSSM, int32_t i32)
3598{
3599 SSM_ASSERT_WRITEABLE_RET(pSSM);
3600 SSM_CHECK_CANCELLED_RET(pSSM);
3601 return ssmR3DataWrite(pSSM, &i32, sizeof(i32));
3602}
3603
3604
3605/**
3606 * Saves a 64-bit unsigned integer item to the current data unit.
3607 *
3608 * @returns VBox status.
3609 * @param pSSM The saved state handle.
3610 * @param u64 Item to save.
3611 */
3612VMMR3DECL(int) SSMR3PutU64(PSSMHANDLE pSSM, uint64_t u64)
3613{
3614 SSM_ASSERT_WRITEABLE_RET(pSSM);
3615 SSM_CHECK_CANCELLED_RET(pSSM);
3616 return ssmR3DataWrite(pSSM, &u64, sizeof(u64));
3617}
3618
3619
3620/**
3621 * Saves a 64-bit signed integer item to the current data unit.
3622 *
3623 * @returns VBox status.
3624 * @param pSSM The saved state handle.
3625 * @param i64 Item to save.
3626 */
3627VMMR3DECL(int) SSMR3PutS64(PSSMHANDLE pSSM, int64_t i64)
3628{
3629 SSM_ASSERT_WRITEABLE_RET(pSSM);
3630 SSM_CHECK_CANCELLED_RET(pSSM);
3631 return ssmR3DataWrite(pSSM, &i64, sizeof(i64));
3632}
3633
3634
3635/**
3636 * Saves a 128-bit unsigned integer item to the current data unit.
3637 *
3638 * @returns VBox status.
3639 * @param pSSM The saved state handle.
3640 * @param u128 Item to save.
3641 */
3642VMMR3DECL(int) SSMR3PutU128(PSSMHANDLE pSSM, uint128_t u128)
3643{
3644 SSM_ASSERT_WRITEABLE_RET(pSSM);
3645 SSM_CHECK_CANCELLED_RET(pSSM);
3646 return ssmR3DataWrite(pSSM, &u128, sizeof(u128));
3647}
3648
3649
3650/**
3651 * Saves a 128-bit signed integer item to the current data unit.
3652 *
3653 * @returns VBox status.
3654 * @param pSSM The saved state handle.
3655 * @param i128 Item to save.
3656 */
3657VMMR3DECL(int) SSMR3PutS128(PSSMHANDLE pSSM, int128_t i128)
3658{
3659 SSM_ASSERT_WRITEABLE_RET(pSSM);
3660 SSM_CHECK_CANCELLED_RET(pSSM);
3661 return ssmR3DataWrite(pSSM, &i128, sizeof(i128));
3662}
3663
3664
3665/**
3666 * Saves a VBox unsigned integer item to the current data unit.
3667 *
3668 * @returns VBox status.
3669 * @param pSSM The saved state handle.
3670 * @param u Item to save.
3671 */
3672VMMR3DECL(int) SSMR3PutUInt(PSSMHANDLE pSSM, RTUINT u)
3673{
3674 SSM_ASSERT_WRITEABLE_RET(pSSM);
3675 SSM_CHECK_CANCELLED_RET(pSSM);
3676 return ssmR3DataWrite(pSSM, &u, sizeof(u));
3677}
3678
3679
3680/**
3681 * Saves a VBox signed integer item to the current data unit.
3682 *
3683 * @returns VBox status.
3684 * @param pSSM The saved state handle.
3685 * @param i Item to save.
3686 */
3687VMMR3DECL(int) SSMR3PutSInt(PSSMHANDLE pSSM, RTINT i)
3688{
3689 SSM_ASSERT_WRITEABLE_RET(pSSM);
3690 SSM_CHECK_CANCELLED_RET(pSSM);
3691 return ssmR3DataWrite(pSSM, &i, sizeof(i));
3692}
3693
3694
3695/**
3696 * Saves a GC natural unsigned integer item to the current data unit.
3697 *
3698 * @returns VBox status.
3699 * @param pSSM The saved state handle.
3700 * @param u Item to save.
3701 *
3702 * @deprecated Silly type, don't use it.
3703 */
3704VMMR3DECL(int) SSMR3PutGCUInt(PSSMHANDLE pSSM, RTGCUINT u)
3705{
3706 SSM_ASSERT_WRITEABLE_RET(pSSM);
3707 SSM_CHECK_CANCELLED_RET(pSSM);
3708 return ssmR3DataWrite(pSSM, &u, sizeof(u));
3709}
3710
3711
3712/**
3713 * Saves a GC unsigned integer register item to the current data unit.
3714 *
3715 * @returns VBox status.
3716 * @param pSSM The saved state handle.
3717 * @param u Item to save.
3718 */
3719VMMR3DECL(int) SSMR3PutGCUIntReg(PSSMHANDLE pSSM, RTGCUINTREG u)
3720{
3721 SSM_ASSERT_WRITEABLE_RET(pSSM);
3722 SSM_CHECK_CANCELLED_RET(pSSM);
3723 return ssmR3DataWrite(pSSM, &u, sizeof(u));
3724}
3725
3726
3727/**
3728 * Saves a 32 bits GC physical address item to the current data unit.
3729 *
3730 * @returns VBox status.
3731 * @param pSSM The saved state handle.
3732 * @param GCPhys The item to save
3733 */
3734VMMR3DECL(int) SSMR3PutGCPhys32(PSSMHANDLE pSSM, RTGCPHYS32 GCPhys)
3735{
3736 SSM_ASSERT_WRITEABLE_RET(pSSM);
3737 SSM_CHECK_CANCELLED_RET(pSSM);
3738 return ssmR3DataWrite(pSSM, &GCPhys, sizeof(GCPhys));
3739}
3740
3741
3742/**
3743 * Saves a 64 bits GC physical address item to the current data unit.
3744 *
3745 * @returns VBox status.
3746 * @param pSSM The saved state handle.
3747 * @param GCPhys The item to save
3748 */
3749VMMR3DECL(int) SSMR3PutGCPhys64(PSSMHANDLE pSSM, RTGCPHYS64 GCPhys)
3750{
3751 SSM_ASSERT_WRITEABLE_RET(pSSM);
3752 SSM_CHECK_CANCELLED_RET(pSSM);
3753 return ssmR3DataWrite(pSSM, &GCPhys, sizeof(GCPhys));
3754}
3755
3756
3757/**
3758 * Saves a GC physical address item to the current data unit.
3759 *
3760 * @returns VBox status.
3761 * @param pSSM The saved state handle.
3762 * @param GCPhys The item to save
3763 */
3764VMMR3DECL(int) SSMR3PutGCPhys(PSSMHANDLE pSSM, RTGCPHYS GCPhys)
3765{
3766 SSM_ASSERT_WRITEABLE_RET(pSSM);
3767 SSM_CHECK_CANCELLED_RET(pSSM);
3768 return ssmR3DataWrite(pSSM, &GCPhys, sizeof(GCPhys));
3769}
3770
3771
3772/**
3773 * Saves a GC virtual address item to the current data unit.
3774 *
3775 * @returns VBox status.
3776 * @param pSSM The saved state handle.
3777 * @param GCPtr The item to save.
3778 */
3779VMMR3DECL(int) SSMR3PutGCPtr(PSSMHANDLE pSSM, RTGCPTR GCPtr)
3780{
3781 SSM_ASSERT_WRITEABLE_RET(pSSM);
3782 SSM_CHECK_CANCELLED_RET(pSSM);
3783 return ssmR3DataWrite(pSSM, &GCPtr, sizeof(GCPtr));
3784}
3785
3786
3787/**
3788 * Saves an RC virtual address item to the current data unit.
3789 *
3790 * @returns VBox status.
3791 * @param pSSM The saved state handle.
3792 * @param RCPtr The item to save.
3793 */
3794VMMR3DECL(int) SSMR3PutRCPtr(PSSMHANDLE pSSM, RTRCPTR RCPtr)
3795{
3796 SSM_ASSERT_WRITEABLE_RET(pSSM);
3797 SSM_CHECK_CANCELLED_RET(pSSM);
3798 return ssmR3DataWrite(pSSM, &RCPtr, sizeof(RCPtr));
3799}
3800
3801
3802/**
3803 * Saves a GC virtual address (represented as an unsigned integer) item to the current data unit.
3804 *
3805 * @returns VBox status.
3806 * @param pSSM The saved state handle.
3807 * @param GCPtr The item to save.
3808 */
3809VMMR3DECL(int) SSMR3PutGCUIntPtr(PSSMHANDLE pSSM, RTGCUINTPTR GCPtr)
3810{
3811 SSM_ASSERT_WRITEABLE_RET(pSSM);
3812 SSM_CHECK_CANCELLED_RET(pSSM);
3813 return ssmR3DataWrite(pSSM, &GCPtr, sizeof(GCPtr));
3814}
3815
3816
3817/**
3818 * Saves a I/O port address item to the current data unit.
3819 *
3820 * @returns VBox status.
3821 * @param pSSM The saved state handle.
3822 * @param IOPort The item to save.
3823 */
3824VMMR3DECL(int) SSMR3PutIOPort(PSSMHANDLE pSSM, RTIOPORT IOPort)
3825{
3826 SSM_ASSERT_WRITEABLE_RET(pSSM);
3827 SSM_CHECK_CANCELLED_RET(pSSM);
3828 return ssmR3DataWrite(pSSM, &IOPort, sizeof(IOPort));
3829}
3830
3831
3832/**
3833 * Saves a selector item to the current data unit.
3834 *
3835 * @returns VBox status.
3836 * @param pSSM The saved state handle.
3837 * @param Sel The item to save.
3838 */
3839VMMR3DECL(int) SSMR3PutSel(PSSMHANDLE pSSM, RTSEL Sel)
3840{
3841 SSM_ASSERT_WRITEABLE_RET(pSSM);
3842 SSM_CHECK_CANCELLED_RET(pSSM);
3843 return ssmR3DataWrite(pSSM, &Sel, sizeof(Sel));
3844}
3845
3846
3847/**
3848 * Saves a memory item to the current data unit.
3849 *
3850 * @returns VBox status.
3851 * @param pSSM The saved state handle.
3852 * @param pv Item to save.
3853 * @param cb Size of the item.
3854 */
3855VMMR3DECL(int) SSMR3PutMem(PSSMHANDLE pSSM, const void *pv, size_t cb)
3856{
3857 SSM_ASSERT_WRITEABLE_RET(pSSM);
3858 SSM_CHECK_CANCELLED_RET(pSSM);
3859 return ssmR3DataWrite(pSSM, pv, cb);
3860}
3861
3862
3863/**
3864 * Saves a zero terminated string item to the current data unit.
3865 *
3866 * @returns VBox status.
3867 * @param pSSM The saved state handle.
3868 * @param psz Item to save.
3869 */
3870VMMR3DECL(int) SSMR3PutStrZ(PSSMHANDLE pSSM, const char *psz)
3871{
3872 SSM_ASSERT_WRITEABLE_RET(pSSM);
3873 SSM_CHECK_CANCELLED_RET(pSSM);
3874
3875 size_t cch = strlen(psz);
3876 if (cch > _1M)
3877 {
3878 AssertMsgFailed(("a %d byte long string, what's this!?!\n"));
3879 return VERR_TOO_MUCH_DATA;
3880 }
3881 uint32_t u32 = (uint32_t)cch;
3882 int rc = ssmR3DataWrite(pSSM, &u32, sizeof(u32));
3883 if (rc)
3884 return rc;
3885 return ssmR3DataWrite(pSSM, psz, cch);
3886}
3887
3888
3889/**
3890 * Worker for SSMR3LiveDone and SSMR3Save that closes the handle and deletes the
3891 * saved state file on failure.
3892 *
3893 * @returns VBox status code (pSSM->rc).
3894 * @param pVM The VM handle.
3895 * @param pSSM The saved state handle.
3896 */
3897static int ssmR3SaveDoClose(PVM pVM, PSSMHANDLE pSSM)
3898{
3899 VM_ASSERT_EMT0(pVM);
3900
3901 /*
3902 * Make it non-cancellable, close the stream and delete the file on failure.
3903 */
3904 ssmR3SetCancellable(pVM, pSSM, false);
3905 int rc = ssmR3StrmClose(&pSSM->Strm);
3906 if (RT_SUCCESS(rc))
3907 rc = pSSM->rc;
3908 if (RT_SUCCESS(rc))
3909 {
3910 if (pSSM->pfnProgress)
3911 pSSM->pfnProgress(pVM, 100, pSSM->pvUser);
3912 LogRel(("SSM: Successfully saved the VM state to '%s'\n",
3913 pSSM->pszFilename ? pSSM->pszFilename : "<remote-machine>"));
3914 }
3915 else
3916 {
3917 if (pSSM->pszFilename)
3918 {
3919 int rc2 = RTFileDelete(pSSM->pszFilename);
3920 AssertRC(rc2);
3921 if (RT_SUCCESS(rc2))
3922 LogRel(("SSM: Failed to save the VM state to '%s' (file deleted): %Rrc\n",
3923 pSSM->pszFilename, rc));
3924 else
3925 LogRel(("SSM: Failed to save the VM state to '%s' (file deletion failed, rc2=%Rrc): %Rrc\n",
3926 pSSM->pszFilename, rc2, rc));
3927 }
3928 else
3929 LogRel(("SSM: Failed to save the VM state.\n"));
3930 }
3931
3932 /*
3933 * Trash the handle before freeing it.
3934 */
3935 ASMAtomicWriteU32(&pSSM->fCancelled, 0);
3936 pSSM->pVM = NULL;
3937 pSSM->enmAfter = SSMAFTER_INVALID;
3938 pSSM->enmOp = SSMSTATE_INVALID;
3939 RTMemFree(pSSM);
3940
3941 return rc;
3942}
3943
3944
3945/**
3946 * Closes the SSM handle.
3947 *
3948 * This must always be called on a handled returned by SSMR3LiveSave.
3949 *
3950 * @returns VBox status.
3951 *
3952 * @param pSSM The SSM handle returned by SSMR3LiveSave.
3953 *
3954 * @thread EMT(0).
3955 */
3956VMMR3_INT_DECL(int) SSMR3LiveDone(PSSMHANDLE pSSM)
3957{
3958 LogFlow(("SSMR3LiveDone: pSSM=%p\n", pSSM));
3959
3960 /*
3961 * Validate input.
3962 */
3963 AssertPtrReturn(pSSM, VERR_INVALID_POINTER);
3964 PVM pVM = pSSM->pVM;
3965 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3966 VM_ASSERT_EMT0(pVM);
3967 AssertMsgReturn( pSSM->enmAfter == SSMAFTER_DESTROY
3968 || pSSM->enmAfter == SSMAFTER_CONTINUE
3969 || pSSM->enmAfter == SSMAFTER_MIGRATE,
3970 ("%d\n", pSSM->enmAfter),
3971 VERR_INVALID_PARAMETER);
3972 AssertMsgReturn( pSSM->enmOp >= SSMSTATE_LIVE_PREP
3973 && pSSM->enmOp <= SSMSTATE_SAVE_DONE,
3974 ("%d\n", pSSM->enmOp), VERR_INVALID_STATE);
3975
3976 /*
3977 * Join paths with SSMR3Save again.
3978 */
3979 return ssmR3SaveDoClose(pVM, pSSM);
3980}
3981
3982
3983/**
3984 * Do the pfnSaveDone run.
3985 *
3986 * @returns VBox status code (pSSM->rc).
3987 * @param pVM The VM handle.
3988 * @param pSSM The saved state handle.
3989 */
3990static int ssmR3SaveDoDoneRun(PVM pVM, PSSMHANDLE pSSM)
3991{
3992 VM_ASSERT_EMT0(pVM);
3993
3994 /*
3995 * Do the done run.
3996 */
3997 pSSM->enmOp = SSMSTATE_SAVE_DONE;
3998 for (PSSMUNIT pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
3999 {
4000 if ( pUnit->u.Common.pfnSaveDone
4001 && ( pUnit->fCalled
4002 || (!pUnit->u.Common.pfnSavePrep && !pUnit->u.Common.pfnSaveExec)))
4003 {
4004 int rcOld = pSSM->rc;
4005 int rc;
4006 switch (pUnit->enmType)
4007 {
4008 case SSMUNITTYPE_DEV:
4009 rc = pUnit->u.Dev.pfnSaveDone(pUnit->u.Dev.pDevIns, pSSM);
4010 break;
4011 case SSMUNITTYPE_DRV:
4012 rc = pUnit->u.Drv.pfnSaveDone(pUnit->u.Drv.pDrvIns, pSSM);
4013 break;
4014 case SSMUNITTYPE_INTERNAL:
4015 rc = pUnit->u.Internal.pfnSaveDone(pVM, pSSM);
4016 break;
4017 case SSMUNITTYPE_EXTERNAL:
4018 rc = pUnit->u.External.pfnSaveDone(pSSM, pUnit->u.External.pvUser);
4019 break;
4020 default:
4021 rc = VERR_INTERNAL_ERROR;
4022 break;
4023 }
4024 if (RT_SUCCESS(rc) && pSSM->rc != rcOld)
4025 rc = pSSM->rc;
4026 if (RT_FAILURE(rc))
4027 {
4028 LogRel(("SSM: Done save failed with rc=%Rrc for data unit '%s.\n", rc, pUnit->szName));
4029 if (RT_SUCCESS_NP(pSSM->rc))
4030 pSSM->rc = rc;
4031 }
4032 }
4033 }
4034 return pSSM->rc;
4035}
4036
4037
4038/**
4039 * Writes the directory.
4040 *
4041 * @returns VBox status code.
4042 * @param pVM The VM handle.
4043 * @param pSSM The SSM handle.
4044 * @param pcEntries Where to return the number of directory entries.
4045 */
4046static int ssmR3WriteDirectory(PVM pVM, PSSMHANDLE pSSM, uint32_t *pcEntries)
4047{
4048 VM_ASSERT_EMT0(pVM);
4049
4050 /*
4051 * Grab some temporary memory for the dictionary.
4052 */
4053 size_t cbDir = RT_OFFSETOF(SSMFILEDIR, aEntries[pVM->ssm.s.cUnits]);
4054 PSSMFILEDIR pDir = (PSSMFILEDIR)RTMemTmpAlloc(cbDir);
4055 if (!pDir)
4056 {
4057 LogRel(("ssmR3WriteDirectory: failed to allocate %zu bytes!\n", cbDir));
4058 return VERR_NO_TMP_MEMORY;
4059 }
4060
4061 /*
4062 * Initialize it.
4063 */
4064 memcpy(pDir->szMagic, SSMFILEDIR_MAGIC, sizeof(pDir->szMagic));
4065 pDir->u32CRC = 0;
4066 pDir->cEntries = 0;
4067
4068 for (PSSMUNIT pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
4069 if (pUnit->offStream != RTFOFF_MIN)
4070 {
4071 PSSMFILEDIRENTRY pEntry = &pDir->aEntries[pDir->cEntries++];
4072 Assert(pDir->cEntries <= pVM->ssm.s.cUnits);
4073 Assert(pUnit->offStream >= (RTFOFF)sizeof(SSMFILEHDR));
4074 pEntry->off = pUnit->offStream;
4075 pEntry->u32Instance = pUnit->u32Instance;
4076 pEntry->u32NameCRC = RTCrc32(pUnit->szName, pUnit->cchName);
4077 }
4078
4079 /*
4080 * Calculate the actual size and CRC-32, then write the directory
4081 * out to the stream.
4082 */
4083 *pcEntries = pDir->cEntries;
4084 cbDir = RT_OFFSETOF(SSMFILEDIR, aEntries[pDir->cEntries]);
4085 pDir->u32CRC = RTCrc32(pDir, cbDir);
4086 int rc = ssmR3StrmWrite(&pSSM->Strm, pDir, cbDir);
4087 RTMemTmpFree(pDir);
4088 return rc;
4089}
4090
4091
4092/**
4093 * Finalize the saved state stream, i.e. add the end unit, directory
4094 * and footer.
4095 *
4096 * @returns VBox status code (pSSM->rc).
4097 * @param pVM The VM handle.
4098 * @param pSSM The saved state handle.
4099 */
4100static int ssmR3SaveDoFinalization(PVM pVM, PSSMHANDLE pSSM)
4101{
4102 VM_ASSERT_EMT0(pVM);
4103 Assert(RT_SUCCESS(pSSM->rc));
4104
4105 /*
4106 * Write the end unit.
4107 */
4108 SSMFILEUNITHDRV2 UnitHdr;
4109 memcpy(&UnitHdr.szMagic[0], SSMFILEUNITHDR_END, sizeof(UnitHdr.szMagic));
4110 UnitHdr.offStream = ssmR3StrmTell(&pSSM->Strm);
4111 UnitHdr.u32CurStreamCRC = ssmR3StrmCurCRC(&pSSM->Strm);
4112 UnitHdr.u32CRC = 0;
4113 UnitHdr.u32Version = 0;
4114 UnitHdr.u32Instance = 0;
4115 UnitHdr.u32Pass = SSM_PASS_FINAL;
4116 UnitHdr.fFlags = 0;
4117 UnitHdr.cbName = 0;
4118 UnitHdr.u32CRC = RTCrc32(&UnitHdr, RT_OFFSETOF(SSMFILEUNITHDRV2, szName[0]));
4119 Log(("SSM: Unit at %#9llx: END UNIT\n", UnitHdr.offStream));
4120 int rc = ssmR3StrmWrite(&pSSM->Strm, &UnitHdr, RT_OFFSETOF(SSMFILEUNITHDRV2, szName[0]));
4121 if (RT_FAILURE(rc))
4122 {
4123 LogRel(("SSM: Failed writing the end unit: %Rrc\n", rc));
4124 return pSSM->rc = rc;
4125 }
4126
4127 /*
4128 * Write the directory for the final units and then the footer.
4129 */
4130 SSMFILEFTR Footer;
4131 rc = ssmR3WriteDirectory(pVM, pSSM, &Footer.cDirEntries);
4132 if (RT_FAILURE(rc))
4133 {
4134 LogRel(("SSM: Failed writing the directory: %Rrc\n", rc));
4135 return pSSM->rc = rc;
4136 }
4137
4138 memcpy(Footer.szMagic, SSMFILEFTR_MAGIC, sizeof(Footer.szMagic));
4139 Footer.offStream = ssmR3StrmTell(&pSSM->Strm);
4140 Footer.u32StreamCRC = ssmR3StrmFinalCRC(&pSSM->Strm);
4141 Footer.u32Reserved = 0;
4142 Footer.u32CRC = 0;
4143 Footer.u32CRC = RTCrc32(&Footer, sizeof(Footer));
4144 Log(("SSM: Footer at %#9llx: \n", Footer.offStream));
4145 rc = ssmR3StrmWrite(&pSSM->Strm, &Footer, sizeof(Footer));
4146 if (RT_SUCCESS(rc))
4147 rc = ssmR3StrmSetEnd(&pSSM->Strm);
4148 if (RT_FAILURE(rc))
4149 {
4150 LogRel(("SSM: Failed writing the footer: %Rrc\n", rc));
4151 return pSSM->rc = rc;
4152 }
4153
4154 LogRel(("SSM: Footer at %#llx (%lld), %u directory entries.\n",
4155 Footer.offStream, Footer.offStream, Footer.cDirEntries));
4156 return VINF_SUCCESS;
4157}
4158
4159
4160/**
4161 * Do the pfnSaveExec run.
4162 *
4163 * @returns VBox status code (pSSM->rc).
4164 * @param pVM The VM handle.
4165 * @param pSSM The saved state handle.
4166 */
4167static int ssmR3SaveDoExecRun(PVM pVM, PSSMHANDLE pSSM)
4168{
4169 VM_ASSERT_EMT0(pVM);
4170 AssertRC(pSSM->rc);
4171 pSSM->rc = VINF_SUCCESS;
4172 pSSM->enmOp = SSMSTATE_SAVE_EXEC;
4173 for (PSSMUNIT pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
4174 {
4175 /*
4176 * Not all unit have a callback. Skip those which don't and
4177 * make sure to keep the progress indicator up to date.
4178 */
4179 pSSM->offEstUnitEnd += pUnit->cbGuess;
4180 if (!pUnit->u.Common.pfnSaveExec)
4181 {
4182 pUnit->fCalled = true;
4183 if (pUnit->cbGuess)
4184 ssmR3Progress(pSSM, pSSM->offEstUnitEnd - pSSM->offEst);
4185 continue;
4186 }
4187 pUnit->offStream = ssmR3StrmTell(&pSSM->Strm);
4188
4189 /*
4190 * Check for cancellation.
4191 */
4192 if (RT_UNLIKELY(ASMAtomicUoReadU32(&(pSSM)->fCancelled) == SSMHANDLE_CANCELLED))
4193 {
4194 LogRel(("SSM: Cancelled!\n"));
4195 AssertRC(pSSM->rc);
4196 return pSSM->rc = VERR_SSM_CANCELLED;
4197 }
4198
4199 /*
4200 * Write data unit header
4201 */
4202 SSMFILEUNITHDRV2 UnitHdr;
4203 memcpy(&UnitHdr.szMagic[0], SSMFILEUNITHDR_MAGIC, sizeof(UnitHdr.szMagic));
4204 UnitHdr.offStream = pUnit->offStream;
4205 UnitHdr.u32CurStreamCRC = ssmR3StrmCurCRC(&pSSM->Strm);
4206 UnitHdr.u32CRC = 0;
4207 UnitHdr.u32Version = pUnit->u32Version;
4208 UnitHdr.u32Instance = pUnit->u32Instance;
4209 UnitHdr.u32Pass = SSM_PASS_FINAL;
4210 UnitHdr.fFlags = 0;
4211 UnitHdr.cbName = (uint32_t)pUnit->cchName + 1;
4212 memcpy(&UnitHdr.szName[0], &pUnit->szName[0], UnitHdr.cbName);
4213 UnitHdr.u32CRC = RTCrc32(&UnitHdr, RT_OFFSETOF(SSMFILEUNITHDRV2, szName[UnitHdr.cbName]));
4214 Log(("SSM: Unit at %#9llx: '%s', instance %u, pass %#x, version %u\n",
4215 UnitHdr.offStream, UnitHdr.szName, UnitHdr.u32Instance, UnitHdr.u32Pass, UnitHdr.u32Version));
4216 int rc = ssmR3StrmWrite(&pSSM->Strm, &UnitHdr, RT_OFFSETOF(SSMFILEUNITHDRV2, szName[UnitHdr.cbName]));
4217 if (RT_FAILURE(rc))
4218 {
4219 LogRel(("SSM: Failed to write unit header. rc=%Rrc\n", rc));
4220 return pSSM->rc = rc;
4221 }
4222
4223 /*
4224 * Call the execute handler.
4225 */
4226 ssmR3DataWriteBegin(pSSM);
4227 switch (pUnit->enmType)
4228 {
4229 case SSMUNITTYPE_DEV:
4230 rc = pUnit->u.Dev.pfnSaveExec(pUnit->u.Dev.pDevIns, pSSM);
4231 break;
4232 case SSMUNITTYPE_DRV:
4233 rc = pUnit->u.Drv.pfnSaveExec(pUnit->u.Drv.pDrvIns, pSSM);
4234 break;
4235 case SSMUNITTYPE_INTERNAL:
4236 rc = pUnit->u.Internal.pfnSaveExec(pVM, pSSM);
4237 break;
4238 case SSMUNITTYPE_EXTERNAL:
4239 pUnit->u.External.pfnSaveExec(pSSM, pUnit->u.External.pvUser);
4240 rc = pSSM->rc;
4241 break;
4242 default:
4243 rc = VERR_INTERNAL_ERROR;
4244 break;
4245 }
4246 pUnit->fCalled = true;
4247 if (RT_FAILURE(rc) && RT_SUCCESS_NP(pSSM->rc))
4248 pSSM->rc = rc;
4249 else
4250 rc = ssmR3DataFlushBuffer(pSSM); /* will return SSMHANDLE::rc if it is set */
4251 if (RT_FAILURE(rc))
4252 {
4253 LogRel(("SSM: Execute save failed with rc=%Rrc for data unit '%s'/#%u.\n", rc, pUnit->szName, pUnit->u32Instance));
4254 return rc;
4255 }
4256
4257 /*
4258 * Write the termination record and flush the compression stream.
4259 */
4260 SSMRECTERM TermRec;
4261 TermRec.u8TypeAndFlags = SSM_REC_FLAGS_FIXED | SSM_REC_FLAGS_IMPORTANT | SSM_REC_TYPE_TERM;
4262 TermRec.cbRec = sizeof(TermRec) - 2;
4263 if (pSSM->Strm.fChecksummed)
4264 {
4265 TermRec.fFlags = SSMRECTERM_FLAGS_CRC32;
4266 TermRec.u32StreamCRC = RTCrc32Finish(RTCrc32Process(ssmR3StrmCurCRC(&pSSM->Strm), &TermRec, 2));
4267 }
4268 else
4269 {
4270 TermRec.fFlags = 0;
4271 TermRec.u32StreamCRC = 0;
4272 }
4273 TermRec.cbUnit = pSSM->offUnit + sizeof(TermRec);
4274 rc = ssmR3DataWriteRaw(pSSM, &TermRec, sizeof(TermRec));
4275 if (RT_SUCCESS(rc))
4276 rc = ssmR3DataWriteFinish(pSSM);
4277 if (RT_FAILURE(rc))
4278 {
4279 LogRel(("SSM: Failed terminating unit: %Rrc\n", rc));
4280 return pSSM->rc = rc;
4281 }
4282
4283 /*
4284 * Advance the progress indicator to the end of the current unit.
4285 */
4286 ssmR3Progress(pSSM, pSSM->offEstUnitEnd - pSSM->offEst);
4287 } /* for each unit */
4288
4289
4290 /* (progress should be pending 99% now) */
4291 AssertMsg( pSSM->uPercent == (101 - pSSM->uPercentDone)
4292 || pSSM->fLiveSave, ("%d\n", pSSM->uPercent));
4293 return VINF_SUCCESS;
4294}
4295
4296
4297/**
4298 * Do the pfnSavePrep run.
4299 *
4300 * @returns VBox status code (pSSM->rc).
4301 * @param pVM The VM handle.
4302 * @param pSSM The saved state handle.
4303 */
4304static int ssmR3SaveDoPrepRun(PVM pVM, PSSMHANDLE pSSM)
4305{
4306 VM_ASSERT_EMT0(pVM);
4307 Assert(RT_SUCCESS(pSSM->rc));
4308 pSSM->enmOp = SSMSTATE_SAVE_PREP;
4309 for (PSSMUNIT pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
4310 {
4311 if (pUnit->u.Common.pfnSavePrep)
4312 {
4313 int rc;
4314 switch (pUnit->enmType)
4315 {
4316 case SSMUNITTYPE_DEV:
4317 rc = pUnit->u.Dev.pfnSavePrep(pUnit->u.Dev.pDevIns, pSSM);
4318 break;
4319 case SSMUNITTYPE_DRV:
4320 rc = pUnit->u.Drv.pfnSavePrep(pUnit->u.Drv.pDrvIns, pSSM);
4321 break;
4322 case SSMUNITTYPE_INTERNAL:
4323 rc = pUnit->u.Internal.pfnSavePrep(pVM, pSSM);
4324 break;
4325 case SSMUNITTYPE_EXTERNAL:
4326 rc = pUnit->u.External.pfnSavePrep(pSSM, pUnit->u.External.pvUser);
4327 break;
4328 default:
4329 rc = VERR_INTERNAL_ERROR;
4330 break;
4331 }
4332 pUnit->fCalled = true;
4333 if (RT_FAILURE(rc) && RT_SUCCESS_NP(pSSM->rc))
4334 pSSM->rc = rc;
4335 else
4336 rc = pSSM->rc;
4337 if (RT_FAILURE(rc))
4338 {
4339 LogRel(("SSM: Prepare save failed with rc=%Rrc for data unit '%s.\n", rc, pUnit->szName));
4340 return rc;
4341 }
4342 }
4343
4344 pSSM->cbEstTotal += pUnit->cbGuess;
4345 }
4346
4347 /*
4348 * Work the progress indicator if we got one.
4349 */
4350 if (pSSM->pfnProgress)
4351 pSSM->pfnProgress(pVM, pSSM->uPercentPrepare-1, pSSM->pvUser);
4352 pSSM->uPercent = pSSM->uPercentPrepare;
4353
4354 return VINF_SUCCESS;
4355}
4356
4357
4358/**
4359 * Common worker for SSMR3Save and SSMR3LiveSave.
4360 *
4361 * @returns VBox status code (no need to check pSSM->rc).
4362 * @param pVM The VM handle.
4363 * @param pSSM The state handle.
4364 *
4365 * @thread EMT(0)
4366 */
4367static int ssmR3SaveDoCommon(PVM pVM, PSSMHANDLE pSSM)
4368{
4369 VM_ASSERT_EMT0(pVM);
4370
4371 /*
4372 * Do the work.
4373 */
4374 int rc = ssmR3SaveDoPrepRun(pVM, pSSM);
4375 if (RT_SUCCESS(rc))
4376 {
4377 rc = ssmR3SaveDoExecRun(pVM, pSSM);
4378 if (RT_SUCCESS(rc))
4379 rc = ssmR3SaveDoFinalization(pVM, pSSM);
4380 }
4381 Assert(pSSM->rc == rc);
4382 int rc2 = ssmR3SaveDoDoneRun(pVM, pSSM);
4383 if (RT_SUCCESS(rc))
4384 rc = rc2;
4385
4386 return rc;
4387}
4388
4389
4390/**
4391 * Saves the rest of the state on EMT0.
4392 *
4393 * @returns VBox status.
4394 *
4395 * @param pSSM The SSM handle returned by SSMR3LiveSave.
4396 *
4397 * @thread Non-EMT thread. Will involve the EMT at the end of the operation.
4398 */
4399VMMR3_INT_DECL(int) SSMR3LiveDoStep2(PSSMHANDLE pSSM)
4400{
4401 LogFlow(("SSMR3LiveDoStep2: pSSM=%p\n", pSSM));
4402
4403 /*
4404 * Validate input.
4405 */
4406 AssertPtrReturn(pSSM, VERR_INVALID_POINTER);
4407 PVM pVM = pSSM->pVM;
4408 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
4409 VM_ASSERT_EMT0(pVM);
4410 AssertMsgReturn( pSSM->enmAfter == SSMAFTER_DESTROY
4411 || pSSM->enmAfter == SSMAFTER_CONTINUE
4412 || pSSM->enmAfter == SSMAFTER_MIGRATE,
4413 ("%d\n", pSSM->enmAfter),
4414 VERR_INVALID_PARAMETER);
4415 AssertMsgReturn(pSSM->enmOp == SSMSTATE_LIVE_STEP2, ("%d\n", pSSM->enmOp), VERR_INVALID_STATE);
4416 AssertRCReturn(pSSM->rc, pSSM->rc);
4417
4418 /*
4419 * Join paths with VMMR3Save.
4420 */
4421 return ssmR3SaveDoCommon(pVM, pSSM);
4422}
4423
4424
4425/**
4426 * Writes the file header and clear the per-unit data.
4427 *
4428 * @returns VBox status code.
4429 * @param pVM The VM handle.
4430 * @param pSSM The SSM handle.
4431 */
4432static int ssmR3WriteHeaderAndClearPerUnitData(PVM pVM, PSSMHANDLE pSSM)
4433{
4434 /*
4435 * Write the header.
4436 */
4437 SSMFILEHDR FileHdr;
4438 memcpy(&FileHdr.szMagic, SSMFILEHDR_MAGIC_V2_0, sizeof(FileHdr.szMagic));
4439 FileHdr.u16VerMajor = VBOX_VERSION_MAJOR;
4440 FileHdr.u16VerMinor = VBOX_VERSION_MINOR;
4441 FileHdr.u32VerBuild = VBOX_VERSION_BUILD;
4442 FileHdr.u32SvnRev = VMMGetSvnRev(),
4443 FileHdr.cHostBits = HC_ARCH_BITS;
4444 FileHdr.cbGCPhys = sizeof(RTGCPHYS);
4445 FileHdr.cbGCPtr = sizeof(RTGCPTR);
4446 FileHdr.u8Reserved = 0;
4447 FileHdr.cUnits = pVM->ssm.s.cUnits;
4448 FileHdr.fFlags = SSMFILEHDR_FLAGS_STREAM_CRC32;
4449 if (pSSM->fLiveSave)
4450 FileHdr.fFlags |= SSMFILEHDR_FLAGS_STREAM_LIVE_SAVE;
4451 FileHdr.cbMaxDecompr = RT_SIZEOFMEMB(SSMHANDLE, u.Read.abDataBuffer);
4452 FileHdr.u32CRC = 0;
4453 FileHdr.u32CRC = RTCrc32(&FileHdr, sizeof(FileHdr));
4454 int rc = ssmR3StrmWrite(&pSSM->Strm, &FileHdr, sizeof(FileHdr));
4455 if (RT_FAILURE(rc))
4456 return rc;
4457
4458 /*
4459 * Clear the per unit flags and offsets.
4460 */
4461 for (PSSMUNIT pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
4462 {
4463 pUnit->fCalled = false;
4464 pUnit->offStream = RTFOFF_MIN;
4465 }
4466
4467 return VINF_SUCCESS;
4468}
4469
4470
4471/**
4472 * Creates a new saved state file.
4473 *
4474 * @returns VBox status code.
4475 * @param pVM The VM handle.
4476 * @param pszFilename The name of the file. NULL if pStreamOps is
4477 * used.
4478 * @param pStreamOps The stream methods. NULL if pszFilename is
4479 * used.
4480 * @param pvStreamOpsUser The user argument to the stream methods.
4481 * @param enmAfter What to do afterwards.
4482 * @param pfnProgress The progress callback.
4483 * @param pvProgressUser The progress callback user argument.
4484 * @param ppSSM Where to return the pointer to the saved state
4485 * handle upon successful return. Free it using
4486 * RTMemFree after closing the stream.
4487 */
4488static int ssmR3SaveDoCreateFile(PVM pVM, const char *pszFilename, PCSSMSTRMOPS pStreamOps, void *pvStreamOpsUser,
4489 SSMAFTER enmAfter, PFNVMPROGRESS pfnProgress, void *pvProgressUser, PSSMHANDLE *ppSSM)
4490{
4491 PSSMHANDLE pSSM = (PSSMHANDLE)RTMemAllocZ(sizeof(*pSSM));
4492 if (!pSSM)
4493 return VERR_NO_MEMORY;
4494
4495 pSSM->pVM = pVM;
4496 pSSM->enmOp = SSMSTATE_INVALID;
4497 pSSM->enmAfter = enmAfter;
4498 pSSM->fCancelled = SSMHANDLE_OK;
4499 pSSM->rc = VINF_SUCCESS;
4500 pSSM->cbUnitLeftV1 = 0;
4501 pSSM->offUnit = UINT64_MAX;
4502 pSSM->fLiveSave = false;
4503 pSSM->pfnProgress = pfnProgress;
4504 pSSM->pvUser = pvProgressUser;
4505 pSSM->uPercent = 0;
4506 pSSM->offEstProgress = 0;
4507 pSSM->cbEstTotal = 0;
4508 pSSM->offEst = 0;
4509 pSSM->offEstUnitEnd = 0;
4510 pSSM->uPercentPrepare = 0;
4511 pSSM->uPercentDone = 0;
4512 pSSM->pszFilename = pszFilename;
4513 pSSM->u.Write.offDataBuffer = 0;
4514
4515 int rc;
4516 if (pStreamOps)
4517 rc = ssmR3StrmInit(&pSSM->Strm, pStreamOps, pvStreamOpsUser, true /*fWrite*/, true /*fChecksummed*/, 8 /*cBuffers*/);
4518 else
4519 rc = ssmR3StrmOpenFile(&pSSM->Strm, pszFilename, true /*fWrite*/, true /*fChecksummed*/, 8 /*cBuffers*/);
4520 if (RT_FAILURE(rc))
4521 {
4522 LogRel(("SSM: Failed to create save state file '%s', rc=%Rrc.\n", pszFilename, rc));
4523 RTMemFree(pSSM);
4524 return rc;
4525 }
4526
4527 *ppSSM = pSSM;
4528 return VINF_SUCCESS;
4529}
4530
4531
4532/**
4533 * Start VM save operation.
4534 *
4535 * @returns VBox status.
4536 *
4537 * @param pVM The VM handle.
4538 * @param pszFilename Name of the file to save the state in.
4539 * @param enmAfter What is planned after a successful save operation.
4540 * @param pfnProgress Progress callback. Optional.
4541 * @param pvUser User argument for the progress callback.
4542 *
4543 * @thread EMT
4544 */
4545VMMR3DECL(int) SSMR3Save(PVM pVM, const char *pszFilename, SSMAFTER enmAfter, PFNVMPROGRESS pfnProgress, void *pvUser)
4546{
4547 LogFlow(("SSMR3Save: pszFilename=%p:{%s} enmAfter=%d pfnProgress=%p pvUser=%p\n", pszFilename, pszFilename, enmAfter, pfnProgress, pvUser));
4548 VM_ASSERT_EMT0(pVM);
4549
4550 /*
4551 * Validate input.
4552 */
4553 AssertMsgReturn( enmAfter == SSMAFTER_DESTROY
4554 || enmAfter == SSMAFTER_CONTINUE,
4555 ("%d\n", enmAfter),
4556 VERR_INVALID_PARAMETER);
4557
4558 /*
4559 * Create the saved state file and handle.
4560 *
4561 * Note that there might be quite some work to do after executing the saving,
4562 * so we reserve 20% for the 'Done' period.
4563 */
4564 PSSMHANDLE pSSM;
4565 int rc = ssmR3SaveDoCreateFile(pVM, pszFilename, NULL /*pStreamOps*/, NULL /*pvStreamOpsUser*/,
4566 enmAfter, pfnProgress, pvUser, &pSSM);
4567 if (RT_FAILURE(rc))
4568 return rc;
4569 pSSM->uPercentPrepare = 20;
4570 pSSM->uPercentDone = 2;
4571
4572 /*
4573 * Write the saved state stream header and join paths with
4574 * the other save methods for the rest of the job.
4575 */
4576 Log(("SSM: Starting state save to file '%s'...\n", pszFilename));
4577 ssmR3StrmStartIoThread(&pSSM->Strm);
4578 rc = ssmR3WriteHeaderAndClearPerUnitData(pVM, pSSM);
4579 if (RT_SUCCESS(rc))
4580 {
4581 ssmR3SetCancellable(pVM, pSSM, true);
4582 ssmR3SaveDoCommon(pVM, pSSM);
4583 }
4584
4585 return ssmR3SaveDoClose(pVM, pSSM);
4586}
4587
4588
4589/**
4590 * Calls pfnLiveVote for all units.
4591 *
4592 * @returns VBox status code (no need to check pSSM->rc).
4593 * @retval VINF_SUCCESS if we can pass on to step 2.
4594 * @retval VINF_SSM_VOTE_FOR_ANOTHER_PASS if we need another pass.
4595 *
4596 * @param pVM The VM handle.
4597 * @param pSSM The saved state handle.
4598 * @param uPass The current pass.
4599 */
4600static int ssmR3LiveDoVoteRun(PVM pVM, PSSMHANDLE pSSM, uint32_t uPass)
4601{
4602 int rcRet = VINF_SUCCESS;
4603 AssertRC(pSSM->rc);
4604 pSSM->rc = VINF_SUCCESS;
4605 pSSM->enmOp = SSMSTATE_LIVE_VOTE;
4606 for (PSSMUNIT pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
4607 {
4608 if ( pUnit->u.Common.pfnLiveVote
4609 && !pUnit->fDoneLive)
4610 {
4611 int rc;
4612 switch (pUnit->enmType)
4613 {
4614 case SSMUNITTYPE_DEV:
4615 rc = pUnit->u.Dev.pfnLiveVote(pUnit->u.Dev.pDevIns, pSSM);
4616 break;
4617 case SSMUNITTYPE_DRV:
4618 rc = pUnit->u.Drv.pfnLiveVote(pUnit->u.Drv.pDrvIns, pSSM);
4619 break;
4620 case SSMUNITTYPE_INTERNAL:
4621 rc = pUnit->u.Internal.pfnLiveVote(pVM, pSSM);
4622 break;
4623 case SSMUNITTYPE_EXTERNAL:
4624 rc = pUnit->u.External.pfnLiveVote(pSSM, pUnit->u.External.pvUser);
4625 break;
4626 default:
4627 rc = VERR_INTERNAL_ERROR;
4628 break;
4629 }
4630 pUnit->fCalled = true;
4631 Assert(pSSM->rc == VINF_SUCCESS);
4632 if (rc != VINF_SUCCESS)
4633 {
4634 if (rc == VINF_SSM_VOTE_FOR_ANOTHER_PASS)
4635 {
4636 Log(("ssmR3DoLiveVoteRun: '%s'/#%u -> VINF_SSM_VOTE_FOR_ANOTHER_PASS (pass=%u)\n", pUnit->szName, pUnit->u32Instance, uPass));
4637 rcRet = VINF_SSM_VOTE_FOR_ANOTHER_PASS;
4638 }
4639 else if (rc == VINF_SSM_VOTE_DONE_DONT_CALL_AGAIN)
4640 {
4641 pUnit->fDoneLive = true;
4642 Log(("ssmR3DoLiveVoteRun: '%s'/#%u -> VINF_SSM_VOTE_DONE_DONT_CALL_AGAIN (pass=%u)\n", pUnit->szName, pUnit->u32Instance, uPass));
4643 }
4644 else
4645 {
4646 /*
4647 * rc is usually VERR_SSM_VOTE_FOR_GIVING_UP here, but we allow
4648 * other status codes for better user feed back. However, no
4649 * other non-error status is allowed.
4650 */
4651 LogRel(("SSM: Error - '%s'/#%u voted %Rrc! (pass=%u)\n", pUnit->szName, pUnit->u32Instance, rc, uPass));
4652 AssertMsgReturn(RT_FAILURE(rc), ("%Rrc; '%s'\n", rc, pUnit->szName), pSSM->rc = VERR_IPE_UNEXPECTED_INFO_STATUS);
4653 return pSSM->rc = rc;
4654 }
4655 }
4656 }
4657 }
4658 if (rcRet == VINF_SUCCESS)
4659 LogRel(("SSM: Step 1 completed after pass %u.\n", uPass));
4660 return rcRet;
4661}
4662
4663
4664/**
4665 * Calls pfnLiveExec for all units.
4666 *
4667 * @returns VBox status code (no need to check pSSM->rc).
4668 *
4669 * @param pVM The VM handle.
4670 * @param pSSM The saved state handle.
4671 * @param uPass The current pass.
4672 */
4673static int ssmR3LiveDoExecRun(PVM pVM, PSSMHANDLE pSSM, uint32_t uPass)
4674{
4675 AssertRC(pSSM->rc);
4676 pSSM->rc = VINF_SUCCESS;
4677 pSSM->enmOp = SSMSTATE_LIVE_EXEC;
4678 for (PSSMUNIT pUnit = pVM->ssm.s.pHead;
4679 /** @todo VMR3GetState(pVM) == VMSTATE_LIVE_SAVING &&*/ pUnit;
4680 pUnit = pUnit->pNext)
4681 {
4682 /*
4683 * Skip units without a callback (this is most).
4684 */
4685 if ( !pUnit->u.Common.pfnLiveExec
4686 || pUnit->fDoneLive)
4687 continue;
4688 pUnit->offStream = ssmR3StrmTell(&pSSM->Strm);
4689
4690 /*
4691 * Check for cancellation.
4692 */
4693 if (RT_UNLIKELY(ASMAtomicUoReadU32(&(pSSM)->fCancelled) == SSMHANDLE_CANCELLED))
4694 {
4695 LogRel(("SSM: Cancelled!\n"));
4696 AssertRC(pSSM->rc);
4697 return pSSM->rc = VERR_SSM_CANCELLED;
4698 }
4699
4700 /*
4701 * Write data unit header.
4702 */
4703 SSMFILEUNITHDRV2 UnitHdr;
4704 memcpy(&UnitHdr.szMagic[0], SSMFILEUNITHDR_MAGIC, sizeof(UnitHdr.szMagic));
4705 UnitHdr.offStream = pUnit->offStream;
4706 UnitHdr.u32CurStreamCRC = ssmR3StrmCurCRC(&pSSM->Strm);
4707 UnitHdr.u32CRC = 0;
4708 UnitHdr.u32Version = pUnit->u32Version;
4709 UnitHdr.u32Instance = pUnit->u32Instance;
4710 UnitHdr.u32Pass = uPass;
4711 UnitHdr.fFlags = 0;
4712 UnitHdr.cbName = (uint32_t)pUnit->cchName + 1;
4713 memcpy(&UnitHdr.szName[0], &pUnit->szName[0], UnitHdr.cbName);
4714 UnitHdr.u32CRC = RTCrc32(&UnitHdr, RT_OFFSETOF(SSMFILEUNITHDRV2, szName[UnitHdr.cbName]));
4715 Log(("SSM: Unit at %#9llx: '%s', instance %u, pass %#x, version %u\n",
4716 UnitHdr.offStream, UnitHdr.szName, UnitHdr.u32Instance, UnitHdr.u32Pass, UnitHdr.u32Version));
4717 int rc = ssmR3StrmWrite(&pSSM->Strm, &UnitHdr, RT_OFFSETOF(SSMFILEUNITHDRV2, szName[UnitHdr.cbName]));
4718 if (RT_FAILURE(rc))
4719 {
4720 LogRel(("SSM: Failed to write unit header. rc=%Rrc\n", rc));
4721 return pSSM->rc = rc;
4722 }
4723
4724 /*
4725 * Call the execute handler.
4726 */
4727 ssmR3DataWriteBegin(pSSM);
4728 switch (pUnit->enmType)
4729 {
4730 case SSMUNITTYPE_DEV:
4731 rc = pUnit->u.Dev.pfnLiveExec(pUnit->u.Dev.pDevIns, pSSM, uPass);
4732 break;
4733 case SSMUNITTYPE_DRV:
4734 rc = pUnit->u.Drv.pfnLiveExec(pUnit->u.Drv.pDrvIns, pSSM, uPass);
4735 break;
4736 case SSMUNITTYPE_INTERNAL:
4737 rc = pUnit->u.Internal.pfnLiveExec(pVM, pSSM, uPass);
4738 break;
4739 case SSMUNITTYPE_EXTERNAL:
4740 rc = pUnit->u.External.pfnLiveExec(pSSM, pUnit->u.External.pvUser, uPass);
4741 break;
4742 default:
4743 rc = VERR_INTERNAL_ERROR;
4744 break;
4745 }
4746 pUnit->fCalled = true;
4747 if (RT_FAILURE(rc) && RT_SUCCESS_NP(pSSM->rc))
4748 pSSM->rc = rc;
4749 else
4750 {
4751 if (rc == VINF_SSM_DONT_CALL_AGAIN)
4752 pUnit->fDoneLive = true;
4753 rc = ssmR3DataFlushBuffer(pSSM); /* will return SSMHANDLE::rc if it is set */
4754 }
4755 if (RT_FAILURE(rc))
4756 {
4757 LogRel(("SSM: Execute save failed with rc=%Rrc for data unit '%s'/#%u.\n", rc, pUnit->szName, pUnit->u32Instance));
4758 if (RT_SUCCESS(pSSM->rc))
4759 pSSM->rc = rc;
4760 return rc;
4761 }
4762
4763 /*
4764 * Write the termination record and flush the compression stream.
4765 */
4766 SSMRECTERM TermRec;
4767 TermRec.u8TypeAndFlags = SSM_REC_FLAGS_FIXED | SSM_REC_FLAGS_IMPORTANT | SSM_REC_TYPE_TERM;
4768 TermRec.cbRec = sizeof(TermRec) - 2;
4769 if (pSSM->Strm.fChecksummed)
4770 {
4771 TermRec.fFlags = SSMRECTERM_FLAGS_CRC32;
4772 TermRec.u32StreamCRC = RTCrc32Finish(RTCrc32Process(ssmR3StrmCurCRC(&pSSM->Strm), &TermRec, 2));
4773 }
4774 else
4775 {
4776 TermRec.fFlags = 0;
4777 TermRec.u32StreamCRC = 0;
4778 }
4779 TermRec.cbUnit = pSSM->offUnit + sizeof(TermRec);
4780 rc = ssmR3DataWriteRaw(pSSM, &TermRec, sizeof(TermRec));
4781 if (RT_SUCCESS(rc))
4782 rc = ssmR3DataWriteFinish(pSSM);
4783 if (RT_FAILURE(rc))
4784 {
4785 LogRel(("SSM: Failed terminating unit: %Rrc (pass=%u)\n", rc, uPass));
4786 return pSSM->rc = rc;
4787 }
4788 } /* for each unit */
4789
4790 return VINF_SUCCESS;
4791}
4792
4793
4794
4795/**
4796 * Continue a live state saving operation on the worker thread.
4797 *
4798 * @returns VBox status.
4799 *
4800 * @param pSSM The SSM handle returned by SSMR3LiveSave.
4801 *
4802 * @thread Non-EMT thread. Will involve the EMT at the end of the operation.
4803 */
4804VMMR3_INT_DECL(int) SSMR3LiveDoStep1(PSSMHANDLE pSSM)
4805{
4806 LogFlow(("SSMR3LiveDoStep1: pSSM=%p\n", pSSM));
4807
4808 /*
4809 * Validate input.
4810 */
4811 AssertPtrReturn(pSSM, VERR_INVALID_POINTER);
4812 PVM pVM = pSSM->pVM;
4813 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
4814 VM_ASSERT_OTHER_THREAD(pVM);
4815 AssertMsgReturn( pSSM->enmAfter == SSMAFTER_DESTROY
4816 || pSSM->enmAfter == SSMAFTER_CONTINUE
4817 || pSSM->enmAfter == SSMAFTER_MIGRATE,
4818 ("%d\n", pSSM->enmAfter),
4819 VERR_INVALID_PARAMETER);
4820 AssertMsgReturn(pSSM->enmOp == SSMSTATE_LIVE_STEP1, ("%d\n", pSSM->enmOp), VERR_INVALID_STATE);
4821 AssertRCReturn(pSSM->rc, pSSM->rc);
4822
4823 /*
4824 * Calc the max saved state size before we should give up because of insane
4825 * amounts of data.
4826 */
4827#define SSM_MAX_GROWTH_FILE 10000
4828#define SSM_MAX_GROWTH_REMOTE 100000
4829 uint64_t cbSum = 0;
4830 for (PSSMUNIT pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
4831 cbSum += pUnit->cbGuess;
4832 uint64_t cbMax = cbSum * (pSSM->pszFilename ? SSM_MAX_GROWTH_FILE : SSM_MAX_GROWTH_REMOTE);
4833 AssertLogRelMsgReturn(cbMax > cbSum, ("cbMax=%#RX64, cbSum=%#RX64\n", cbMax, cbSum), pSSM->rc = VERR_OUT_OF_RANGE);
4834 if (cbMax < _1G)
4835 cbMax = _1G;
4836
4837 /*
4838 * The pass loop.
4839 *
4840 * The number of interations is restricted for two reasons, first
4841 * to make sure
4842 */
4843#define SSM_MAX_PASSES _1M
4844 for (uint32_t uPass = 0; uPass < SSM_MAX_PASSES; uPass++)
4845 {
4846 /*
4847 * Save state and vote on whether we need more passes or not.
4848 */
4849 int rc = ssmR3LiveDoExecRun(pVM, pSSM, uPass);
4850 if (RT_FAILURE(rc))
4851 return rc;
4852 rc = ssmR3LiveDoVoteRun(pVM, pSSM, uPass);
4853 if (rc == VINF_SUCCESS)
4854 {
4855 pSSM->enmOp = SSMSTATE_LIVE_STEP2;
4856 return VINF_SUCCESS;
4857 }
4858 if (RT_FAILURE(rc))
4859 return rc;
4860
4861 /*
4862 * Check that we're still within sane data amounts.
4863 */
4864 uint64_t cbSaved = ssmR3StrmTell(&pSSM->Strm);
4865 if (cbSaved > cbMax)
4866 {
4867 LogRel(("SSM: Giving up: Exceeded max state size. (cbSaved=%#RX64, cbMax=%#RX64)\n", cbSaved, cbMax));
4868 return pSSM->rc = VERR_SSM_STATE_GREW_TOO_BIG;
4869 }
4870
4871 /*
4872 * Check that there is still some space left on the disk.
4873 */
4874 /** @todo move this to the stream flushing code? It's not perfect when done
4875 * here, it could be way better if we did it there. */
4876 if (pSSM->pszFilename)
4877 {
4878 RTFOFF cbFree;
4879 rc = RTFsQuerySizes(pSSM->pszFilename, NULL, &cbFree, NULL, NULL);
4880 AssertRC(rc);
4881#define SSM_MIN_DISK_FREE ((RTFOFF)( 10 * _1M ))
4882 if ( RT_SUCCESS(rc)
4883 && cbFree < SSM_MIN_DISK_FREE)
4884 {
4885 LogRel(("SSM: Giving up: Low on disk space. (cbFree=%RTfoff, SSM_MIN_DISK_FREE=%RTfoff).\n",
4886 cbFree, SSM_MIN_DISK_FREE));
4887 return pSSM->rc = VERR_SSM_LOW_ON_DISK_SPACE;
4888 }
4889 }
4890#if 0 /** @todo check this out... */
4891 /*
4892 * Check the VM state to see if it has changed.
4893 */
4894 VMSTATE enmState = VMR3GetState(pVM);
4895 if (enmState != VMSTATE_LIVE_SAVING)
4896 {
4897 switch (enmState)
4898 {
4899 case VMSTATE_LIVE_CANCELLED:
4900 LogRel(("SSM: Cancelled\n"));
4901 return pSSM->rc = VERR_SSM_LIVE_CANCELLED;
4902 case VMSTATE_LIVE_POWERED_OFF:
4903 LogRel(("SSM: Powered off, no state to save, aborting.\n"));
4904 return pSSM->rc = VERR_SSM_LIVE_POWERED_OFF;
4905 case VMSTATE_GURU_MEDITATION:
4906 LogRel(("SSM: Guru meditation, aborting.\n"));
4907 return pSSM->rc = VERR_SSM_LIVE_GURU_MEDITATION;
4908 default:
4909 LogRel(("SSM: Invalid VM state transition: %d->%d\n", VMSTATE_LIVE_SAVING, enmState));
4910 return pSSM->rc = VERR_INTERNAL_ERROR_3;
4911 }
4912 }
4913#endif
4914 }
4915
4916 LogRel(("SSM: Giving up: Too many passes! (%u)\n", SSM_MAX_PASSES));
4917 return pSSM->rc = VERR_SSM_TOO_MANY_PASSES;
4918}
4919
4920
4921/**
4922 * Calls pfnLivePrep for all units.
4923 *
4924 * @returns VBox status code (no need to check pSSM->rc).
4925 * @param pVM The VM handle.
4926 * @param pSSM The saved state handle.
4927 */
4928static int ssmR3DoLivePrepRun(PVM pVM, PSSMHANDLE pSSM)
4929{
4930 /*
4931 * Do the prepare run.
4932 */
4933 pSSM->rc = VINF_SUCCESS;
4934 pSSM->enmOp = SSMSTATE_SAVE_PREP;
4935 for (PSSMUNIT pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
4936 {
4937 if (pUnit->u.Common.pfnLivePrep)
4938 {
4939 int rc;
4940 switch (pUnit->enmType)
4941 {
4942 case SSMUNITTYPE_DEV:
4943 rc = pUnit->u.Dev.pfnLivePrep(pUnit->u.Dev.pDevIns, pSSM);
4944 break;
4945 case SSMUNITTYPE_DRV:
4946 rc = pUnit->u.Drv.pfnLivePrep(pUnit->u.Drv.pDrvIns, pSSM);
4947 break;
4948 case SSMUNITTYPE_INTERNAL:
4949 rc = pUnit->u.Internal.pfnLivePrep(pVM, pSSM);
4950 break;
4951 case SSMUNITTYPE_EXTERNAL:
4952 rc = pUnit->u.External.pfnLivePrep(pSSM, pUnit->u.External.pvUser);
4953 break;
4954 default:
4955 rc = VERR_INTERNAL_ERROR;
4956 break;
4957 }
4958 pUnit->fCalled = true;
4959 if (RT_FAILURE(rc) && RT_SUCCESS_NP(pSSM->rc))
4960 pSSM->rc = rc;
4961 else
4962 rc = pSSM->rc;
4963 if (RT_FAILURE(rc))
4964 {
4965 LogRel(("SSM: Prepare save failed with rc=%Rrc for data unit '%s.\n", rc, pUnit->szName));
4966 return rc;
4967 }
4968 }
4969
4970 pSSM->cbEstTotal += pUnit->cbGuess;
4971 }
4972
4973 /*
4974 * Work the progress indicator if we got one.
4975 */
4976 if (pSSM->pfnProgress)
4977 pSSM->pfnProgress(pVM, 2, pSSM->pvUser);
4978 pSSM->uPercent = 2;
4979
4980 return VINF_SUCCESS;
4981}
4982
4983
4984/**
4985 * Start saving the live state.
4986 *
4987 * Call SSMR3LiveDoStep1, SSMR3LiveDoStep2 and finally SSMR3LiveDone on success.
4988 * SSMR3LiveDone should be called even if SSMR3LiveDoStep1 or SSMR3LiveDoStep2
4989 * fails.
4990 *
4991 * @returns VBox status.
4992 *
4993 * @param pVM The VM handle.
4994 * @param pszFilename Name of the file to save the state in. This string
4995 * must remain valid until SSMR3LiveDone is called.
4996 * Must be NULL if pStreamOps is used.
4997 * @param pStreamOps The stream method table. NULL if pszFilename is
4998 * used.
4999 * @param pvStreamOpsUser The user argument to the stream methods.
5000 * @param enmAfter What is planned after a successful save operation.
5001 * @param pfnProgress Progress callback. Optional.
5002 * @param pvProgressUser User argument for the progress callback.
5003 *
5004 * @thread EMT0
5005 */
5006VMMR3_INT_DECL(int) SSMR3LiveSave(PVM pVM, const char *pszFilename, PCSSMSTRMOPS pStreamOps, void *pvStreamOpsUser,
5007 SSMAFTER enmAfter, PFNVMPROGRESS pfnProgress, void *pvProgressUser, PSSMHANDLE *ppSSM)
5008{
5009 LogFlow(("SSMR3LiveSave: pszFilename=%p:{%s} pStreamOps=%p pvStreamOpsUser=%p enmAfter=%d pfnProgress=%p pvProgressUser=%p\n",
5010 pszFilename, pszFilename, pStreamOps, pvStreamOpsUser, enmAfter, pfnProgress, pvProgressUser));
5011 VM_ASSERT_EMT0(pVM);
5012
5013 /*
5014 * Validate input.
5015 */
5016 AssertMsgReturn( enmAfter == SSMAFTER_DESTROY
5017 || enmAfter == SSMAFTER_CONTINUE
5018 || enmAfter == SSMAFTER_MIGRATE,
5019 ("%d\n", enmAfter),
5020 VERR_INVALID_PARAMETER);
5021 AssertReturn(!pszFilename != !pStreamOps, VERR_INVALID_PARAMETER);
5022 if (pStreamOps)
5023 {
5024 AssertReturn(pStreamOps->u32Version == SSMSTRMOPS_VERSION, VERR_INVALID_MAGIC);
5025 AssertReturn(pStreamOps->u32EndVersion == SSMSTRMOPS_VERSION, VERR_INVALID_MAGIC);
5026 AssertReturn(pStreamOps->pfnWrite, VERR_INVALID_PARAMETER);
5027 AssertReturn(pStreamOps->pfnRead, VERR_INVALID_PARAMETER);
5028 AssertReturn(pStreamOps->pfnSeek, VERR_INVALID_PARAMETER);
5029 AssertReturn(pStreamOps->pfnTell, VERR_INVALID_PARAMETER);
5030 AssertReturn(pStreamOps->pfnSize, VERR_INVALID_PARAMETER);
5031 AssertReturn(pStreamOps->pfnClose, VERR_INVALID_PARAMETER);
5032 }
5033
5034 /*
5035 * Create the saved state file and handle.
5036 *
5037 * Note that there might be quite some work to do after executing the saving,
5038 * so we reserve 20% for the 'Done' period.
5039 */
5040 PSSMHANDLE pSSM;
5041 int rc = ssmR3SaveDoCreateFile(pVM, pszFilename, pStreamOps, pvStreamOpsUser,
5042 enmAfter, pfnProgress, pvProgressUser, &pSSM);
5043 if (RT_FAILURE(rc))
5044 return rc;
5045 pSSM->uPercentPrepare = 20; /** @todo fix these. */
5046 pSSM->uPercentDone = 2;
5047 pSSM->fLiveSave = true;
5048
5049 /*
5050 * Write the saved state stream header and do the prep run for live saving.
5051 */
5052 Log(("SSM: Starting state save to file '%s'...\n", pszFilename));
5053 ssmR3StrmStartIoThread(&pSSM->Strm);
5054 rc = ssmR3WriteHeaderAndClearPerUnitData(pVM, pSSM);
5055 if (RT_SUCCESS(rc))
5056 {
5057/** @todo If it turns out we don't need to do ssmR3DoLivePrepRun on EMT0,
5058 * simply move the code to SSMR3LiveDoStep1.
5059 * Update: This is certinaly the case, move it. */
5060 rc = ssmR3DoLivePrepRun(pVM, pSSM);
5061 if (RT_SUCCESS(rc))
5062 {
5063 /*
5064 * Return and let the requstor thread do the pfnLiveExec/Vote part
5065 * via SSMR3SaveFinishLive
5066 */
5067 pSSM->enmOp = SSMSTATE_LIVE_STEP1;
5068 ssmR3SetCancellable(pVM, pSSM, true);
5069 *ppSSM = pSSM;
5070 return VINF_SUCCESS;
5071 }
5072 }
5073 /* bail out. */
5074 int rc2 = ssmR3StrmClose(&pSSM->Strm);
5075 RTMemFree(pSSM);
5076 rc2 = RTFileDelete(pszFilename);
5077 AssertRC(rc2);
5078 return rc;
5079}
5080
5081
5082VMMR3DECL(int) SSMR3LiveToRemote(PVM pVM, PFNVMPROGRESS pfnProgress, void *pvUser /*,
5083 invent stream interface and stuff */)
5084{
5085 return VERR_NOT_IMPLEMENTED;
5086}
5087
5088
5089/* ... Loading and reading starts here ... */
5090/* ... Loading and reading starts here ... */
5091/* ... Loading and reading starts here ... */
5092/* ... Loading and reading starts here ... */
5093/* ... Loading and reading starts here ... */
5094/* ... Loading and reading starts here ... */
5095/* ... Loading and reading starts here ... */
5096/* ... Loading and reading starts here ... */
5097/* ... Loading and reading starts here ... */
5098/* ... Loading and reading starts here ... */
5099/* ... Loading and reading starts here ... */
5100/* ... Loading and reading starts here ... */
5101/* ... Loading and reading starts here ... */
5102/* ... Loading and reading starts here ... */
5103/* ... Loading and reading starts here ... */
5104/* ... Loading and reading starts here ... */
5105/* ... Loading and reading starts here ... */
5106
5107
5108/**
5109 * Closes the decompressor of a data unit.
5110 *
5111 * @returns pSSM->rc.
5112 * @param pSSM The saved state handle.
5113 */
5114static int ssmR3DataReadFinishV1(PSSMHANDLE pSSM)
5115{
5116 if (pSSM->u.Read.pZipDecompV1)
5117 {
5118 int rc = RTZipDecompDestroy(pSSM->u.Read.pZipDecompV1);
5119 AssertRC(rc);
5120 pSSM->u.Read.pZipDecompV1 = NULL;
5121 }
5122 return pSSM->rc;
5123}
5124
5125
5126/**
5127 * Callback for reading compressed data into the input buffer of the
5128 * decompressor, for saved file format version 1.
5129 *
5130 * @returns VBox status code.
5131 * @param pvSSM The SSM handle.
5132 * @param pvBuf Where to store the compressed data.
5133 * @param cbBuf Size of the buffer.
5134 * @param pcbRead Number of bytes actually stored in the buffer.
5135 */
5136static DECLCALLBACK(int) ssmR3ReadInV1(void *pvSSM, void *pvBuf, size_t cbBuf, size_t *pcbRead)
5137{
5138 PSSMHANDLE pSSM = (PSSMHANDLE)pvSSM;
5139 size_t cbRead = cbBuf;
5140 if (pSSM->cbUnitLeftV1 < cbBuf)
5141 cbRead = (size_t)pSSM->cbUnitLeftV1;
5142 if (cbRead)
5143 {
5144 //Log2(("ssmR3ReadInV1: %#010llx cbBug=%#x cbRead=%#x\n", ssmR3StrmTell(&pSSM->Strm), cbBuf, cbRead));
5145 int rc = ssmR3StrmRead(&pSSM->Strm, pvBuf, cbRead);
5146 if (RT_SUCCESS(rc))
5147 {
5148 pSSM->cbUnitLeftV1 -= cbRead;
5149 if (pcbRead)
5150 *pcbRead = cbRead;
5151 ssmR3Progress(pSSM, cbRead);
5152 return VINF_SUCCESS;
5153 }
5154 return rc;
5155 }
5156
5157 if (pSSM->enmAfter != SSMAFTER_DEBUG_IT)
5158 AssertMsgFailed(("SSM: attempted reading more than the unit!\n"));
5159 return VERR_SSM_LOADED_TOO_MUCH;
5160}
5161
5162
5163/**
5164 * Internal read worker for reading data from a version 1 unit.
5165 *
5166 * @param pSSM The saved state handle.
5167 * @param pvBuf Where to store the read data.
5168 * @param cbBuf Number of bytes to read.
5169 */
5170static int ssmR3DataReadV1(PSSMHANDLE pSSM, void *pvBuf, size_t cbBuf)
5171{
5172 /*
5173 * Open the decompressor on the first read.
5174 */
5175 if (!pSSM->u.Read.pZipDecompV1)
5176 {
5177 pSSM->rc = RTZipDecompCreate(&pSSM->u.Read.pZipDecompV1, pSSM, ssmR3ReadInV1);
5178 if (RT_FAILURE(pSSM->rc))
5179 return pSSM->rc;
5180 }
5181
5182 /*
5183 * Do the requested read.
5184 */
5185 int rc = pSSM->rc = RTZipDecompress(pSSM->u.Read.pZipDecompV1, pvBuf, cbBuf, NULL);
5186 if (RT_SUCCESS(rc))
5187 {
5188 Log2(("ssmR3DataRead: pvBuf=%p cbBuf=%#x offUnit=%#llx %.*Rhxs%s\n", pvBuf, cbBuf, pSSM->offUnit, RT_MIN(cbBuf, SSM_LOG_BYTES), pvBuf, cbBuf > SSM_LOG_BYTES ? "..." : ""));
5189 pSSM->offUnit += cbBuf;
5190 return VINF_SUCCESS;
5191 }
5192 AssertMsgFailed(("rc=%Rrc cbBuf=%#x\n", rc, cbBuf));
5193 return rc;
5194}
5195
5196
5197/**
5198 * Creates the decompressor for the data unit.
5199 *
5200 * pSSM->rc will be set on error.
5201 *
5202 * @param pSSM The saved state handle.
5203 */
5204static void ssmR3DataReadBeginV2(PSSMHANDLE pSSM)
5205{
5206 Assert(!pSSM->u.Read.cbDataBuffer || pSSM->u.Read.cbDataBuffer == pSSM->u.Read.offDataBuffer);
5207 Assert(!pSSM->u.Read.cbRecLeft);
5208
5209 pSSM->offUnit = 0;
5210 pSSM->u.Read.cbRecLeft = 0;
5211 pSSM->u.Read.cbDataBuffer = 0;
5212 pSSM->u.Read.offDataBuffer = 0;
5213 pSSM->u.Read.fEndOfData = false;
5214 pSSM->u.Read.u8TypeAndFlags = 0;
5215}
5216
5217
5218/**
5219 * Checks for the termination record and closes the decompressor.
5220 *
5221 * pSSM->rc will be set on error.
5222 *
5223 * @returns pSSM->rc.
5224 * @param pSSM The saved state handle.
5225 */
5226static int ssmR3DataReadFinishV2(PSSMHANDLE pSSM)
5227{
5228 /*
5229 * If we haven't encountered the end of the record, it must be the next one.
5230 */
5231 int rc = pSSM->rc;
5232 if ( !pSSM->u.Read.fEndOfData
5233 && RT_SUCCESS(rc))
5234 {
5235 rc = ssmR3DataReadRecHdrV2(pSSM);
5236 if ( RT_SUCCESS(rc)
5237 && !pSSM->u.Read.fEndOfData)
5238 {
5239 rc = VERR_SSM_LOADED_TOO_LITTLE;
5240 AssertFailed();
5241 }
5242 pSSM->rc = rc;
5243 }
5244 return rc;
5245}
5246
5247
5248/**
5249 * Read reader that keep works the progress indicator and unit offset.
5250 *
5251 * Does not set SSM::rc.
5252 *
5253 * @returns VBox status code.
5254 * @param pSSM The saved state handle.
5255 * @param pvBuf Where to put the bits
5256 * @param cbBuf How many bytes to read.
5257 */
5258DECLINLINE(int) ssmR3DataReadV2Raw(PSSMHANDLE pSSM, void *pvBuf, size_t cbToRead)
5259{
5260 int rc = ssmR3StrmRead(&pSSM->Strm, pvBuf, cbToRead);
5261 if (RT_SUCCESS(rc))
5262 {
5263 pSSM->offUnit += cbToRead;
5264 ssmR3Progress(pSSM, cbToRead);
5265 return VINF_SUCCESS;
5266 }
5267
5268 /** @todo weed out lazy saving */
5269 if (pSSM->enmAfter != SSMAFTER_DEBUG_IT)
5270 AssertMsgFailed(("SSM: attempted reading more than the unit!\n"));
5271 return VERR_SSM_LOADED_TOO_MUCH;
5272}
5273
5274
5275/**
5276 * Reads and checks the LZF "header".
5277 *
5278 * @returns VBox status code.
5279 * @param pSSM The saved state handle..
5280 * @param pcbDecompr Where to store the size of the decompressed data.
5281 */
5282DECLINLINE(int) ssmR3DataReadV2RawLzfHdr(PSSMHANDLE pSSM, uint32_t *pcbDecompr)
5283{
5284 *pcbDecompr = 0; /* shuts up gcc. */
5285 AssertLogRelMsgReturn( pSSM->u.Read.cbRecLeft > 1
5286 && pSSM->u.Read.cbRecLeft <= RT_SIZEOFMEMB(SSMHANDLE, u.Read.abComprBuffer) + 2,
5287 ("%#x\n", pSSM->u.Read.cbRecLeft),
5288 VERR_SSM_INTEGRITY_DECOMPRESSION);
5289
5290 uint8_t cKB;
5291 int rc = ssmR3DataReadV2Raw(pSSM, &cKB, 1);
5292 if (RT_FAILURE(rc))
5293 return rc;
5294 pSSM->u.Read.cbRecLeft -= sizeof(cKB);
5295
5296 uint32_t cbDecompr = (uint32_t)cKB * _1K;
5297 AssertLogRelMsgReturn( cbDecompr >= pSSM->u.Read.cbRecLeft
5298 && cbDecompr <= RT_SIZEOFMEMB(SSMHANDLE, u.Read.abDataBuffer),
5299 ("%#x\n", cbDecompr),
5300 VERR_SSM_INTEGRITY_DECOMPRESSION);
5301
5302 *pcbDecompr = cbDecompr;
5303 return VINF_SUCCESS;
5304}
5305
5306
5307/**
5308 * Reads an LZF block from the stream and decompresses into the specified
5309 * buffer.
5310 *
5311 * @returns VBox status code.
5312 * @param SSM The saved state handle.
5313 * @param pvDst Pointer to the output buffer.
5314 * @param cbDecompr The size of the decompressed data.
5315 */
5316static int ssmR3DataReadV2RawLzf(PSSMHANDLE pSSM, void *pvDst, size_t cbDecompr)
5317{
5318 int rc;
5319 uint32_t cbCompr = pSSM->u.Read.cbRecLeft;
5320 pSSM->u.Read.cbRecLeft = 0;
5321
5322 /*
5323 * Try use the stream buffer directly to avoid copying things around.
5324 */
5325 uint8_t const *pb = ssmR3StrmReadDirect(&pSSM->Strm, cbCompr);
5326 if (pb)
5327 {
5328 pSSM->offUnit += cbCompr;
5329 ssmR3Progress(pSSM, cbCompr);
5330 }
5331 else
5332 {
5333 rc = ssmR3DataReadV2Raw(pSSM, &pSSM->u.Read.abComprBuffer[0], cbCompr);
5334 if (RT_FAILURE(rc))
5335 return rc;
5336 pb = &pSSM->u.Read.abComprBuffer[0];
5337 }
5338
5339 /*
5340 * Decompress it.
5341 */
5342 size_t cbDstActual;
5343 rc = RTZipBlockDecompress(RTZIPTYPE_LZF, 0 /*fFlags*/,
5344 pb, cbCompr, NULL /*pcbSrcActual*/,
5345 pvDst, cbDecompr, &cbDstActual);
5346 if (RT_SUCCESS(rc))
5347 {
5348 AssertLogRelMsgReturn(cbDstActual == cbDecompr, ("%#x %#x\n", cbDstActual, cbDecompr), VERR_SSM_INTEGRITY_DECOMPRESSION);
5349 return VINF_SUCCESS;
5350 }
5351
5352 AssertLogRelMsgFailed(("cbCompr=%#x cbDecompr=%#x rc=%Rrc\n", cbCompr, cbDecompr, rc));
5353 return VERR_SSM_INTEGRITY_DECOMPRESSION;
5354}
5355
5356
5357/**
5358 * Reads and checks the raw zero "header".
5359 *
5360 * @returns VBox status code.
5361 * @param pSSM The saved state handle..
5362 * @param pcbDecompr Where to store the size of the zero data.
5363 */
5364DECLINLINE(int) ssmR3DataReadV2RawZeroHdr(PSSMHANDLE pSSM, uint32_t *pcbZero)
5365{
5366 *pcbZero = 0; /* shuts up gcc. */
5367 AssertLogRelMsgReturn(pSSM->u.Read.cbRecLeft == 1, ("%#x\n", pSSM->u.Read.cbRecLeft), VERR_SSM_INTEGRITY_DECOMPRESSION);
5368
5369 uint8_t cKB;
5370 int rc = ssmR3DataReadV2Raw(pSSM, &cKB, 1);
5371 if (RT_FAILURE(rc))
5372 return rc;
5373 pSSM->u.Read.cbRecLeft = 0;
5374
5375 uint32_t cbZero = (uint32_t)cKB * _1K;
5376 AssertLogRelMsgReturn(cbZero <= RT_SIZEOFMEMB(SSMHANDLE, u.Read.abDataBuffer),
5377 ("%#x\n", cbZero), VERR_SSM_INTEGRITY_DECOMPRESSION);
5378
5379 *pcbZero = cbZero;
5380 return VINF_SUCCESS;
5381}
5382
5383
5384/**
5385 * Worker for reading the record header.
5386 *
5387 * It sets pSSM->u.Read.cbRecLeft, pSSM->u.Read.u8TypeAndFlags and
5388 * pSSM->u.Read.fEndOfData. When a termination record is encounter, it will be
5389 * read in full and validated, the fEndOfData indicator is set, and VINF_SUCCESS
5390 * is returned.
5391 *
5392 * @returns VBox status code.
5393 * @param pSSM The saved state handle.
5394 */
5395static int ssmR3DataReadRecHdrV2(PSSMHANDLE pSSM)
5396{
5397 AssertLogRelReturn(!pSSM->u.Read.fEndOfData, VERR_SSM_LOADED_TOO_MUCH);
5398
5399 /*
5400 * Read the two mandatory bytes.
5401 */
5402 uint8_t abHdr[8];
5403 int rc = ssmR3DataReadV2Raw(pSSM, abHdr, 2);
5404 if (RT_FAILURE(rc))
5405 return rc;
5406
5407 /*
5408 * Validate the first byte and check for the termination records.
5409 */
5410 pSSM->u.Read.u8TypeAndFlags = abHdr[0];
5411 AssertLogRelMsgReturn(SSM_REC_ARE_TYPE_AND_FLAGS_VALID(abHdr[0]), ("%#x %#x\n", abHdr[0], abHdr[1]), VERR_SSM_INTEGRITY_REC_HDR);
5412 if ((abHdr[0] & SSM_REC_TYPE_MASK) == SSM_REC_TYPE_TERM)
5413 {
5414 pSSM->u.Read.cbRecLeft = 0;
5415 pSSM->u.Read.fEndOfData = true;
5416 AssertLogRelMsgReturn(abHdr[1] == sizeof(SSMRECTERM) - 2, ("%#x\n", abHdr[1]), VERR_SSM_INTEGRITY_REC_TERM);
5417 AssertLogRelMsgReturn(abHdr[0] & SSM_REC_FLAGS_IMPORTANT, ("%#x\n", abHdr[0]), VERR_SSM_INTEGRITY_REC_TERM);
5418
5419 /* get the rest */
5420 uint32_t u32StreamCRC = ssmR3StrmFinalCRC(&pSSM->Strm);
5421 SSMRECTERM TermRec;
5422 int rc = ssmR3DataReadV2Raw(pSSM, (uint8_t *)&TermRec + 2, sizeof(SSMRECTERM) - 2);
5423 if (RT_FAILURE(rc))
5424 return rc;
5425
5426 /* validate integrity */
5427 AssertLogRelMsgReturn(TermRec.cbUnit == pSSM->offUnit,
5428 ("cbUnit=%#llx offUnit=%#llx\n", TermRec.cbUnit, pSSM->offUnit),
5429 VERR_SSM_INTEGRITY_REC_TERM);
5430 AssertLogRelMsgReturn(!(TermRec.fFlags & ~SSMRECTERM_FLAGS_CRC32), ("%#x\n", TermRec.fFlags), VERR_SSM_INTEGRITY_REC_TERM);
5431 if (!(TermRec.fFlags & SSMRECTERM_FLAGS_CRC32))
5432 AssertLogRelMsgReturn(TermRec.u32StreamCRC == 0, ("%#x\n", TermRec.u32StreamCRC), VERR_SSM_INTEGRITY_REC_TERM);
5433 else if (pSSM->Strm.fChecksummed)
5434 AssertLogRelMsgReturn(TermRec.u32StreamCRC == u32StreamCRC, ("%#x, %#x\n", TermRec.u32StreamCRC, u32StreamCRC),
5435 VERR_SSM_INTEGRITY_REC_TERM_CRC);
5436
5437 Log3(("ssmR3DataReadRecHdrV2: %08llx|%08llx: TERM\n", ssmR3StrmTell(&pSSM->Strm) - sizeof(SSMRECTERM), pSSM->offUnit));
5438 return VINF_SUCCESS;
5439 }
5440
5441 /*
5442 * Figure the size. The 2nd byte is encoded in UTF-8 fashion, so this
5443 * is can be highly enjoyable.
5444 */
5445 uint32_t cbHdr = 2;
5446 uint32_t cb = abHdr[1];
5447 if (!(cb & 0x80))
5448 pSSM->u.Read.cbRecLeft = cb;
5449 else
5450 {
5451 /*
5452 * Need more data. Figure how much and read it.
5453 */
5454 if (!(cb & RT_BIT(5)))
5455 cb = 2;
5456 else if (!(cb & RT_BIT(4)))
5457 cb = 3;
5458 else if (!(cb & RT_BIT(3)))
5459 cb = 4;
5460 else if (!(cb & RT_BIT(2)))
5461 cb = 5;
5462 else if (!(cb & RT_BIT(1)))
5463 cb = 6;
5464 else
5465 AssertLogRelMsgFailedReturn(("Invalid record size byte: %#x\n", cb), VERR_SSM_INTEGRITY_REC_HDR);
5466 cbHdr = cb + 1;
5467
5468 rc = ssmR3DataReadV2Raw(pSSM, &abHdr[2], cb - 1);
5469 if (RT_FAILURE(rc))
5470 return rc;
5471
5472 /*
5473 * Validate what we've read.
5474 */
5475 switch (cb)
5476 {
5477 case 6:
5478 AssertLogRelMsgReturn((abHdr[6] & 0xc0) == 0x80, ("6/%u: %.*Rhxs\n", cb, cb + 1, &abHdr[0]), VERR_SSM_INTEGRITY_REC_HDR);
5479 case 5:
5480 AssertLogRelMsgReturn((abHdr[5] & 0xc0) == 0x80, ("5/%u: %.*Rhxs\n", cb, cb + 1, &abHdr[0]), VERR_SSM_INTEGRITY_REC_HDR);
5481 case 4:
5482 AssertLogRelMsgReturn((abHdr[4] & 0xc0) == 0x80, ("4/%u: %.*Rhxs\n", cb, cb + 1, &abHdr[0]), VERR_SSM_INTEGRITY_REC_HDR);
5483 case 3:
5484 AssertLogRelMsgReturn((abHdr[3] & 0xc0) == 0x80, ("3/%u: %.*Rhxs\n", cb, cb + 1, &abHdr[0]), VERR_SSM_INTEGRITY_REC_HDR);
5485 case 2:
5486 AssertLogRelMsgReturn((abHdr[2] & 0xc0) == 0x80, ("2/%u: %.*Rhxs\n", cb, cb + 1, &abHdr[0]), VERR_SSM_INTEGRITY_REC_HDR);
5487 break;
5488 default:
5489 return VERR_INTERNAL_ERROR;
5490 }
5491
5492 /*
5493 * Decode it and validate the range.
5494 */
5495 switch (cb)
5496 {
5497 case 6:
5498 cb = (abHdr[6] & 0x3f)
5499 | ((uint32_t)(abHdr[5] & 0x3f) << 6)
5500 | ((uint32_t)(abHdr[4] & 0x3f) << 12)
5501 | ((uint32_t)(abHdr[3] & 0x3f) << 18)
5502 | ((uint32_t)(abHdr[2] & 0x3f) << 24)
5503 | ((uint32_t)(abHdr[1] & 0x01) << 30);
5504 AssertLogRelMsgReturn(cb >= 0x04000000 && cb <= 0x7fffffff, ("cb=%#x\n", cb), VERR_SSM_INTEGRITY_REC_HDR);
5505 break;
5506 case 5:
5507 cb = (abHdr[5] & 0x3f)
5508 | ((uint32_t)(abHdr[4] & 0x3f) << 6)
5509 | ((uint32_t)(abHdr[3] & 0x3f) << 12)
5510 | ((uint32_t)(abHdr[2] & 0x3f) << 18)
5511 | ((uint32_t)(abHdr[1] & 0x03) << 24);
5512 AssertLogRelMsgReturn(cb >= 0x00200000 && cb <= 0x03ffffff, ("cb=%#x\n", cb), VERR_SSM_INTEGRITY_REC_HDR);
5513 break;
5514 case 4:
5515 cb = (abHdr[4] & 0x3f)
5516 | ((uint32_t)(abHdr[3] & 0x3f) << 6)
5517 | ((uint32_t)(abHdr[2] & 0x3f) << 12)
5518 | ((uint32_t)(abHdr[1] & 0x07) << 18);
5519 AssertLogRelMsgReturn(cb >= 0x00010000 && cb <= 0x001fffff, ("cb=%#x\n", cb), VERR_SSM_INTEGRITY_REC_HDR);
5520 break;
5521 case 3:
5522 cb = (abHdr[3] & 0x3f)
5523 | ((uint32_t)(abHdr[2] & 0x3f) << 6)
5524 | ((uint32_t)(abHdr[1] & 0x0f) << 12);
5525#if 0 /* disabled to optimize buffering */
5526 AssertLogRelMsgReturn(cb >= 0x00000800 && cb <= 0x0000ffff, ("cb=%#x\n", cb), VERR_SSM_INTEGRITY_REC_HDR);
5527#endif
5528 break;
5529 case 2:
5530 cb = (abHdr[2] & 0x3f)
5531 | ((uint32_t)(abHdr[1] & 0x1f) << 6);
5532#if 0 /* disabled to optimize buffering */
5533 AssertLogRelMsgReturn(cb >= 0x00000080 && cb <= 0x000007ff, ("cb=%#x\n", cb), VERR_SSM_INTEGRITY_REC_HDR);
5534#endif
5535 break;
5536 default:
5537 return VERR_INTERNAL_ERROR;
5538 }
5539
5540 pSSM->u.Read.cbRecLeft = cb;
5541 }
5542
5543 Log3(("ssmR3DataReadRecHdrV2: %08llx|%08llx/%08x: Type=%02x fImportant=%RTbool cbHdr=%u\n",
5544 ssmR3StrmTell(&pSSM->Strm), pSSM->offUnit, pSSM->u.Read.cbRecLeft,
5545 pSSM->u.Read.u8TypeAndFlags & SSM_REC_TYPE_MASK,
5546 !!(pSSM->u.Read.u8TypeAndFlags & SSM_REC_FLAGS_IMPORTANT),
5547 cbHdr
5548 )); NOREF(cbHdr);
5549 return VINF_SUCCESS;
5550}
5551
5552
5553/**
5554 * Buffer miss, do an unbuffered read.
5555 *
5556 * @param pSSM The saved state handle.
5557 * @param pvBuf Where to store the read data.
5558 * @param cbBuf Number of bytes to read.
5559 */
5560static int ssmR3DataReadUnbufferedV2(PSSMHANDLE pSSM, void *pvBuf, size_t cbBuf)
5561{
5562 void const *pvBufOrg = pvBuf; NOREF(pvBufOrg);
5563 size_t const cbBufOrg = cbBuf; NOREF(cbBufOrg);
5564
5565 /*
5566 * Copy out what we've got in the buffer.
5567 */
5568 uint32_t off = pSSM->u.Read.offDataBuffer;
5569 int32_t cbInBuffer = pSSM->u.Read.cbDataBuffer - off;
5570 Log4(("ssmR3DataReadUnbufferedV2: %08llx|%08llx/%08x/%08x: cbBuf=%#x\n", ssmR3StrmTell(&pSSM->Strm), pSSM->offUnit, pSSM->u.Read.cbRecLeft, cbInBuffer, cbBufOrg));
5571 if (cbInBuffer > 0)
5572 {
5573 uint32_t const cbToCopy = (uint32_t)cbInBuffer;
5574 Assert(cbBuf > cbToCopy);
5575 memcpy(pvBuf, &pSSM->u.Read.abDataBuffer[off], cbToCopy);
5576 pvBuf = (uint8_t *)pvBuf + cbToCopy;
5577 cbBuf -= cbToCopy;
5578 pSSM->u.Read.cbDataBuffer = 0;
5579 pSSM->u.Read.offDataBuffer = 0;
5580 }
5581
5582 /*
5583 * Read data.
5584 */
5585 do
5586 {
5587 /*
5588 * Read the next record header if no more data.
5589 */
5590 if (!pSSM->u.Read.cbRecLeft)
5591 {
5592 int rc = ssmR3DataReadRecHdrV2(pSSM);
5593 if (RT_FAILURE(rc))
5594 return pSSM->rc = rc;
5595 }
5596 AssertLogRelMsgReturn(!pSSM->u.Read.fEndOfData, ("cbBuf=%zu", cbBuf), pSSM->rc = VERR_SSM_LOADED_TOO_MUCH);
5597
5598 /*
5599 * Read data from the current record.
5600 */
5601 uint32_t cbToRead;
5602 switch (pSSM->u.Read.u8TypeAndFlags & SSM_REC_TYPE_MASK)
5603 {
5604 case SSM_REC_TYPE_RAW:
5605 {
5606 cbToRead = (uint32_t)RT_MIN(cbBuf, pSSM->u.Read.cbRecLeft);
5607 int rc = ssmR3DataReadV2Raw(pSSM, pvBuf, cbToRead);
5608 if (RT_FAILURE(rc))
5609 return pSSM->rc = rc;
5610 pSSM->u.Read.cbRecLeft -= cbToRead;
5611 break;
5612 }
5613
5614 case SSM_REC_TYPE_RAW_LZF:
5615 {
5616 int rc = ssmR3DataReadV2RawLzfHdr(pSSM, &cbToRead);
5617 if (RT_FAILURE(rc))
5618 return rc;
5619 if (cbToRead <= cbBuf)
5620 {
5621 rc = ssmR3DataReadV2RawLzf(pSSM, pvBuf, cbToRead);
5622 if (RT_FAILURE(rc))
5623 return rc;
5624 }
5625 else
5626 {
5627 /* The output buffer is too small, use the data buffer. */
5628 rc = ssmR3DataReadV2RawLzf(pSSM, &pSSM->u.Read.abDataBuffer[0], cbToRead);
5629 if (RT_FAILURE(rc))
5630 return rc;
5631 pSSM->u.Read.cbDataBuffer = cbToRead;
5632 cbToRead = (uint32_t)cbBuf;
5633 pSSM->u.Read.offDataBuffer = cbToRead;
5634 memcpy(pvBuf, &pSSM->u.Read.abDataBuffer[0], cbToRead);
5635 }
5636 break;
5637 }
5638
5639 case SSM_REC_TYPE_RAW_ZERO:
5640 {
5641 int rc = ssmR3DataReadV2RawZeroHdr(pSSM, &cbToRead);
5642 if (RT_FAILURE(rc))
5643 return rc;
5644 if (cbToRead > cbBuf)
5645 {
5646 /* Spill the remainer into the data buffer. */
5647 memset(&pSSM->u.Read.abDataBuffer[0], 0, cbToRead - cbBuf);
5648 pSSM->u.Read.cbDataBuffer = cbToRead - cbBuf;
5649 pSSM->u.Read.offDataBuffer = 0;
5650 cbToRead = (uint32_t)cbBuf;
5651 }
5652 memset(pvBuf, 0, cbToRead);
5653 break;
5654 }
5655
5656 default:
5657 AssertMsgFailedReturn(("%x\n", pSSM->u.Read.u8TypeAndFlags), VERR_INTERNAL_ERROR_5);
5658 }
5659
5660 cbBuf -= cbToRead;
5661 pvBuf = (uint8_t *)pvBuf + cbToRead;
5662 } while (cbBuf > 0);
5663
5664 Log4(("ssmR3DataReadUnBufferedV2: %08llx|%08llx/%08x/%08x: cbBuf=%#x %.*Rhxs%s\n",
5665 ssmR3StrmTell(&pSSM->Strm), pSSM->offUnit, pSSM->u.Read.cbRecLeft, 0, cbBufOrg, RT_MIN(SSM_LOG_BYTES, cbBufOrg), pvBufOrg, cbBufOrg > SSM_LOG_BYTES ? "..." : ""));
5666 return VINF_SUCCESS;
5667}
5668
5669
5670/**
5671 * Buffer miss, do a buffered read.
5672 *
5673 * @param pSSM The saved state handle.
5674 * @param pvBuf Where to store the read data.
5675 * @param cbBuf Number of bytes to read.
5676 */
5677static int ssmR3DataReadBufferedV2(PSSMHANDLE pSSM, void *pvBuf, size_t cbBuf)
5678{
5679 void const *pvBufOrg = pvBuf; NOREF(pvBufOrg);
5680 size_t const cbBufOrg = cbBuf; NOREF(cbBufOrg);
5681
5682 /*
5683 * Copy out what we've got in the buffer.
5684 */
5685 uint32_t off = pSSM->u.Read.offDataBuffer;
5686 int32_t cbInBuffer = pSSM->u.Read.cbDataBuffer - off;
5687 Log4(("ssmR3DataReadBufferedV2: %08llx|%08llx/%08x/%08x: cbBuf=%#x\n", ssmR3StrmTell(&pSSM->Strm), pSSM->offUnit, pSSM->u.Read.cbRecLeft, cbInBuffer, cbBufOrg));
5688 if (cbInBuffer > 0)
5689 {
5690 uint32_t const cbToCopy = (uint32_t)cbInBuffer;
5691 Assert(cbBuf > cbToCopy);
5692 memcpy(pvBuf, &pSSM->u.Read.abDataBuffer[off], cbToCopy);
5693 pvBuf = (uint8_t *)pvBuf + cbToCopy;
5694 cbBuf -= cbToCopy;
5695 pSSM->u.Read.cbDataBuffer = 0;
5696 pSSM->u.Read.offDataBuffer = 0;
5697 }
5698
5699 /*
5700 * Buffer more data.
5701 */
5702 do
5703 {
5704 /*
5705 * Read the next record header if no more data.
5706 */
5707 if (!pSSM->u.Read.cbRecLeft)
5708 {
5709 int rc = ssmR3DataReadRecHdrV2(pSSM);
5710 if (RT_FAILURE(rc))
5711 return pSSM->rc = rc;
5712 }
5713 AssertLogRelMsgReturn(!pSSM->u.Read.fEndOfData, ("cbBuf=%zu", cbBuf), pSSM->rc = VERR_SSM_LOADED_TOO_MUCH);
5714
5715 /*
5716 * Read data from the current record.
5717 * LATER: optimize by reading directly into the output buffer for some cases.
5718 */
5719 uint32_t cbToRead;
5720 switch (pSSM->u.Read.u8TypeAndFlags & SSM_REC_TYPE_MASK)
5721 {
5722 case SSM_REC_TYPE_RAW:
5723 {
5724 cbToRead = RT_MIN(sizeof(pSSM->u.Read.abDataBuffer), pSSM->u.Read.cbRecLeft);
5725 int rc = ssmR3DataReadV2Raw(pSSM, &pSSM->u.Read.abDataBuffer[0], cbToRead);
5726 if (RT_FAILURE(rc))
5727 return pSSM->rc = rc;
5728 pSSM->u.Read.cbRecLeft -= cbToRead;
5729 pSSM->u.Read.cbDataBuffer = cbToRead;
5730 break;
5731 }
5732
5733 case SSM_REC_TYPE_RAW_LZF:
5734 {
5735 int rc = ssmR3DataReadV2RawLzfHdr(pSSM, &cbToRead);
5736 if (RT_FAILURE(rc))
5737 return rc;
5738 rc = ssmR3DataReadV2RawLzf(pSSM, &pSSM->u.Read.abDataBuffer[0], cbToRead);
5739 if (RT_FAILURE(rc))
5740 return rc;
5741 pSSM->u.Read.cbDataBuffer = cbToRead;
5742 break;
5743 }
5744
5745 case SSM_REC_TYPE_RAW_ZERO:
5746 {
5747 int rc = ssmR3DataReadV2RawZeroHdr(pSSM, &cbToRead);
5748 if (RT_FAILURE(rc))
5749 return rc;
5750 memset(&pSSM->u.Read.abDataBuffer[0], 0, cbToRead);
5751 pSSM->u.Read.cbDataBuffer = cbToRead;
5752 break;
5753 }
5754
5755 default:
5756 AssertMsgFailedReturn(("%x\n", pSSM->u.Read.u8TypeAndFlags), VERR_INTERNAL_ERROR_5);
5757 }
5758 /*pSSM->u.Read.offDataBuffer = 0;*/
5759
5760 /*
5761 * Copy data from the buffer.
5762 */
5763 uint32_t cbToCopy = (uint32_t)RT_MIN(cbBuf, cbToRead);
5764 memcpy(pvBuf, &pSSM->u.Read.abDataBuffer[0], cbToCopy);
5765 cbBuf -= cbToCopy;
5766 pvBuf = (uint8_t *)pvBuf + cbToCopy;
5767 pSSM->u.Read.offDataBuffer = cbToCopy;
5768 } while (cbBuf > 0);
5769
5770 Log4(("ssmR3DataReadBufferedV2: %08llx|%08llx/%08x/%08x: cbBuf=%#x %.*Rhxs%s\n",
5771 ssmR3StrmTell(&pSSM->Strm), pSSM->offUnit, pSSM->u.Read.cbRecLeft, pSSM->u.Read.cbDataBuffer - pSSM->u.Read.offDataBuffer,
5772 cbBufOrg, RT_MIN(SSM_LOG_BYTES, cbBufOrg), pvBufOrg, cbBufOrg > SSM_LOG_BYTES ? "..." : ""));
5773 return VINF_SUCCESS;
5774}
5775
5776
5777/**
5778 * Inlined worker that handles format checks and buffered reads.
5779 *
5780 * @param pSSM The saved state handle.
5781 * @param pvBuf Where to store the read data.
5782 * @param cbBuf Number of bytes to read.
5783 */
5784DECLINLINE(int) ssmR3DataRead(PSSMHANDLE pSSM, void *pvBuf, size_t cbBuf)
5785{
5786 /*
5787 * Fend off previous errors and V1 data units.
5788 */
5789 if (RT_FAILURE(pSSM->rc))
5790 return pSSM->rc;
5791 if (RT_UNLIKELY(pSSM->u.Read.uFmtVerMajor == 1))
5792 return ssmR3DataReadV1(pSSM, pvBuf, cbBuf);
5793
5794 /*
5795 * Check if the requested data is buffered.
5796 */
5797 uint32_t off = pSSM->u.Read.offDataBuffer;
5798 if ( off + cbBuf > pSSM->u.Read.cbDataBuffer
5799 || cbBuf > sizeof(pSSM->u.Read.abDataBuffer))
5800 {
5801 if (cbBuf <= sizeof(pSSM->u.Read.abDataBuffer) / 8)
5802 return ssmR3DataReadBufferedV2(pSSM, pvBuf, cbBuf);
5803 return ssmR3DataReadUnbufferedV2(pSSM, pvBuf, cbBuf);
5804 }
5805
5806 memcpy(pvBuf, &pSSM->u.Read.abDataBuffer[off], cbBuf);
5807 pSSM->u.Read.offDataBuffer = off + (uint32_t)cbBuf;
5808 Log4((cbBuf
5809 ? "ssmR3DataRead: %08llx|%08llx/%08x/%08x: cbBuf=%#x %.*Rhxs%s\n"
5810 : "ssmR3DataRead: %08llx|%08llx/%08x/%08x: cbBuf=%#x\n",
5811 ssmR3StrmTell(&pSSM->Strm), pSSM->offUnit, pSSM->u.Read.cbRecLeft, pSSM->u.Read.cbDataBuffer - pSSM->u.Read.offDataBuffer,
5812 cbBuf, RT_MIN(SSM_LOG_BYTES, cbBuf), pvBuf, cbBuf > SSM_LOG_BYTES ? "..." : ""));
5813
5814 return VINF_SUCCESS;
5815}
5816
5817
5818/**
5819 * Gets a structure.
5820 *
5821 * @returns VBox status code.
5822 * @param pSSM The saved state handle.
5823 * @param pvStruct The structure address.
5824 * @param paFields The array of structure fields descriptions.
5825 * The array must be terminated by a SSMFIELD_ENTRY_TERM().
5826 */
5827VMMR3DECL(int) SSMR3GetStruct(PSSMHANDLE pSSM, void *pvStruct, PCSSMFIELD paFields)
5828{
5829 SSM_ASSERT_READABLE_RET(pSSM);
5830 SSM_CHECK_CANCELLED_RET(pSSM);
5831 AssertPtr(pvStruct);
5832 AssertPtr(paFields);
5833
5834 /* begin marker. */
5835 uint32_t u32Magic;
5836 int rc = SSMR3GetU32(pSSM, &u32Magic);
5837 if (RT_FAILURE(rc))
5838 return rc;
5839 AssertMsgReturn(u32Magic == SSMR3STRUCT_BEGIN, ("u32Magic=%#RX32\n", u32Magic), VERR_SSM_STRUCTURE_MAGIC);
5840
5841 /* get the fields */
5842 for (PCSSMFIELD pCur = paFields;
5843 pCur->cb != UINT32_MAX && pCur->off != UINT32_MAX;
5844 pCur++)
5845 {
5846 uint8_t *pbField = (uint8_t *)pvStruct + pCur->off;
5847 switch ((uintptr_t)pCur->pfnGetPutOrTransformer)
5848 {
5849 case SSMFIELDTRANS_NO_TRANSFORMATION:
5850 rc = ssmR3DataRead(pSSM, pbField, pCur->cb);
5851 break;
5852
5853 case SSMFIELDTRANS_GCPTR:
5854 AssertMsgReturn(pCur->cb == sizeof(RTGCPTR), ("%#x (%s)\n", pCur->cb, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
5855 rc = SSMR3GetGCPtr(pSSM, (PRTGCPTR)pbField);
5856 break;
5857
5858 case SSMFIELDTRANS_GCPHYS:
5859 AssertMsgReturn(pCur->cb == sizeof(RTGCPHYS), ("%#x (%s)\n", pCur->cb, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
5860 rc = SSMR3GetGCPhys(pSSM, (PRTGCPHYS)pbField);
5861 break;
5862
5863 case SSMFIELDTRANS_RCPTR:
5864 AssertMsgReturn(pCur->cb == sizeof(RTRCPTR), ("%#x (%s)\n", pCur->cb, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
5865 rc = SSMR3GetRCPtr(pSSM, (PRTRCPTR)pbField);
5866 break;
5867
5868 case SSMFIELDTRANS_RCPTR_ARRAY:
5869 {
5870 uint32_t const cEntries = pCur->cb / sizeof(RTRCPTR);
5871 AssertMsgReturn(pCur->cb == cEntries * sizeof(RTRCPTR) && cEntries, ("%#x (%s)\n", pCur->cb, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
5872 rc = VINF_SUCCESS;
5873 for (uint32_t i = 0; i < cEntries && RT_SUCCESS(rc); i++)
5874 rc = SSMR3GetRCPtr(pSSM, &((PRTRCPTR)pbField)[i]);
5875 break;
5876 }
5877
5878 default:
5879 AssertMsgFailedReturn(("%#x\n", pCur->pfnGetPutOrTransformer), VERR_SSM_FIELD_COMPLEX);
5880 }
5881 if (RT_FAILURE(rc))
5882 return rc;
5883 }
5884
5885 /* end marker */
5886 rc = SSMR3GetU32(pSSM, &u32Magic);
5887 if (RT_FAILURE(rc))
5888 return rc;
5889 AssertMsgReturn(u32Magic == SSMR3STRUCT_END, ("u32Magic=%#RX32\n", u32Magic), VERR_SSM_STRUCTURE_MAGIC);
5890 return rc;
5891}
5892
5893
5894/**
5895 * SSMR3GetStructEx helper that gets a HCPTR that is used as a NULL indicator.
5896 *
5897 * @returns VBox status code.
5898 *
5899 * @param pSSM The saved state handle.
5900 * @param ppv Where to return the value (0/1).
5901 * @param fFlags SSMSTRUCT_FLAGS_XXX.
5902 */
5903DECLINLINE(int) ssmR3GetHCPtrNI(PSSMHANDLE pSSM, void **ppv, uint32_t fFlags)
5904{
5905 int rc;
5906 if (fFlags & SSMSTRUCT_FLAGS_DONT_IGNORE)
5907 {
5908 if (ssmR3GetHostBits(pSSM) == 64)
5909 {
5910 uint64_t u;
5911 rc = ssmR3DataRead(pSSM, &u, sizeof(u));
5912 if (RT_SUCCESS(rc))
5913 *ppv = (void *)(u ? 1 : 0);
5914 }
5915 else
5916 {
5917 uint32_t u;
5918 rc = ssmR3DataRead(pSSM, &u, sizeof(u));
5919 if (RT_SUCCESS(rc))
5920 *ppv = (void *)(u ? 1 : 0);
5921 }
5922 }
5923 else
5924 {
5925 bool f;
5926 rc = SSMR3GetBool(pSSM, &f);
5927 if (RT_SUCCESS(rc))
5928 *ppv = (void *)(f ? 1 : 0);
5929 }
5930 return rc;
5931}
5932
5933
5934/**
5935 * Guts a structure, extended API.
5936 *
5937 * @returns VBox status code.
5938 * @param pSSM The saved state handle.
5939 * @param pvStruct The structure address.
5940 * @param cbStruct The size of the struct (use for validation only).
5941 * @param fFlags Combination of SSMSTRUCT_FLAGS_XXX defines.
5942 * @param paFields The array of structure fields descriptions. The
5943 * array must be terminated by a SSMFIELD_ENTRY_TERM().
5944 * @param pvUser User argument for any callbacks that paFields might
5945 * contain.
5946 */
5947VMMR3DECL(int) SSMR3GetStructEx(PSSMHANDLE pSSM, void *pvStruct, size_t cbStruct,
5948 uint32_t fFlags, PCSSMFIELD paFields, void *pvUser)
5949{
5950 int rc;
5951 uint32_t u32Magic;
5952
5953 /*
5954 * Validation.
5955 */
5956 SSM_ASSERT_READABLE_RET(pSSM);
5957 SSM_CHECK_CANCELLED_RET(pSSM);
5958 AssertMsgReturn(!(fFlags & ~SSMSTRUCT_FLAGS_VALID_MASK), ("%#x\n", fFlags), VERR_INVALID_PARAMETER);
5959 AssertPtr(pvStruct);
5960 AssertPtr(paFields);
5961
5962 /*
5963 * Begin marker.
5964 */
5965 if (!(fFlags & SSMSTRUCT_FLAGS_NO_MARKERS))
5966 {
5967 rc = SSMR3GetU32(pSSM, &u32Magic);
5968 if (RT_FAILURE(rc))
5969 return rc;
5970 AssertMsgReturn(u32Magic == SSMR3STRUCT_BEGIN, ("u32Magic=%#RX32\n", u32Magic), VERR_SSM_STRUCTURE_MAGIC);
5971 }
5972
5973 /*
5974 * Put the fields
5975 */
5976 uint32_t off = 0;
5977 for (PCSSMFIELD pCur = paFields;
5978 pCur->cb != UINT32_MAX && pCur->off != UINT32_MAX;
5979 pCur++)
5980 {
5981 uint32_t const offField = !SSMFIELDTRANS_IS_PADDING(pCur->pfnGetPutOrTransformer) || pCur->off != UINT32_MAX / 2
5982 ? pCur->off
5983 : off;
5984 uint32_t const cbField = !SSMFIELDTRANS_IS_PADDING(pCur->pfnGetPutOrTransformer)
5985 ? pCur->cb
5986 : RT_HIWORD(pCur->cb);
5987 AssertMsgReturn( cbField <= cbStruct
5988 && offField + cbField <= cbStruct
5989 && offField + cbField >= offField,
5990 ("off=%#x cb=%#x cbStruct=%#x (%s)\n", cbField, offField, cbStruct, pCur->pszName),
5991 VERR_SSM_FIELD_OUT_OF_BOUNDS);
5992 AssertMsgReturn( !(fFlags & SSMSTRUCT_FLAGS_FULL_STRUCT)
5993 || off == offField,
5994 ("off=%#x offField=%#x (%s)\n", off, offField, pCur->pszName),
5995 VERR_SSM_FIELD_NOT_CONSECUTIVE);
5996
5997 uint8_t *pbField = (uint8_t *)pvStruct + offField;
5998 switch ((uintptr_t)pCur->pfnGetPutOrTransformer)
5999 {
6000 case SSMFIELDTRANS_NO_TRANSFORMATION:
6001 rc = ssmR3DataRead(pSSM, pbField, cbField);
6002 break;
6003
6004 case SSMFIELDTRANS_GCPTR:
6005 AssertMsgReturn(cbField == sizeof(RTGCPTR), ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
6006 rc = SSMR3GetGCPtr(pSSM, (PRTGCPTR)pbField);
6007 break;
6008
6009 case SSMFIELDTRANS_GCPHYS:
6010 AssertMsgReturn(cbField == sizeof(RTGCPHYS), ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
6011 rc = SSMR3GetGCPhys(pSSM, (PRTGCPHYS)pbField);
6012 break;
6013
6014 case SSMFIELDTRANS_RCPTR:
6015 AssertMsgReturn(cbField == sizeof(RTRCPTR), ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
6016 rc = SSMR3GetRCPtr(pSSM, (PRTRCPTR)pbField);
6017 break;
6018
6019 case SSMFIELDTRANS_RCPTR_ARRAY:
6020 {
6021 uint32_t const cEntries = cbField / sizeof(RTRCPTR);
6022 AssertMsgReturn(cbField == cEntries * sizeof(RTRCPTR) && cEntries, ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
6023 rc = VINF_SUCCESS;
6024 for (uint32_t i = 0; i < cEntries && RT_SUCCESS(rc); i++)
6025 rc = SSMR3GetRCPtr(pSSM, &((PRTRCPTR)pbField)[i]);
6026 break;
6027 }
6028
6029 case SSMFIELDTRANS_HCPTR_NI:
6030 AssertMsgReturn(cbField == sizeof(void *), ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
6031 rc = ssmR3GetHCPtrNI(pSSM, (void **)pbField, fFlags);
6032 break;
6033
6034 case SSMFIELDTRANS_HCPTR_NI_ARRAY:
6035 {
6036 uint32_t const cEntries = cbField / sizeof(void *);
6037 AssertMsgReturn(cbField == cEntries * sizeof(void *) && cEntries, ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
6038 rc = VINF_SUCCESS;
6039 for (uint32_t i = 0; i < cEntries && RT_SUCCESS(rc); i++)
6040 rc = ssmR3GetHCPtrNI(pSSM, &((void **)pbField)[i], fFlags);
6041 break;
6042 }
6043
6044 case SSMFIELDTRANS_IGNORE:
6045 if (fFlags & SSMSTRUCT_FLAGS_DONT_IGNORE)
6046 rc = SSMR3Skip(pSSM, cbField);
6047 break;
6048
6049 case SSMFIELDTRANS_IGN_RCPTR:
6050 AssertMsgReturn(cbField == sizeof(RTRCPTR), ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
6051 if (fFlags & SSMSTRUCT_FLAGS_DONT_IGNORE)
6052 rc = SSMR3Skip(pSSM, sizeof(RTRCPTR));
6053 break;
6054
6055 case SSMFIELDTRANS_IGN_HCPTR:
6056 AssertMsgReturn(cbField == sizeof(void *), ("%#x (%s)\n", cbField, pCur->pszName), VERR_SSM_FIELD_INVALID_SIZE);
6057 if (fFlags & SSMSTRUCT_FLAGS_DONT_IGNORE)
6058 rc = SSMR3Skip(pSSM, ssmR3GetHostBits(pSSM) / 8);
6059 break;
6060
6061 case SSMFIELDTRANS_PAD_HC:
6062 case SSMFIELDTRANS_PAD_HC32:
6063 case SSMFIELDTRANS_PAD_HC64:
6064 case SSMFIELDTRANS_PAD_HC_AUTO:
6065 case SSMFIELDTRANS_PAD_MSC32_AUTO:
6066 {
6067 uint32_t cb32 = RT_BYTE1(pCur->cb);
6068 uint32_t cb64 = RT_BYTE2(pCur->cb);
6069 uint32_t cbCtx = HC_ARCH_BITS == 64
6070 || ( (uintptr_t)pCur->pfnGetPutOrTransformer == SSMFIELDTRANS_PAD_MSC32_AUTO
6071 && !SSM_HOST_IS_MSC_32)
6072 ? cb64 : cb32;
6073 uint32_t cbSaved = ssmR3GetHostBits(pSSM) == 64
6074 || ( (uintptr_t)pCur->pfnGetPutOrTransformer == SSMFIELDTRANS_PAD_MSC32_AUTO
6075 && !ssmR3IsHostMsc32(pSSM))
6076 ? cb64 : cb32;
6077 AssertMsgReturn( cbField == cbCtx
6078 && ( ( pCur->off == UINT32_MAX / 2
6079 && ( cbField == 0
6080 || (uintptr_t)pCur->pfnGetPutOrTransformer == SSMFIELDTRANS_PAD_HC_AUTO
6081 || (uintptr_t)pCur->pfnGetPutOrTransformer == SSMFIELDTRANS_PAD_MSC32_AUTO
6082 )
6083 )
6084 || (pCur->off != UINT32_MAX / 2 && cbField != 0)
6085 )
6086 , ("cbField=%#x cb32=%#x cb64=%#x HC_ARCH_BITS=%u cbCtx=%#x cbSaved=%#x off=%#x\n",
6087 cbField, cb32, cb64, HC_ARCH_BITS, cbCtx, cbSaved, pCur->off),
6088 VERR_SSM_FIELD_INVALID_PADDING_SIZE);
6089 if (fFlags & SSMSTRUCT_FLAGS_DONT_IGNORE)
6090 rc = SSMR3Skip(pSSM, cbSaved);
6091 break;
6092 }
6093
6094 default:
6095 AssertPtrReturn(pCur->pfnGetPutOrTransformer, VERR_SSM_FIELD_INVALID_CALLBACK);
6096 rc = pCur->pfnGetPutOrTransformer(pSSM, pCur, pvStruct, fFlags, true /*fGetOrPut*/, pvUser);
6097 break;
6098 }
6099 if (RT_FAILURE(rc))
6100 return rc;
6101
6102 off = offField + cbField;
6103 }
6104 AssertMsgReturn( !(fFlags & SSMSTRUCT_FLAGS_FULL_STRUCT)
6105 || off == cbStruct,
6106 ("off=%#x cbStruct=%#x\n", off, cbStruct),
6107 VERR_SSM_FIELD_NOT_CONSECUTIVE);
6108
6109 /*
6110 * End marker
6111 */
6112 if (!(fFlags & SSMSTRUCT_FLAGS_NO_MARKERS))
6113 {
6114 rc = SSMR3GetU32(pSSM, &u32Magic);
6115 if (RT_FAILURE(rc))
6116 return rc;
6117 AssertMsgReturn(u32Magic == SSMR3STRUCT_END, ("u32Magic=%#RX32\n", u32Magic), VERR_SSM_STRUCTURE_MAGIC);
6118 }
6119
6120 return VINF_SUCCESS;
6121}
6122
6123
6124/**
6125 * Loads a boolean item from the current data unit.
6126 *
6127 * @returns VBox status.
6128 * @param pSSM The saved state handle.
6129 * @param pfBool Where to store the item.
6130 */
6131VMMR3DECL(int) SSMR3GetBool(PSSMHANDLE pSSM, bool *pfBool)
6132{
6133 SSM_ASSERT_READABLE_RET(pSSM);
6134 SSM_CHECK_CANCELLED_RET(pSSM);
6135 uint8_t u8; /* see SSMR3PutBool */
6136 int rc = ssmR3DataRead(pSSM, &u8, sizeof(u8));
6137 if (RT_SUCCESS(rc))
6138 {
6139 Assert(u8 <= 1);
6140 *pfBool = !!u8;
6141 }
6142 return rc;
6143}
6144
6145
6146/**
6147 * Loads a 8-bit unsigned integer item from the current data unit.
6148 *
6149 * @returns VBox status.
6150 * @param pSSM The saved state handle.
6151 * @param pu8 Where to store the item.
6152 */
6153VMMR3DECL(int) SSMR3GetU8(PSSMHANDLE pSSM, uint8_t *pu8)
6154{
6155 SSM_ASSERT_READABLE_RET(pSSM);
6156 SSM_CHECK_CANCELLED_RET(pSSM);
6157 return ssmR3DataRead(pSSM, pu8, sizeof(*pu8));
6158}
6159
6160
6161/**
6162 * Loads a 8-bit signed integer item from the current data unit.
6163 *
6164 * @returns VBox status.
6165 * @param pSSM The saved state handle.
6166 * @param pi8 Where to store the item.
6167 */
6168VMMR3DECL(int) SSMR3GetS8(PSSMHANDLE pSSM, int8_t *pi8)
6169{
6170 SSM_ASSERT_READABLE_RET(pSSM);
6171 SSM_CHECK_CANCELLED_RET(pSSM);
6172 return ssmR3DataRead(pSSM, pi8, sizeof(*pi8));
6173}
6174
6175
6176/**
6177 * Loads a 16-bit unsigned integer item from the current data unit.
6178 *
6179 * @returns VBox status.
6180 * @param pSSM The saved state handle.
6181 * @param pu16 Where to store the item.
6182 */
6183VMMR3DECL(int) SSMR3GetU16(PSSMHANDLE pSSM, uint16_t *pu16)
6184{
6185 SSM_ASSERT_READABLE_RET(pSSM);
6186 SSM_CHECK_CANCELLED_RET(pSSM);
6187 return ssmR3DataRead(pSSM, pu16, sizeof(*pu16));
6188}
6189
6190
6191/**
6192 * Loads a 16-bit signed integer item from the current data unit.
6193 *
6194 * @returns VBox status.
6195 * @param pSSM The saved state handle.
6196 * @param pi16 Where to store the item.
6197 */
6198VMMR3DECL(int) SSMR3GetS16(PSSMHANDLE pSSM, int16_t *pi16)
6199{
6200 SSM_ASSERT_READABLE_RET(pSSM);
6201 SSM_CHECK_CANCELLED_RET(pSSM);
6202 return ssmR3DataRead(pSSM, pi16, sizeof(*pi16));
6203}
6204
6205
6206/**
6207 * Loads a 32-bit unsigned integer item from the current data unit.
6208 *
6209 * @returns VBox status.
6210 * @param pSSM The saved state handle.
6211 * @param pu32 Where to store the item.
6212 */
6213VMMR3DECL(int) SSMR3GetU32(PSSMHANDLE pSSM, uint32_t *pu32)
6214{
6215 SSM_ASSERT_READABLE_RET(pSSM);
6216 SSM_CHECK_CANCELLED_RET(pSSM);
6217 return ssmR3DataRead(pSSM, pu32, sizeof(*pu32));
6218}
6219
6220
6221/**
6222 * Loads a 32-bit signed integer item from the current data unit.
6223 *
6224 * @returns VBox status.
6225 * @param pSSM The saved state handle.
6226 * @param pi32 Where to store the item.
6227 */
6228VMMR3DECL(int) SSMR3GetS32(PSSMHANDLE pSSM, int32_t *pi32)
6229{
6230 SSM_ASSERT_READABLE_RET(pSSM);
6231 SSM_CHECK_CANCELLED_RET(pSSM);
6232 return ssmR3DataRead(pSSM, pi32, sizeof(*pi32));
6233}
6234
6235
6236/**
6237 * Loads a 64-bit unsigned integer item from the current data unit.
6238 *
6239 * @returns VBox status.
6240 * @param pSSM The saved state handle.
6241 * @param pu64 Where to store the item.
6242 */
6243VMMR3DECL(int) SSMR3GetU64(PSSMHANDLE pSSM, uint64_t *pu64)
6244{
6245 SSM_ASSERT_READABLE_RET(pSSM);
6246 SSM_CHECK_CANCELLED_RET(pSSM);
6247 return ssmR3DataRead(pSSM, pu64, sizeof(*pu64));
6248}
6249
6250
6251/**
6252 * Loads a 64-bit signed integer item from the current data unit.
6253 *
6254 * @returns VBox status.
6255 * @param pSSM The saved state handle.
6256 * @param pi64 Where to store the item.
6257 */
6258VMMR3DECL(int) SSMR3GetS64(PSSMHANDLE pSSM, int64_t *pi64)
6259{
6260 SSM_ASSERT_READABLE_RET(pSSM);
6261 SSM_CHECK_CANCELLED_RET(pSSM);
6262 return ssmR3DataRead(pSSM, pi64, sizeof(*pi64));
6263}
6264
6265
6266/**
6267 * Loads a 128-bit unsigned integer item from the current data unit.
6268 *
6269 * @returns VBox status.
6270 * @param pSSM The saved state handle.
6271 * @param pu128 Where to store the item.
6272 */
6273VMMR3DECL(int) SSMR3GetU128(PSSMHANDLE pSSM, uint128_t *pu128)
6274{
6275 SSM_ASSERT_READABLE_RET(pSSM);
6276 SSM_CHECK_CANCELLED_RET(pSSM);
6277 return ssmR3DataRead(pSSM, pu128, sizeof(*pu128));
6278}
6279
6280
6281/**
6282 * Loads a 128-bit signed integer item from the current data unit.
6283 *
6284 * @returns VBox status.
6285 * @param pSSM The saved state handle.
6286 * @param pi128 Where to store the item.
6287 */
6288VMMR3DECL(int) SSMR3GetS128(PSSMHANDLE pSSM, int128_t *pi128)
6289{
6290 SSM_ASSERT_READABLE_RET(pSSM);
6291 SSM_CHECK_CANCELLED_RET(pSSM);
6292 return ssmR3DataRead(pSSM, pi128, sizeof(*pi128));
6293}
6294
6295
6296/**
6297 * Loads a VBox unsigned integer item from the current data unit.
6298 *
6299 * @returns VBox status.
6300 * @param pSSM The saved state handle.
6301 * @param pu Where to store the integer.
6302 */
6303VMMR3DECL(int) SSMR3GetUInt(PSSMHANDLE pSSM, PRTUINT pu)
6304{
6305 SSM_ASSERT_READABLE_RET(pSSM);
6306 SSM_CHECK_CANCELLED_RET(pSSM);
6307 return ssmR3DataRead(pSSM, pu, sizeof(*pu));
6308}
6309
6310
6311/**
6312 * Loads a VBox signed integer item from the current data unit.
6313 *
6314 * @returns VBox status.
6315 * @param pSSM The saved state handle.
6316 * @param pi Where to store the integer.
6317 */
6318VMMR3DECL(int) SSMR3GetSInt(PSSMHANDLE pSSM, PRTINT pi)
6319{
6320 SSM_ASSERT_READABLE_RET(pSSM);
6321 SSM_CHECK_CANCELLED_RET(pSSM);
6322 return ssmR3DataRead(pSSM, pi, sizeof(*pi));
6323}
6324
6325
6326/**
6327 * Loads a GC natural unsigned integer item from the current data unit.
6328 *
6329 * @returns VBox status.
6330 * @param pSSM The saved state handle.
6331 * @param pu Where to store the integer.
6332 *
6333 * @deprecated Silly type with an incorrect size, don't use it.
6334 */
6335VMMR3DECL(int) SSMR3GetGCUInt(PSSMHANDLE pSSM, PRTGCUINT pu)
6336{
6337 AssertCompile(sizeof(RTGCPTR) == sizeof(*pu));
6338 return SSMR3GetGCPtr(pSSM, (PRTGCPTR)pu);
6339}
6340
6341
6342/**
6343 * Loads a GC unsigned integer register item from the current data unit.
6344 *
6345 * @returns VBox status.
6346 * @param pSSM The saved state handle.
6347 * @param pu Where to store the integer.
6348 */
6349VMMR3DECL(int) SSMR3GetGCUIntReg(PSSMHANDLE pSSM, PRTGCUINTREG pu)
6350{
6351 AssertCompile(sizeof(RTGCPTR) == sizeof(*pu));
6352 return SSMR3GetGCPtr(pSSM, (PRTGCPTR)pu);
6353}
6354
6355
6356/**
6357 * Loads a 32 bits GC physical address item from the current data unit.
6358 *
6359 * @returns VBox status.
6360 * @param pSSM The saved state handle.
6361 * @param pGCPhys Where to store the GC physical address.
6362 */
6363VMMR3DECL(int) SSMR3GetGCPhys32(PSSMHANDLE pSSM, PRTGCPHYS32 pGCPhys)
6364{
6365 SSM_ASSERT_READABLE_RET(pSSM);
6366 SSM_CHECK_CANCELLED_RET(pSSM);
6367 return ssmR3DataRead(pSSM, pGCPhys, sizeof(*pGCPhys));
6368}
6369
6370
6371/**
6372 * Loads a 64 bits GC physical address item from the current data unit.
6373 *
6374 * @returns VBox status.
6375 * @param pSSM The saved state handle.
6376 * @param pGCPhys Where to store the GC physical address.
6377 */
6378VMMR3DECL(int) SSMR3GetGCPhys64(PSSMHANDLE pSSM, PRTGCPHYS64 pGCPhys)
6379{
6380 SSM_ASSERT_READABLE_RET(pSSM);
6381 SSM_CHECK_CANCELLED_RET(pSSM);
6382 return ssmR3DataRead(pSSM, pGCPhys, sizeof(*pGCPhys));
6383}
6384
6385
6386/**
6387 * Loads a GC physical address item from the current data unit.
6388 *
6389 * @returns VBox status.
6390 * @param pSSM The saved state handle.
6391 * @param pGCPhys Where to store the GC physical address.
6392 */
6393VMMR3DECL(int) SSMR3GetGCPhys(PSSMHANDLE pSSM, PRTGCPHYS pGCPhys)
6394{
6395 SSM_ASSERT_READABLE_RET(pSSM);
6396 SSM_CHECK_CANCELLED_RET(pSSM);
6397
6398 /*
6399 * Default size?
6400 */
6401 if (RT_LIKELY(sizeof(*pGCPhys) == pSSM->u.Read.cbGCPhys))
6402 return ssmR3DataRead(pSSM, pGCPhys, sizeof(*pGCPhys));
6403
6404 /*
6405 * Fiddly.
6406 */
6407 Assert(sizeof(*pGCPhys) == sizeof(uint64_t) || sizeof(*pGCPhys) == sizeof(uint32_t));
6408 Assert(pSSM->u.Read.cbGCPhys == sizeof(uint64_t) || pSSM->u.Read.cbGCPhys == sizeof(uint32_t));
6409 if (pSSM->u.Read.cbGCPhys == sizeof(uint64_t))
6410 {
6411 /* 64-bit saved, 32-bit load: try truncate it. */
6412 uint64_t u64;
6413 int rc = ssmR3DataRead(pSSM, &u64, sizeof(uint64_t));
6414 if (RT_FAILURE(rc))
6415 return rc;
6416 if (u64 >= _4G)
6417 return VERR_SSM_GCPHYS_OVERFLOW;
6418 *pGCPhys = (RTGCPHYS)u64;
6419 return rc;
6420 }
6421
6422 /* 32-bit saved, 64-bit load: clear the high part. */
6423 *pGCPhys = 0;
6424 return ssmR3DataRead(pSSM, pGCPhys, sizeof(uint32_t));
6425}
6426
6427
6428/**
6429 * Loads a GC virtual address item from the current data unit.
6430 *
6431 * Only applies to in the 1.1 format:
6432 * - SSMR3GetGCPtr
6433 * - SSMR3GetGCUIntPtr
6434 * - SSMR3GetGCUInt
6435 * - SSMR3GetGCUIntReg
6436 *
6437 * Put functions are not affected.
6438 *
6439 * @returns VBox status.
6440 * @param pSSM The saved state handle.
6441 * @param cbGCPtr Size of RTGCPTR
6442 *
6443 * @remarks This interface only works with saved state version 1.1, if the
6444 * format isn't 1.1 the call will be ignored.
6445 */
6446VMMR3_INT_DECL(int) SSMR3SetGCPtrSize(PSSMHANDLE pSSM, unsigned cbGCPtr)
6447{
6448 Assert(cbGCPtr == sizeof(RTGCPTR32) || cbGCPtr == sizeof(RTGCPTR64));
6449 if (!pSSM->u.Read.fFixedGCPtrSize)
6450 {
6451 Log(("SSMR3SetGCPtrSize: %u -> %u bytes\n", pSSM->u.Read.cbGCPtr, cbGCPtr));
6452 pSSM->u.Read.cbGCPtr = cbGCPtr;
6453 pSSM->u.Read.fFixedGCPtrSize = true;
6454 }
6455 else if ( pSSM->u.Read.cbGCPtr != cbGCPtr
6456 && pSSM->u.Read.uFmtVerMajor == 1
6457 && pSSM->u.Read.uFmtVerMinor == 1)
6458 AssertMsgFailed(("SSMR3SetGCPtrSize: already fixed at %u bytes; requested %u bytes\n", pSSM->u.Read.cbGCPtr, cbGCPtr));
6459
6460 return VINF_SUCCESS;
6461}
6462
6463
6464/**
6465 * Loads a GC virtual address item from the current data unit.
6466 *
6467 * @returns VBox status.
6468 * @param pSSM The saved state handle.
6469 * @param pGCPtr Where to store the GC virtual address.
6470 */
6471VMMR3DECL(int) SSMR3GetGCPtr(PSSMHANDLE pSSM, PRTGCPTR pGCPtr)
6472{
6473 SSM_ASSERT_READABLE_RET(pSSM);
6474 SSM_CHECK_CANCELLED_RET(pSSM);
6475
6476 /*
6477 * Default size?
6478 */
6479 if (RT_LIKELY(sizeof(*pGCPtr) == pSSM->u.Read.cbGCPtr))
6480 return ssmR3DataRead(pSSM, pGCPtr, sizeof(*pGCPtr));
6481
6482 /*
6483 * Fiddly.
6484 */
6485 Assert(sizeof(*pGCPtr) == sizeof(uint64_t) || sizeof(*pGCPtr) == sizeof(uint32_t));
6486 Assert(pSSM->u.Read.cbGCPtr == sizeof(uint64_t) || pSSM->u.Read.cbGCPtr == sizeof(uint32_t));
6487 if (pSSM->u.Read.cbGCPtr == sizeof(uint64_t))
6488 {
6489 /* 64-bit saved, 32-bit load: try truncate it. */
6490 uint64_t u64;
6491 int rc = ssmR3DataRead(pSSM, &u64, sizeof(uint64_t));
6492 if (RT_FAILURE(rc))
6493 return rc;
6494 if (u64 >= _4G)
6495 return VERR_SSM_GCPTR_OVERFLOW;
6496 *pGCPtr = (RTGCPTR)u64;
6497 return rc;
6498 }
6499
6500 /* 32-bit saved, 64-bit load: clear the high part. */
6501 *pGCPtr = 0;
6502 return ssmR3DataRead(pSSM, pGCPtr, sizeof(uint32_t));
6503}
6504
6505
6506/**
6507 * Loads a GC virtual address (represented as unsigned integer) item from the current data unit.
6508 *
6509 * @returns VBox status.
6510 * @param pSSM The saved state handle.
6511 * @param pGCPtr Where to store the GC virtual address.
6512 */
6513VMMR3DECL(int) SSMR3GetGCUIntPtr(PSSMHANDLE pSSM, PRTGCUINTPTR pGCPtr)
6514{
6515 AssertCompile(sizeof(RTGCPTR) == sizeof(*pGCPtr));
6516 return SSMR3GetGCPtr(pSSM, (PRTGCPTR)pGCPtr);
6517}
6518
6519
6520/**
6521 * Loads an RC virtual address item from the current data unit.
6522 *
6523 * @returns VBox status.
6524 * @param pSSM The saved state handle.
6525 * @param pRCPtr Where to store the RC virtual address.
6526 */
6527VMMR3DECL(int) SSMR3GetRCPtr(PSSMHANDLE pSSM, PRTRCPTR pRCPtr)
6528{
6529 SSM_ASSERT_READABLE_RET(pSSM);
6530 SSM_CHECK_CANCELLED_RET(pSSM);
6531 return ssmR3DataRead(pSSM, pRCPtr, sizeof(*pRCPtr));
6532}
6533
6534
6535/**
6536 * Loads a I/O port address item from the current data unit.
6537 *
6538 * @returns VBox status.
6539 * @param pSSM The saved state handle.
6540 * @param pIOPort Where to store the I/O port address.
6541 */
6542VMMR3DECL(int) SSMR3GetIOPort(PSSMHANDLE pSSM, PRTIOPORT pIOPort)
6543{
6544 SSM_ASSERT_READABLE_RET(pSSM);
6545 SSM_CHECK_CANCELLED_RET(pSSM);
6546 return ssmR3DataRead(pSSM, pIOPort, sizeof(*pIOPort));
6547}
6548
6549
6550/**
6551 * Loads a selector item from the current data unit.
6552 *
6553 * @returns VBox status.
6554 * @param pSSM The saved state handle.
6555 * @param pSel Where to store the selector.
6556 */
6557VMMR3DECL(int) SSMR3GetSel(PSSMHANDLE pSSM, PRTSEL pSel)
6558{
6559 SSM_ASSERT_READABLE_RET(pSSM);
6560 SSM_CHECK_CANCELLED_RET(pSSM);
6561 return ssmR3DataRead(pSSM, pSel, sizeof(*pSel));
6562}
6563
6564
6565/**
6566 * Loads a memory item from the current data unit.
6567 *
6568 * @returns VBox status.
6569 * @param pSSM The saved state handle.
6570 * @param pv Where to store the item.
6571 * @param cb Size of the item.
6572 */
6573VMMR3DECL(int) SSMR3GetMem(PSSMHANDLE pSSM, void *pv, size_t cb)
6574{
6575 SSM_ASSERT_READABLE_RET(pSSM);
6576 SSM_CHECK_CANCELLED_RET(pSSM);
6577 return ssmR3DataRead(pSSM, pv, cb);
6578}
6579
6580
6581/**
6582 * Loads a string item from the current data unit.
6583 *
6584 * @returns VBox status.
6585 * @param pSSM The saved state handle.
6586 * @param psz Where to store the item.
6587 * @param cbMax Max size of the item (including '\\0').
6588 */
6589VMMR3DECL(int) SSMR3GetStrZ(PSSMHANDLE pSSM, char *psz, size_t cbMax)
6590{
6591 return SSMR3GetStrZEx(pSSM, psz, cbMax, NULL);
6592}
6593
6594
6595/**
6596 * Loads a string item from the current data unit.
6597 *
6598 * @returns VBox status.
6599 * @param pSSM The saved state handle.
6600 * @param psz Where to store the item.
6601 * @param cbMax Max size of the item (including '\\0').
6602 * @param pcbStr The length of the loaded string excluding the '\\0'. (optional)
6603 */
6604VMMR3DECL(int) SSMR3GetStrZEx(PSSMHANDLE pSSM, char *psz, size_t cbMax, size_t *pcbStr)
6605{
6606 SSM_ASSERT_READABLE_RET(pSSM);
6607 SSM_CHECK_CANCELLED_RET(pSSM);
6608
6609 /* read size prefix. */
6610 uint32_t u32;
6611 int rc = SSMR3GetU32(pSSM, &u32);
6612 if (RT_SUCCESS(rc))
6613 {
6614 if (pcbStr)
6615 *pcbStr = u32;
6616 if (u32 < cbMax)
6617 {
6618 /* terminate and read string content. */
6619 psz[u32] = '\0';
6620 return ssmR3DataRead(pSSM, psz, u32);
6621 }
6622 return VERR_TOO_MUCH_DATA;
6623 }
6624 return rc;
6625}
6626
6627
6628/**
6629 * Skips a number of bytes in the current data unit.
6630 *
6631 * @returns VBox status code.
6632 * @param pSSM The SSM handle.
6633 * @param cb The number of bytes to skip.
6634 */
6635VMMR3DECL(int) SSMR3Skip(PSSMHANDLE pSSM, size_t cb)
6636{
6637 SSM_ASSERT_READABLE_RET(pSSM);
6638 SSM_CHECK_CANCELLED_RET(pSSM);
6639 while (cb > 0)
6640 {
6641 uint8_t abBuf[8192];
6642 size_t cbCur = RT_MIN(sizeof(abBuf), cb);
6643 cb -= cbCur;
6644 int rc = ssmR3DataRead(pSSM, abBuf, cbCur);
6645 if (RT_FAILURE(rc))
6646 return rc;
6647 }
6648
6649 return VINF_SUCCESS;
6650}
6651
6652
6653/**
6654 * Skips to the end of the current data unit.
6655 *
6656 * Since version 2 of the format, the load exec callback have to explicitly call
6657 * this API if it wish to be lazy for some reason. This is because there seldom
6658 * is a good reason to not read your entire data unit and it was hiding bugs.
6659 *
6660 * @returns VBox status code.
6661 * @param pSSM The saved state handle.
6662 */
6663VMMR3DECL(int) SSMR3SkipToEndOfUnit(PSSMHANDLE pSSM)
6664{
6665 SSM_ASSERT_READABLE_RET(pSSM);
6666 SSM_CHECK_CANCELLED_RET(pSSM);
6667 if (pSSM->u.Read.uFmtVerMajor >= 2)
6668 {
6669 /*
6670 * Read until we the end of data condition is raised.
6671 */
6672 pSSM->u.Read.cbDataBuffer = 0;
6673 pSSM->u.Read.offDataBuffer = 0;
6674 if (!pSSM->u.Read.fEndOfData)
6675 {
6676 do
6677 {
6678 /* read the rest of the current record */
6679 while (pSSM->u.Read.cbRecLeft)
6680 {
6681 uint8_t abBuf[8192];
6682 size_t cbToRead = RT_MIN(pSSM->u.Read.cbRecLeft, sizeof(abBuf));
6683 int rc = ssmR3DataReadV2Raw(pSSM, abBuf, cbToRead);
6684 if (RT_FAILURE(rc))
6685 return pSSM->rc = rc;
6686 pSSM->u.Read.cbRecLeft -= cbToRead;
6687 }
6688
6689 /* read the next header. */
6690 int rc = ssmR3DataReadRecHdrV2(pSSM);
6691 if (RT_FAILURE(rc))
6692 return pSSM->rc = rc;
6693 } while (!pSSM->u.Read.fEndOfData);
6694 }
6695 }
6696 /* else: Doesn't matter for the version 1 loading. */
6697
6698 return VINF_SUCCESS;
6699}
6700
6701
6702/**
6703 * Calculate the checksum of a file portion.
6704 *
6705 * @returns VBox status.
6706 * @param pStrm The stream handle
6707 * @param off Where to start checksumming.
6708 * @param cb How much to checksum.
6709 * @param pu32CRC Where to store the calculated checksum.
6710 */
6711static int ssmR3CalcChecksum(PSSMSTRM pStrm, uint64_t off, uint64_t cb, uint32_t *pu32CRC)
6712{
6713 /*
6714 * Allocate a buffer.
6715 */
6716 const size_t cbBuf = _32K;
6717 void *pvBuf = RTMemTmpAlloc(cbBuf);
6718 if (!pvBuf)
6719 return VERR_NO_TMP_MEMORY;
6720
6721 /*
6722 * Loop reading and calculating CRC32.
6723 */
6724 int rc = VINF_SUCCESS;
6725 uint32_t u32CRC = RTCrc32Start();
6726 while (cb > 0)
6727 {
6728 /* read chunk */
6729 size_t cbToRead = cbBuf;
6730 if (cb < cbBuf)
6731 cbToRead = cb;
6732 rc = ssmR3StrmPeekAt(pStrm, off, pvBuf, cbToRead, NULL);
6733 if (RT_FAILURE(rc))
6734 {
6735 AssertMsgFailed(("Failed with rc=%Rrc while calculating crc.\n", rc));
6736 RTMemTmpFree(pvBuf);
6737 return rc;
6738 }
6739
6740 /* advance */
6741 cb -= cbToRead;
6742 off += cbToRead;
6743
6744 /* calc crc32. */
6745 u32CRC = RTCrc32Process(u32CRC, pvBuf, cbToRead);
6746 }
6747 RTMemTmpFree(pvBuf);
6748
6749 /* store the calculated crc */
6750 u32CRC = RTCrc32Finish(u32CRC);
6751 Log(("SSM: u32CRC=0x%08x\n", u32CRC));
6752 *pu32CRC = u32CRC;
6753
6754 return VINF_SUCCESS;
6755}
6756
6757
6758/**
6759 * Validates a version 2 footer.
6760 *
6761 * @returns VBox status code.
6762 *
6763 * @param pFooter The footer.
6764 * @param offFooter The stream offset of the footer.
6765 * @param cDirEntries The number of directory entries. UINT32_MAX if
6766 * unknown.
6767 * @param fStreamCrc32 Whether the stream is checksummed using CRC-32.
6768 * @param u32StreamCRC The stream checksum.
6769 */
6770static int ssmR3ValidateFooter(PSSMFILEFTR pFooter, uint64_t offFooter, uint32_t cDirEntries, bool fStreamCrc32, uint32_t u32StreamCRC)
6771{
6772 if (memcmp(pFooter->szMagic, SSMFILEFTR_MAGIC, sizeof(pFooter->szMagic)))
6773 {
6774 LogRel(("SSM: Bad footer magic: %.*Rhxs\n", sizeof(pFooter->szMagic), &pFooter->szMagic[0]));
6775 return VERR_SSM_INTEGRITY_FOOTER;
6776 }
6777 SSM_CHECK_CRC32_RET(pFooter, sizeof(*pFooter), ("Footer CRC mismatch: %08x, correct is %08x\n", u32CRC, u32ActualCRC));
6778 if (pFooter->offStream != offFooter)
6779 {
6780 LogRel(("SSM: SSMFILEFTR::offStream is wrong: %llx, expected %llx\n", pFooter->offStream, offFooter));
6781 return VERR_SSM_INTEGRITY_FOOTER;
6782 }
6783 if (pFooter->u32Reserved)
6784 {
6785 LogRel(("SSM: Reserved footer field isn't zero: %08x\n", pFooter->u32Reserved));
6786 return VERR_SSM_INTEGRITY_FOOTER;
6787 }
6788 if (cDirEntries != UINT32_MAX)
6789 AssertLogRelMsgReturn(pFooter->cDirEntries == cDirEntries,
6790 ("Footer: cDirEntries=%#x, expected %#x\n", pFooter->cDirEntries, cDirEntries),
6791 VERR_SSM_INTEGRITY_FOOTER);
6792 else
6793 AssertLogRelMsgReturn(pFooter->cDirEntries < _64K,
6794 ("Footer: cDirEntries=%#x\n", pFooter->cDirEntries),
6795 VERR_SSM_INTEGRITY_FOOTER);
6796 if ( !fStreamCrc32
6797 && pFooter->u32StreamCRC)
6798 {
6799 LogRel(("SSM: u32StreamCRC field isn't zero, but header says stream checksumming is disabled.\n"));
6800 return VERR_SSM_INTEGRITY_FOOTER;
6801 }
6802 if ( fStreamCrc32
6803 && pFooter->u32StreamCRC != u32StreamCRC)
6804 {
6805 LogRel(("SSM: Bad stream CRC: %#x, expected %#x.\n", pFooter->u32StreamCRC, u32StreamCRC));
6806 return VERR_SSM_INTEGRITY_CRC;
6807 }
6808 return VINF_SUCCESS;
6809}
6810
6811
6812/**
6813 * Validates the header information stored in the handle.
6814 *
6815 * @returns VBox status code.
6816 *
6817 * @param pSSM The handle.
6818 * @param fHaveHostBits Set if the host bits field is valid.
6819 * @param fHaveVersion Set if we have a version.
6820 */
6821static int ssmR3ValidateHeaderInfo(PSSMHANDLE pSSM, bool fHaveHostBits, bool fHaveVersion)
6822{
6823 Assert(pSSM->u.Read.cbFileHdr < 256 && pSSM->u.Read.cbFileHdr > 32);
6824 Assert(pSSM->u.Read.uFmtVerMajor == 1 || pSSM->u.Read.uFmtVerMajor == 2);
6825 Assert(pSSM->u.Read.uFmtVerMinor <= 2);
6826
6827 if (fHaveVersion)
6828 {
6829 if ( pSSM->u.Read.u16VerMajor == 0
6830 || pSSM->u.Read.u16VerMajor > 1000
6831 || pSSM->u.Read.u16VerMinor > 1000
6832 || pSSM->u.Read.u32VerBuild > _1M
6833 || pSSM->u.Read.u32SvnRev == 0
6834 || pSSM->u.Read.u32SvnRev > 10000000 /*100M*/)
6835 {
6836 LogRel(("SSM: Incorrect version values: %u.%u.%u.r%u\n",
6837 pSSM->u.Read.u16VerMajor, pSSM->u.Read.u16VerMinor, pSSM->u.Read.u32VerBuild, pSSM->u.Read.u32SvnRev));
6838 return VERR_SSM_INTEGRITY_VBOX_VERSION;
6839 }
6840 }
6841 else
6842 AssertLogRelReturn( pSSM->u.Read.u16VerMajor == 0
6843 && pSSM->u.Read.u16VerMinor == 0
6844 && pSSM->u.Read.u32VerBuild == 0
6845 && pSSM->u.Read.u32SvnRev == 0,
6846 VERR_SSM_INTEGRITY_VBOX_VERSION);
6847
6848 if (fHaveHostBits)
6849 {
6850 if ( pSSM->u.Read.cHostBits != 32
6851 && pSSM->u.Read.cHostBits != 64)
6852 {
6853 LogRel(("SSM: Incorrect cHostBits value: %u\n", pSSM->u.Read.cHostBits));
6854 return VERR_SSM_INTEGRITY_HEADER;
6855 }
6856 }
6857 else
6858 AssertLogRelReturn(pSSM->u.Read.cHostBits == 0, VERR_SSM_INTEGRITY_HEADER);
6859
6860 if ( pSSM->u.Read.cbGCPhys != sizeof(uint32_t)
6861 && pSSM->u.Read.cbGCPhys != sizeof(uint64_t))
6862 {
6863 LogRel(("SSM: Incorrect cbGCPhys value: %d\n", pSSM->u.Read.cbGCPhys));
6864 return VERR_SSM_INTEGRITY_HEADER;
6865 }
6866 if ( pSSM->u.Read.cbGCPtr != sizeof(uint32_t)
6867 && pSSM->u.Read.cbGCPtr != sizeof(uint64_t))
6868 {
6869 LogRel(("SSM: Incorrect cbGCPtr value: %d\n", pSSM->u.Read.cbGCPtr));
6870 return VERR_SSM_INTEGRITY_HEADER;
6871 }
6872
6873 return VINF_SUCCESS;
6874}
6875
6876
6877/**
6878 * Reads the header, detects the format version and performs integrity
6879 * validations.
6880 *
6881 * @returns VBox status.
6882 * @param pSSM The saved state handle. A number of field will
6883 * be updated, mostly header related information.
6884 * fLiveSave is also set if appropriate.
6885 * @param fChecksumIt Whether to checksum the file or not. This will
6886 * be ignored if it the stream isn't a file.
6887 * @param fChecksumOnRead Whether to validate the checksum while reading
6888 * the stream instead of up front. If not possible,
6889 * verify the checksum up front.
6890 * @param pHdr Where to store the file header.
6891 */
6892static int ssmR3HeaderAndValidate(PSSMHANDLE pSSM, bool fChecksumIt, bool fChecksumOnRead)
6893{
6894 /*
6895 * Read and check the header magic.
6896 */
6897 union
6898 {
6899 SSMFILEHDR v2_0;
6900 SSMFILEHDRV12 v1_2;
6901 SSMFILEHDRV11 v1_1;
6902 } uHdr;
6903 int rc = ssmR3StrmRead(&pSSM->Strm, &uHdr, sizeof(uHdr.v2_0.szMagic));
6904 if (RT_FAILURE(rc))
6905 {
6906 LogRel(("SSM: Failed to read file magic header. rc=%Rrc\n", rc));
6907 return rc;
6908 }
6909 if (memcmp(uHdr.v2_0.szMagic, SSMFILEHDR_MAGIC_BASE, sizeof(SSMFILEHDR_MAGIC_BASE) - 1))
6910 {
6911 Log(("SSM: Not a saved state file. magic=%.*s\n", sizeof(uHdr.v2_0.szMagic) - 1, uHdr.v2_0.szMagic));
6912 return VERR_SSM_INTEGRITY_MAGIC;
6913 }
6914
6915 /*
6916 * Find the header size and read the rest.
6917 */
6918 static const struct
6919 {
6920 char szMagic[sizeof(SSMFILEHDR_MAGIC_V2_0)];
6921 size_t cbHdr;
6922 unsigned uFmtVerMajor;
6923 unsigned uFmtVerMinor;
6924 } s_aVers[] =
6925 {
6926 { SSMFILEHDR_MAGIC_V2_0, sizeof(SSMFILEHDR), 2, 0 },
6927 { SSMFILEHDR_MAGIC_V1_2, sizeof(SSMFILEHDRV12), 1, 2 },
6928 { SSMFILEHDR_MAGIC_V1_1, sizeof(SSMFILEHDRV11), 1, 1 },
6929 };
6930 int iVer = RT_ELEMENTS(s_aVers);
6931 while (iVer-- > 0)
6932 if (!memcmp(uHdr.v2_0.szMagic, s_aVers[iVer].szMagic, sizeof(uHdr.v2_0.szMagic)))
6933 break;
6934 if (iVer < 0)
6935 {
6936 Log(("SSM: Unknown file format version. magic=%.*s\n", sizeof(uHdr.v2_0.szMagic) - 1, uHdr.v2_0.szMagic));
6937 return VERR_SSM_INTEGRITY_VERSION;
6938 }
6939 pSSM->u.Read.uFmtVerMajor = s_aVers[iVer].uFmtVerMajor;
6940 pSSM->u.Read.uFmtVerMinor = s_aVers[iVer].uFmtVerMinor;
6941 pSSM->u.Read.cbFileHdr = s_aVers[iVer].cbHdr;
6942
6943 rc = ssmR3StrmRead(&pSSM->Strm, (uint8_t *)&uHdr + sizeof(uHdr.v2_0.szMagic), pSSM->u.Read.cbFileHdr - sizeof(uHdr.v2_0.szMagic));
6944 if (RT_FAILURE(rc))
6945 {
6946 LogRel(("SSM: Failed to read the file header. rc=%Rrc\n", rc));
6947 return rc;
6948 }
6949
6950 /*
6951 * Make version specific adjustments.
6952 */
6953 if (pSSM->u.Read.uFmtVerMajor >= 2)
6954 {
6955 /*
6956 * Version 2.0 and later.
6957 */
6958 if (pSSM->u.Read.uFmtVerMinor == 0)
6959 {
6960 /* validate the header. */
6961 SSM_CHECK_CRC32_RET(&uHdr.v2_0, sizeof(uHdr.v2_0), ("Header CRC mismatch: %08x, correct is %08x\n", u32CRC, u32ActualCRC));
6962 if (uHdr.v2_0.u8Reserved)
6963 {
6964 LogRel(("SSM: Reserved header field isn't zero: %02x\n", uHdr.v2_0.u8Reserved));
6965 return VERR_SSM_INTEGRITY;
6966 }
6967 if (uHdr.v2_0.fFlags & ~(SSMFILEHDR_FLAGS_STREAM_CRC32 | SSMFILEHDR_FLAGS_STREAM_LIVE_SAVE))
6968 {
6969 LogRel(("SSM: Unknown header flags: %08x\n", uHdr.v2_0.fFlags));
6970 return VERR_SSM_INTEGRITY;
6971 }
6972 if ( uHdr.v2_0.cbMaxDecompr > sizeof(pSSM->u.Read.abDataBuffer)
6973 || uHdr.v2_0.cbMaxDecompr < _1K
6974 || (uHdr.v2_0.cbMaxDecompr & 0xff) != 0)
6975 {
6976 LogRel(("SSM: The cbMaxDecompr header field is out of range: %#x\n", uHdr.v2_0.cbMaxDecompr));
6977 return VERR_SSM_INTEGRITY;
6978 }
6979
6980 /* set the header info. */
6981 pSSM->u.Read.cHostBits = uHdr.v2_0.cHostBits;
6982 pSSM->u.Read.u16VerMajor = uHdr.v2_0.u16VerMajor;
6983 pSSM->u.Read.u16VerMinor = uHdr.v2_0.u16VerMinor;
6984 pSSM->u.Read.u32VerBuild = uHdr.v2_0.u32VerBuild;
6985 pSSM->u.Read.u32SvnRev = uHdr.v2_0.u32SvnRev;
6986 pSSM->u.Read.cbGCPhys = uHdr.v2_0.cbGCPhys;
6987 pSSM->u.Read.cbGCPtr = uHdr.v2_0.cbGCPtr;
6988 pSSM->u.Read.fFixedGCPtrSize= true;
6989 pSSM->u.Read.fStreamCrc32 = !!(uHdr.v2_0.fFlags & SSMFILEHDR_FLAGS_STREAM_CRC32);
6990 pSSM->fLiveSave = !!(uHdr.v2_0.fFlags & SSMFILEHDR_FLAGS_STREAM_LIVE_SAVE);
6991 }
6992 else
6993 AssertFailedReturn(VERR_INTERNAL_ERROR);
6994 if (!pSSM->u.Read.fStreamCrc32)
6995 ssmR3StrmDisableChecksumming(&pSSM->Strm);
6996
6997 /*
6998 * Read and validate the footer if it's a file.
6999 */
7000 if (ssmR3StrmIsFile(&pSSM->Strm))
7001 {
7002 SSMFILEFTR Footer;
7003 uint64_t offFooter;
7004 rc = ssmR3StrmPeekAt(&pSSM->Strm, -(RTFOFF)sizeof(SSMFILEFTR), &Footer, sizeof(Footer), &offFooter);
7005 AssertLogRelRCReturn(rc, rc);
7006
7007 rc = ssmR3ValidateFooter(&Footer, offFooter, UINT32_MAX, pSSM->u.Read.fStreamCrc32, Footer.u32StreamCRC);
7008 if (RT_FAILURE(rc))
7009 return rc;
7010
7011 pSSM->u.Read.cbLoadFile = offFooter + sizeof(Footer);
7012 pSSM->u.Read.u32LoadCRC = Footer.u32StreamCRC;
7013 }
7014 else
7015 {
7016 pSSM->u.Read.cbLoadFile = UINT64_MAX;
7017 pSSM->u.Read.u32LoadCRC = 0;
7018 }
7019
7020 /*
7021 * Validate the header info we've set in the handle.
7022 */
7023 rc = ssmR3ValidateHeaderInfo(pSSM, true /*fHaveHostBits*/, true /*fHaveVersion*/);
7024 if (RT_FAILURE(rc))
7025 return rc;
7026
7027 /*
7028 * Check the checksum if that's called for and possible.
7029 */
7030 if ( pSSM->u.Read.fStreamCrc32
7031 && fChecksumIt
7032 && !fChecksumOnRead
7033 && ssmR3StrmIsFile(&pSSM->Strm))
7034 {
7035 uint32_t u32CRC;
7036 rc = ssmR3CalcChecksum(&pSSM->Strm, 0, pSSM->u.Read.cbLoadFile - sizeof(SSMFILEFTR), &u32CRC);
7037 if (RT_FAILURE(rc))
7038 return rc;
7039 if (u32CRC != pSSM->u.Read.u32LoadCRC)
7040 {
7041 LogRel(("SSM: Invalid CRC! Calculated %#010x, in footer %#010x\n", u32CRC, pSSM->u.Read.u32LoadCRC));
7042 return VERR_SSM_INTEGRITY_CRC;
7043 }
7044 }
7045 }
7046 else
7047 {
7048 /*
7049 * Version 1.x of the format.
7050 */
7051 bool fHaveHostBits = true;
7052 bool fHaveVersion = false;
7053 RTUUID MachineUuidFromHdr;
7054
7055 ssmR3StrmDisableChecksumming(&pSSM->Strm);
7056 if (pSSM->u.Read.uFmtVerMinor == 1)
7057 {
7058 pSSM->u.Read.cHostBits = 0; /* unknown */
7059 pSSM->u.Read.u16VerMajor = 0;
7060 pSSM->u.Read.u16VerMinor = 0;
7061 pSSM->u.Read.u32VerBuild = 0;
7062 pSSM->u.Read.u32SvnRev = 0;
7063 pSSM->u.Read.cbLoadFile = uHdr.v1_1.cbFile;
7064 pSSM->u.Read.u32LoadCRC = uHdr.v1_1.u32CRC;
7065 pSSM->u.Read.cbGCPhys = sizeof(RTGCPHYS);
7066 pSSM->u.Read.cbGCPtr = sizeof(RTGCPTR);
7067 pSSM->u.Read.fFixedGCPtrSize = false; /* settable */
7068 pSSM->u.Read.fStreamCrc32 = false;
7069
7070 MachineUuidFromHdr = uHdr.v1_1.MachineUuid;
7071 fHaveHostBits = false;
7072 }
7073 else if (pSSM->u.Read.uFmtVerMinor == 2)
7074 {
7075 pSSM->u.Read.cHostBits = uHdr.v1_2.cHostBits;
7076 pSSM->u.Read.u16VerMajor = uHdr.v1_2.u16VerMajor;
7077 pSSM->u.Read.u16VerMinor = uHdr.v1_2.u16VerMinor;
7078 pSSM->u.Read.u32VerBuild = uHdr.v1_2.u32VerBuild;
7079 pSSM->u.Read.u32SvnRev = uHdr.v1_2.u32SvnRev;
7080 pSSM->u.Read.cbLoadFile = uHdr.v1_2.cbFile;
7081 pSSM->u.Read.u32LoadCRC = uHdr.v1_2.u32CRC;
7082 pSSM->u.Read.cbGCPhys = uHdr.v1_2.cbGCPhys;
7083 pSSM->u.Read.cbGCPtr = uHdr.v1_2.cbGCPtr;
7084 pSSM->u.Read.fFixedGCPtrSize = true;
7085 pSSM->u.Read.fStreamCrc32 = false;
7086
7087 MachineUuidFromHdr = uHdr.v1_2.MachineUuid;
7088 fHaveVersion = true;
7089 }
7090 else
7091 AssertFailedReturn(VERR_INTERNAL_ERROR);
7092
7093 /*
7094 * The MachineUuid must be NULL (was never used).
7095 */
7096 if (!RTUuidIsNull(&MachineUuidFromHdr))
7097 {
7098 LogRel(("SSM: The UUID of the saved state doesn't match the running VM.\n"));
7099 return VERR_SMM_INTEGRITY_MACHINE;
7100 }
7101
7102 /*
7103 * Verify the file size.
7104 */
7105 uint64_t cbFile = ssmR3StrmGetSize(&pSSM->Strm);
7106 if (cbFile != pSSM->u.Read.cbLoadFile)
7107 {
7108 LogRel(("SSM: File size mismatch. hdr.cbFile=%lld actual %lld\n", pSSM->u.Read.cbLoadFile, cbFile));
7109 return VERR_SSM_INTEGRITY_SIZE;
7110 }
7111
7112 /*
7113 * Validate the header info we've set in the handle.
7114 */
7115 rc = ssmR3ValidateHeaderInfo(pSSM, fHaveHostBits, fHaveVersion);
7116 if (RT_FAILURE(rc))
7117 return rc;
7118
7119 /*
7120 * Verify the checksum if requested.
7121 *
7122 * Note! The checksum is not actually generated for the whole file,
7123 * this is of course a bug in the v1.x code that we cannot do
7124 * anything about.
7125 */
7126 if ( fChecksumIt
7127 || fChecksumOnRead)
7128 {
7129 uint32_t u32CRC;
7130 rc = ssmR3CalcChecksum(&pSSM->Strm,
7131 RT_OFFSETOF(SSMFILEHDRV11, u32CRC) + sizeof(uHdr.v1_1.u32CRC),
7132 cbFile - pSSM->u.Read.cbFileHdr,
7133 &u32CRC);
7134 if (RT_FAILURE(rc))
7135 return rc;
7136 if (u32CRC != pSSM->u.Read.u32LoadCRC)
7137 {
7138 LogRel(("SSM: Invalid CRC! Calculated %#010x, in header %#010x\n", u32CRC, pSSM->u.Read.u32LoadCRC));
7139 return VERR_SSM_INTEGRITY_CRC;
7140 }
7141 }
7142 }
7143
7144 return VINF_SUCCESS;
7145}
7146
7147
7148/**
7149 * Open a saved state for reading.
7150 *
7151 * The file will be positioned at the first data unit upon successful return.
7152 *
7153 * @returns VBox status code.
7154 *
7155 * @param pVM The VM handle.
7156 * @param pszFilename The filename. NULL if pStreamOps is used.
7157 * @param pStreamOps The stream method table. NULL if pszFilename is
7158 * used.
7159 * @param pvUser The user argument to the stream methods.
7160 * @param fChecksumIt Check the checksum for the entire file.
7161 * @param fChecksumOnRead Whether to validate the checksum while reading
7162 * the stream instead of up front. If not possible,
7163 * verify the checksum up front.
7164 * @param pSSM Pointer to the handle structure. This will be
7165 * completely initialized on success.
7166 * @param cBuffers The number of stream buffers.
7167 */
7168static int ssmR3OpenFile(PVM pVM, const char *pszFilename, PCSSMSTRMOPS pStreamOps, void *pvUser,
7169 bool fChecksumIt, bool fChecksumOnRead, uint32_t cBuffers, PSSMHANDLE pSSM)
7170{
7171 /*
7172 * Initialize the handle.
7173 */
7174 pSSM->pVM = pVM;
7175 pSSM->enmOp = SSMSTATE_INVALID;
7176 pSSM->enmAfter = SSMAFTER_INVALID;
7177 pSSM->fCancelled = SSMHANDLE_OK;
7178 pSSM->rc = VINF_SUCCESS;
7179 pSSM->cbUnitLeftV1 = 0;
7180 pSSM->offUnit = UINT64_MAX;
7181 pSSM->fLiveSave = false;
7182 pSSM->pfnProgress = NULL;
7183 pSSM->pvUser = NULL;
7184 pSSM->uPercent = 0;
7185 pSSM->offEstProgress = 0;
7186 pSSM->cbEstTotal = 0;
7187 pSSM->offEst = 0;
7188 pSSM->offEstUnitEnd = 0;
7189 pSSM->uPercentPrepare = 5;
7190 pSSM->uPercentDone = 2;
7191 pSSM->pszFilename = pszFilename;
7192
7193 pSSM->u.Read.pZipDecompV1 = NULL;
7194 pSSM->u.Read.uFmtVerMajor = UINT32_MAX;
7195 pSSM->u.Read.uFmtVerMinor = UINT32_MAX;
7196 pSSM->u.Read.cbFileHdr = UINT32_MAX;
7197 pSSM->u.Read.cbGCPhys = UINT8_MAX;
7198 pSSM->u.Read.cbGCPtr = UINT8_MAX;
7199 pSSM->u.Read.fFixedGCPtrSize= false;
7200 pSSM->u.Read.fIsHostMsc32 = SSM_HOST_IS_MSC_32;
7201 pSSM->u.Read.u16VerMajor = UINT16_MAX;
7202 pSSM->u.Read.u16VerMinor = UINT16_MAX;
7203 pSSM->u.Read.u32VerBuild = UINT32_MAX;
7204 pSSM->u.Read.u32SvnRev = UINT32_MAX;
7205 pSSM->u.Read.cHostBits = UINT8_MAX;
7206 pSSM->u.Read.cbLoadFile = UINT64_MAX;
7207
7208 pSSM->u.Read.cbRecLeft = 0;
7209 pSSM->u.Read.cbDataBuffer = 0;
7210 pSSM->u.Read.offDataBuffer = 0;
7211 pSSM->u.Read.fEndOfData = 0;
7212 pSSM->u.Read.u8TypeAndFlags = 0;
7213
7214 /*
7215 * Try open and validate the file.
7216 */
7217 int rc;
7218 if (pStreamOps)
7219 rc = ssmR3StrmInit(&pSSM->Strm, pStreamOps, pvUser, false /*fWrite*/, fChecksumOnRead, cBuffers);
7220 else
7221 rc = ssmR3StrmOpenFile(&pSSM->Strm, pszFilename, false /*fWrite*/, fChecksumOnRead, cBuffers);
7222 if (RT_SUCCESS(rc))
7223 {
7224 rc = ssmR3HeaderAndValidate(pSSM, fChecksumIt, fChecksumOnRead);
7225 if (RT_SUCCESS(rc))
7226 return rc;
7227
7228 /* failure path */
7229 ssmR3StrmClose(&pSSM->Strm);
7230 }
7231 else
7232 Log(("SSM: Failed to open save state file '%s', rc=%Rrc.\n", pszFilename, rc));
7233 return rc;
7234}
7235
7236
7237/**
7238 * Find a data unit by name.
7239 *
7240 * @returns Pointer to the unit.
7241 * @returns NULL if not found.
7242 *
7243 * @param pVM VM handle.
7244 * @param pszName Data unit name.
7245 * @param uInstance The data unit instance id.
7246 */
7247static PSSMUNIT ssmR3Find(PVM pVM, const char *pszName, uint32_t uInstance)
7248{
7249 size_t cchName = strlen(pszName);
7250 PSSMUNIT pUnit = pVM->ssm.s.pHead;
7251 while ( pUnit
7252 && ( pUnit->u32Instance != uInstance
7253 || pUnit->cchName != cchName
7254 || memcmp(pUnit->szName, pszName, cchName)))
7255 pUnit = pUnit->pNext;
7256 return pUnit;
7257}
7258
7259
7260/**
7261 * Executes the loading of a V1.X file.
7262 *
7263 * @returns VBox status code.
7264 * @param pVM The VM handle.
7265 * @param pSSM The saved state handle.
7266 */
7267static int ssmR3LoadExecV1(PVM pVM, PSSMHANDLE pSSM)
7268{
7269 int rc;
7270 char *pszName = NULL;
7271 size_t cchName = 0;
7272 pSSM->enmOp = SSMSTATE_LOAD_EXEC;
7273 for (;;)
7274 {
7275 /*
7276 * Save the current file position and read the data unit header.
7277 */
7278 uint64_t offUnit = ssmR3StrmTell(&pSSM->Strm);
7279 SSMFILEUNITHDRV1 UnitHdr;
7280 rc = ssmR3StrmRead(&pSSM->Strm, &UnitHdr, RT_OFFSETOF(SSMFILEUNITHDRV1, szName));
7281 if (RT_SUCCESS(rc))
7282 {
7283 /*
7284 * Check the magic and see if it's valid and whether it is a end header or not.
7285 */
7286 if (memcmp(&UnitHdr.achMagic[0], SSMFILEUNITHDR_MAGIC, sizeof(SSMFILEUNITHDR_MAGIC)))
7287 {
7288 if (!memcmp(&UnitHdr.achMagic[0], SSMFILEUNITHDR_END, sizeof(SSMFILEUNITHDR_END)))
7289 {
7290 Log(("SSM: EndOfFile: offset %#9llx size %9d\n", offUnit, UnitHdr.cbUnit));
7291 /* Complete the progress bar (pending 99% afterwards). */
7292 ssmR3Progress(pSSM, pSSM->cbEstTotal - pSSM->offEst);
7293 break;
7294 }
7295 LogRel(("SSM: Invalid unit magic at offset %#llx (%lld), '%.*s'!\n",
7296 offUnit, offUnit, sizeof(UnitHdr.achMagic) - 1, &UnitHdr.achMagic[0]));
7297 rc = VERR_SSM_INTEGRITY_UNIT_MAGIC;
7298 break;
7299 }
7300
7301 /*
7302 * Read the name.
7303 * Adjust the name buffer first.
7304 */
7305 if (cchName < UnitHdr.cchName)
7306 {
7307 if (pszName)
7308 RTMemTmpFree(pszName);
7309 cchName = RT_ALIGN_Z(UnitHdr.cchName, 64);
7310 pszName = (char *)RTMemTmpAlloc(cchName);
7311 }
7312 if (pszName)
7313 {
7314 rc = ssmR3StrmRead(&pSSM->Strm, pszName, UnitHdr.cchName);
7315 if (RT_SUCCESS(rc))
7316 {
7317 if (pszName[UnitHdr.cchName - 1])
7318 {
7319 LogRel(("SSM: Unit name '%.*s' was not properly terminated.\n", UnitHdr.cchName, pszName));
7320 rc = VERR_SSM_INTEGRITY_UNIT;
7321 break;
7322 }
7323 Log(("SSM: Data unit: offset %#9llx size %9lld '%s'\n", offUnit, UnitHdr.cbUnit, pszName));
7324
7325 /*
7326 * Find the data unit in our internal table.
7327 */
7328 PSSMUNIT pUnit = ssmR3Find(pVM, pszName, UnitHdr.u32Instance);
7329 if (pUnit)
7330 {
7331 /*
7332 * Call the execute handler.
7333 */
7334 pSSM->cbUnitLeftV1 = UnitHdr.cbUnit - RT_OFFSETOF(SSMFILEUNITHDRV1, szName[UnitHdr.cchName]);
7335 pSSM->offUnit = 0;
7336 if (!pUnit->u.Common.pfnLoadExec)
7337 {
7338 LogRel(("SSM: No load exec callback for unit '%s'!\n", pszName));
7339 pSSM->rc = rc = VERR_SSM_NO_LOAD_EXEC;
7340 break;
7341 }
7342 switch (pUnit->enmType)
7343 {
7344 case SSMUNITTYPE_DEV:
7345 rc = pUnit->u.Dev.pfnLoadExec(pUnit->u.Dev.pDevIns, pSSM, UnitHdr.u32Version, SSM_PASS_FINAL);
7346 break;
7347 case SSMUNITTYPE_DRV:
7348 rc = pUnit->u.Drv.pfnLoadExec(pUnit->u.Drv.pDrvIns, pSSM, UnitHdr.u32Version, SSM_PASS_FINAL);
7349 break;
7350 case SSMUNITTYPE_INTERNAL:
7351 rc = pUnit->u.Internal.pfnLoadExec(pVM, pSSM, UnitHdr.u32Version, SSM_PASS_FINAL);
7352 break;
7353 case SSMUNITTYPE_EXTERNAL:
7354 rc = pUnit->u.External.pfnLoadExec(pSSM, pUnit->u.External.pvUser, UnitHdr.u32Version, SSM_PASS_FINAL);
7355 break;
7356 default:
7357 rc = VERR_INTERNAL_ERROR;
7358 break;
7359 }
7360 pUnit->fCalled = true;
7361 if (RT_FAILURE(rc) && RT_SUCCESS_NP(pSSM->rc))
7362 pSSM->rc = rc;
7363
7364 /*
7365 * Close the reader stream.
7366 */
7367 rc = ssmR3DataReadFinishV1(pSSM);
7368 if (RT_SUCCESS(rc))
7369 {
7370 /*
7371 * Now, we'll check the current position to see if all, or
7372 * more than all, the data was read.
7373 *
7374 * Note! Because of buffering / compression we'll only see the
7375 * really bad ones here.
7376 */
7377 uint64_t off = ssmR3StrmTell(&pSSM->Strm);
7378 int64_t i64Diff = off - (offUnit + UnitHdr.cbUnit);
7379 if (i64Diff < 0)
7380 {
7381 Log(("SSM: Unit '%s' left %lld bytes unread!\n", pszName, -i64Diff));
7382 rc = ssmR3StrmSkipTo(&pSSM->Strm, offUnit + UnitHdr.cbUnit);
7383 ssmR3Progress(pSSM, offUnit + UnitHdr.cbUnit - pSSM->offEst);
7384 }
7385 else if (i64Diff > 0)
7386 {
7387 LogRel(("SSM: Unit '%s' read %lld bytes too much!\n", pszName, i64Diff));
7388 rc = VMSetError(pVM, VERR_SSM_LOADED_TOO_MUCH, RT_SRC_POS,
7389 N_("Unit '%s' read %lld bytes too much"), pszName, i64Diff);
7390 break;
7391 }
7392
7393 pSSM->offUnit = UINT64_MAX;
7394 }
7395 else
7396 {
7397 LogRel(("SSM: Load exec failed for '%s' instance #%u ! (version %u)\n",
7398 pszName, UnitHdr.u32Instance, UnitHdr.u32Version));
7399 VMSetError(pVM, rc, RT_SRC_POS, N_("Load exec failed for '%s' instance #%u (version %u)"),
7400 pszName, UnitHdr.u32Instance, UnitHdr.u32Version);
7401 break;
7402 }
7403 }
7404 else
7405 {
7406 /*
7407 * SSM unit wasn't found - ignore this when loading for the debugger.
7408 */
7409 LogRel(("SSM: Found no handler for unit '%s'!\n", pszName));
7410 rc = VERR_SSM_INTEGRITY_UNIT_NOT_FOUND;
7411 if (pSSM->enmAfter != SSMAFTER_DEBUG_IT)
7412 break;
7413 rc = ssmR3StrmSkipTo(&pSSM->Strm, offUnit + UnitHdr.cbUnit);
7414 }
7415 }
7416 }
7417 else
7418 rc = VERR_NO_TMP_MEMORY;
7419 }
7420
7421 /*
7422 * I/O errors ends up here (yea, I know, very nice programming).
7423 */
7424 if (RT_FAILURE(rc))
7425 {
7426 LogRel(("SSM: I/O error. rc=%Rrc\n", rc));
7427 break;
7428 }
7429
7430 /*
7431 * Check for cancellation.
7432 */
7433 if (RT_UNLIKELY(ASMAtomicUoReadU32(&(pSSM)->fCancelled) == SSMHANDLE_CANCELLED))
7434 {
7435 LogRel(("SSM: Cancelled!n"));
7436 rc = pSSM->rc;
7437 if (RT_SUCCESS(pSSM->rc))
7438 pSSM->rc = rc = VERR_SSM_CANCELLED;
7439 break;
7440 }
7441 }
7442
7443 RTMemTmpFree(pszName);
7444 return rc;
7445}
7446
7447
7448/**
7449 * Verifies the directory.
7450 *
7451 * @returns VBox status code.
7452 *
7453 * @param pDir The full directory.
7454 * @param cbDir The size of the directory.
7455 * @param offDir The directory stream offset.
7456 * @param cDirEntries The directory entry count from the footer.
7457 * @param cbHdr The header size.
7458 * @param uSvnRev The SVN revision that saved the state. Bug detection.
7459 */
7460static int ssmR3ValidateDirectory(PSSMFILEDIR pDir, size_t cbDir, uint64_t offDir, uint32_t cDirEntries,
7461 uint32_t cbHdr, uint32_t uSvnRev)
7462{
7463 AssertLogRelReturn(!memcmp(pDir->szMagic, SSMFILEDIR_MAGIC, sizeof(pDir->szMagic)), VERR_SSM_INTEGRITY_DIR_MAGIC);
7464 SSM_CHECK_CRC32_RET(pDir, cbDir, ("Bad directory CRC: %08x, actual %08x\n", u32CRC, u32ActualCRC));
7465 AssertLogRelMsgReturn(pDir->cEntries == cDirEntries,
7466 ("Bad directory entry count: %#x, expected %#x (from the footer)\n", pDir->cEntries, cDirEntries),
7467 VERR_SSM_INTEGRITY_DIR);
7468 AssertLogRelReturn(RT_UOFFSETOF(SSMFILEDIR, aEntries[pDir->cEntries]) == cbDir, VERR_SSM_INTEGRITY_DIR);
7469
7470 for (uint32_t i = 0; i < pDir->cEntries; i++)
7471 {
7472 AssertLogRelMsgReturn( ( pDir->aEntries[i].off >= cbHdr
7473 && pDir->aEntries[i].off < offDir)
7474 || ( pDir->aEntries[i].off == 0 /* bug in unreleased code */
7475 && uSvnRev < 53365),
7476 ("off=%#llx cbHdr=%#x offDir=%#llx\n", pDir->aEntries[i].off, cbHdr, offDir),
7477 VERR_SSM_INTEGRITY_DIR);
7478 }
7479 return VINF_SUCCESS;
7480}
7481
7482
7483/**
7484 * Reads and verifies the directory and footer.
7485 *
7486 * @returns VBox status code.
7487 * @param pSSM The saved state handle.
7488 */
7489static int ssmR3LoadDirectoryAndFooter(PSSMHANDLE pSSM)
7490{
7491 /*
7492 * The directory.
7493 *
7494 * Get the header containing the number of entries first. Then read the
7495 * entries and pass the combined block to the validation function.
7496 */
7497 uint64_t off = ssmR3StrmTell(&pSSM->Strm);
7498 size_t const cbDirHdr = RT_OFFSETOF(SSMFILEDIR, aEntries);
7499 SSMFILEDIR DirHdr;
7500 int rc = ssmR3StrmRead(&pSSM->Strm, &DirHdr, cbDirHdr);
7501 if (RT_FAILURE(rc))
7502 return rc;
7503 AssertLogRelMsgReturn(!memcmp(DirHdr.szMagic, SSMFILEDIR_MAGIC, sizeof(DirHdr.szMagic)),
7504 ("Invalid directory magic at %#llx (%lld): %.*Rhxs\n", off, off, sizeof(DirHdr.szMagic), DirHdr.szMagic),
7505 VERR_SSM_INTEGRITY_DIR_MAGIC);
7506 AssertLogRelMsgReturn(DirHdr.cEntries < _64K,
7507 ("Too many directory entries at %#llx (%lld): %#x\n", off, off, DirHdr.cEntries),
7508 VERR_SSM_INTEGRITY_DIR);
7509
7510 size_t cbDir = RT_OFFSETOF(SSMFILEDIR, aEntries[DirHdr.cEntries]);
7511 PSSMFILEDIR pDir = (PSSMFILEDIR)RTMemTmpAlloc(cbDir);
7512 if (!pDir)
7513 return VERR_NO_TMP_MEMORY;
7514 memcpy(pDir, &DirHdr, cbDirHdr);
7515 rc = ssmR3StrmRead(&pSSM->Strm, (uint8_t *)pDir + cbDirHdr, cbDir - cbDirHdr);
7516 if (RT_SUCCESS(rc))
7517 rc = ssmR3ValidateDirectory(pDir, cbDir, off, DirHdr.cEntries, pSSM->u.Read.cbFileHdr, pSSM->u.Read.u32SvnRev);
7518 RTMemTmpFree(pDir);
7519 if (RT_FAILURE(rc))
7520 return rc;
7521
7522 /*
7523 * Read and validate the footer.
7524 */
7525 off = ssmR3StrmTell(&pSSM->Strm);
7526 uint32_t u32StreamCRC = ssmR3StrmFinalCRC(&pSSM->Strm);
7527 SSMFILEFTR Footer;
7528 rc = ssmR3StrmRead(&pSSM->Strm, &Footer, sizeof(Footer));
7529 if (RT_FAILURE(rc))
7530 return rc;
7531 return ssmR3ValidateFooter(&Footer, off, DirHdr.cEntries, pSSM->u.Read.fStreamCrc32, u32StreamCRC);
7532}
7533
7534
7535/**
7536 * Executes the loading of a V2.X file.
7537 *
7538 * @returns VBox status code.
7539 * @param pVM The VM handle.
7540 * @param pSSM The saved state handle.
7541 */
7542static int ssmR3LoadExecV2(PVM pVM, PSSMHANDLE pSSM)
7543{
7544 pSSM->enmOp = SSMSTATE_LOAD_EXEC;
7545 for (;;)
7546 {
7547 /*
7548 * Read the unit header and check its integrity.
7549 */
7550 uint64_t offUnit = ssmR3StrmTell(&pSSM->Strm);
7551 uint32_t u32CurStreamCRC = ssmR3StrmCurCRC(&pSSM->Strm);
7552 SSMFILEUNITHDRV2 UnitHdr;
7553 int rc = ssmR3StrmRead(&pSSM->Strm, &UnitHdr, RT_OFFSETOF(SSMFILEUNITHDRV2, szName));
7554 if (RT_FAILURE(rc))
7555 return rc;
7556 if (RT_UNLIKELY( memcmp(&UnitHdr.szMagic[0], SSMFILEUNITHDR_MAGIC, sizeof(UnitHdr.szMagic))
7557 && memcmp(&UnitHdr.szMagic[0], SSMFILEUNITHDR_END, sizeof(UnitHdr.szMagic))))
7558 {
7559 LogRel(("SSM: Unit at %#llx (%lld): Invalid unit magic: %.*Rhxs!\n",
7560 offUnit, offUnit, sizeof(UnitHdr.szMagic) - 1, &UnitHdr.szMagic[0]));
7561 return VMSetError(pVM, VERR_SSM_INTEGRITY_UNIT_MAGIC, RT_SRC_POS,
7562 N_("Unit at %#llx (%lld): Invalid unit magic"), offUnit, offUnit);
7563 }
7564 if (UnitHdr.cbName)
7565 {
7566 AssertLogRelMsgReturn(UnitHdr.cbName <= sizeof(UnitHdr.szName),
7567 ("Unit at %#llx (%lld): UnitHdr.cbName=%u > %u\n",
7568 offUnit, offUnit, UnitHdr.cbName, sizeof(UnitHdr.szName)),
7569 VERR_SSM_INTEGRITY_UNIT);
7570 rc = ssmR3StrmRead(&pSSM->Strm, &UnitHdr.szName[0], UnitHdr.cbName);
7571 if (RT_FAILURE(rc))
7572 return rc;
7573 AssertLogRelMsgReturn(!UnitHdr.szName[UnitHdr.cbName - 1],
7574 ("Unit at %#llx (%lld): Name %.*Rhxs was not properly terminated.\n",
7575 offUnit, offUnit, UnitHdr.cbName, UnitHdr.szName),
7576 VERR_SSM_INTEGRITY_UNIT);
7577 }
7578 SSM_CHECK_CRC32_RET(&UnitHdr, RT_OFFSETOF(SSMFILEUNITHDRV2, szName[UnitHdr.cbName]),
7579 ("Unit at %#llx (%lld): CRC mismatch: %08x, correct is %08x\n", offUnit, offUnit, u32CRC, u32ActualCRC));
7580 AssertLogRelMsgReturn(UnitHdr.offStream == offUnit,
7581 ("Unit at %#llx (%lld): offStream=%#llx, expected %#llx\n", offUnit, offUnit, UnitHdr.offStream, offUnit),
7582 VERR_SSM_INTEGRITY_UNIT);
7583 AssertLogRelMsgReturn(UnitHdr.u32CurStreamCRC == u32CurStreamCRC || !pSSM->Strm.fChecksummed,
7584 ("Unit at %#llx (%lld): Stream CRC mismatch: %08x, correct is %08x\n", offUnit, offUnit, UnitHdr.u32CurStreamCRC, u32CurStreamCRC),
7585 VERR_SSM_INTEGRITY_UNIT);
7586 AssertLogRelMsgReturn(!UnitHdr.fFlags, ("Unit at %#llx (%lld): fFlags=%08x\n", offUnit, offUnit, UnitHdr.fFlags),
7587 VERR_SSM_INTEGRITY_UNIT);
7588 if (!memcmp(&UnitHdr.szMagic[0], SSMFILEUNITHDR_END, sizeof(UnitHdr.szMagic)))
7589 {
7590 AssertLogRelMsgReturn( UnitHdr.cbName == 0
7591 && UnitHdr.u32Instance == 0
7592 && UnitHdr.u32Version == 0
7593 && UnitHdr.u32Pass == SSM_PASS_FINAL,
7594 ("Unit at %#llx (%lld): Malformed END unit\n", offUnit, offUnit),
7595 VERR_SSM_INTEGRITY_UNIT);
7596
7597 /*
7598 * Complete the progress bar (pending 99% afterwards) and RETURN.
7599 */
7600 Log(("SSM: Unit at %#9llx: END UNIT\n", offUnit));
7601 ssmR3Progress(pSSM, pSSM->cbEstTotal - pSSM->offEst);
7602
7603 return ssmR3LoadDirectoryAndFooter(pSSM);
7604 }
7605 AssertLogRelMsgReturn(UnitHdr.cbName > 1, ("Unit at %#llx (%lld): No name\n", offUnit, offUnit), VERR_SSM_INTEGRITY);
7606
7607 Log(("SSM: Unit at %#9llx: '%s', instance %u, pass %#x, version %u\n",
7608 offUnit, UnitHdr.szName, UnitHdr.u32Instance, UnitHdr.u32Pass, UnitHdr.u32Version));
7609
7610 /*
7611 * Find the data unit in our internal table.
7612 */
7613 PSSMUNIT pUnit = ssmR3Find(pVM, UnitHdr.szName, UnitHdr.u32Instance);
7614 if (pUnit)
7615 {
7616 /*
7617 * Call the execute handler.
7618 */
7619 AssertLogRelMsgReturn(pUnit->u.Common.pfnLoadExec,
7620 ("SSM: No load exec callback for unit '%s'!\n", UnitHdr.szName),
7621 VERR_SSM_NO_LOAD_EXEC);
7622 ssmR3DataReadBeginV2(pSSM);
7623 switch (pUnit->enmType)
7624 {
7625 case SSMUNITTYPE_DEV:
7626 rc = pUnit->u.Dev.pfnLoadExec(pUnit->u.Dev.pDevIns, pSSM, UnitHdr.u32Version, UnitHdr.u32Pass);
7627 break;
7628 case SSMUNITTYPE_DRV:
7629 rc = pUnit->u.Drv.pfnLoadExec(pUnit->u.Drv.pDrvIns, pSSM, UnitHdr.u32Version, UnitHdr.u32Pass);
7630 break;
7631 case SSMUNITTYPE_INTERNAL:
7632 rc = pUnit->u.Internal.pfnLoadExec(pVM, pSSM, UnitHdr.u32Version, UnitHdr.u32Pass);
7633 break;
7634 case SSMUNITTYPE_EXTERNAL:
7635 rc = pUnit->u.External.pfnLoadExec(pSSM, pUnit->u.External.pvUser, UnitHdr.u32Version, UnitHdr.u32Pass);
7636 break;
7637 default:
7638 rc = VERR_INTERNAL_ERROR;
7639 break;
7640 }
7641 pUnit->fCalled = true;
7642 if (RT_FAILURE(rc) && RT_SUCCESS_NP(pSSM->rc))
7643 pSSM->rc = rc;
7644 rc = ssmR3DataReadFinishV2(pSSM);
7645 if (RT_SUCCESS(rc))
7646 pSSM->offUnit = UINT64_MAX;
7647 else
7648 {
7649 LogRel(("SSM: LoadExec failed for '%s' instance #%u (version %u, pass %#x): %Rrc\n",
7650 UnitHdr.szName, UnitHdr.u32Instance, UnitHdr.u32Version, UnitHdr.u32Pass, rc));
7651 return VMSetError(pVM, rc, RT_SRC_POS, N_("Failed to load unit '%s'"), UnitHdr.szName);
7652 }
7653 }
7654 else
7655 {
7656 /*
7657 * SSM unit wasn't found - ignore this when loading for the debugger.
7658 */
7659 LogRel(("SSM: Found no handler for unit '%s' instance #%u!\n", UnitHdr.szName, UnitHdr.u32Instance));
7660 if (pSSM->enmAfter != SSMAFTER_DEBUG_IT)
7661 return VMSetError(pVM, VERR_SSM_INTEGRITY_UNIT_NOT_FOUND, RT_SRC_POS,
7662 N_("Found no handler for unit '%s' instance #%u"), UnitHdr.szName, UnitHdr.u32Instance);
7663 SSMR3SkipToEndOfUnit(pSSM);
7664 ssmR3DataReadFinishV2(pSSM);
7665 }
7666
7667 /*
7668 * Check for cancellation.
7669 */
7670 if (RT_UNLIKELY(ASMAtomicUoReadU32(&(pSSM)->fCancelled) == SSMHANDLE_CANCELLED))
7671 {
7672 LogRel(("SSM: Cancelled!\n"));
7673 if (RT_SUCCESS(pSSM->rc))
7674 pSSM->rc = VERR_SSM_CANCELLED;
7675 return pSSM->rc;
7676 }
7677 }
7678 /* won't get here */
7679}
7680
7681
7682
7683
7684/**
7685 * Load VM save operation.
7686 *
7687 * @returns VBox status.
7688 *
7689 * @param pVM The VM handle.
7690 * @param pszFilename The name of the saved state file. NULL if pStreamOps
7691 * is used.
7692 * @param pStreamOps The stream method table. NULL if pszFilename is
7693 * used.
7694 * @param pvStreamOpsUser The user argument for the stream methods.
7695 * @param enmAfter What is planned after a successful load operation.
7696 * Only acceptable values are SSMAFTER_RESUME and SSMAFTER_DEBUG_IT.
7697 * @param pfnProgress Progress callback. Optional.
7698 * @param pvProgressUser User argument for the progress callback.
7699 *
7700 * @thread EMT
7701 */
7702VMMR3DECL(int) SSMR3Load(PVM pVM, const char *pszFilename, PCSSMSTRMOPS pStreamOps, void *pvStreamOpsUser,
7703 SSMAFTER enmAfter, PFNVMPROGRESS pfnProgress, void *pvProgressUser)
7704{
7705 LogFlow(("SSMR3Load: pszFilename=%p:{%s} pStreamOps=%p pvStreamOpsUser=%p enmAfter=%d pfnProgress=%p pvProgressUser=%p\n",
7706 pszFilename, pszFilename, pStreamOps, pvStreamOpsUser, enmAfter, pfnProgress, pvProgressUser));
7707 VM_ASSERT_EMT0(pVM);
7708
7709 /*
7710 * Validate input.
7711 */
7712 AssertMsgReturn( enmAfter == SSMAFTER_RESUME
7713 || enmAfter == SSMAFTER_MIGRATE
7714 || enmAfter == SSMAFTER_DEBUG_IT,
7715 ("%d\n", enmAfter),
7716 VERR_INVALID_PARAMETER);
7717 AssertReturn(!pszFilename != !pStreamOps, VERR_INVALID_PARAMETER);
7718 if (pStreamOps)
7719 {
7720 AssertReturn(pStreamOps->u32Version == SSMSTRMOPS_VERSION, VERR_INVALID_MAGIC);
7721 AssertReturn(pStreamOps->u32EndVersion == SSMSTRMOPS_VERSION, VERR_INVALID_MAGIC);
7722 AssertReturn(pStreamOps->pfnWrite, VERR_INVALID_PARAMETER);
7723 AssertReturn(pStreamOps->pfnRead, VERR_INVALID_PARAMETER);
7724 AssertReturn(pStreamOps->pfnSeek, VERR_INVALID_PARAMETER);
7725 AssertReturn(pStreamOps->pfnTell, VERR_INVALID_PARAMETER);
7726 AssertReturn(pStreamOps->pfnSize, VERR_INVALID_PARAMETER);
7727 AssertReturn(pStreamOps->pfnClose, VERR_INVALID_PARAMETER);
7728 }
7729
7730 /*
7731 * Create the handle and open the file.
7732 */
7733 SSMHANDLE Handle;
7734 int rc = ssmR3OpenFile(pVM, pszFilename, pStreamOps, pvStreamOpsUser, false /* fChecksumIt */,
7735 true /* fChecksumOnRead */, 8 /*cBuffers*/, &Handle);
7736 if (RT_SUCCESS(rc))
7737 {
7738 ssmR3StrmStartIoThread(&Handle.Strm);
7739 ssmR3SetCancellable(pVM, &Handle, true);
7740
7741 Handle.enmAfter = enmAfter;
7742 Handle.pfnProgress = pfnProgress;
7743 Handle.pvUser = pvProgressUser;
7744
7745 if (Handle.u.Read.u16VerMajor)
7746 LogRel(("SSM: File header: Format %u.%u, VirtualBox Version %u.%u.%u r%u, %u-bit host, cbGCPhys=%u, cbGCPtr=%u\n",
7747 Handle.u.Read.uFmtVerMajor, Handle.u.Read.uFmtVerMinor,
7748 Handle.u.Read.u16VerMajor, Handle.u.Read.u16VerMinor, Handle.u.Read.u32VerBuild, Handle.u.Read.u32SvnRev,
7749 Handle.u.Read.cHostBits, Handle.u.Read.cbGCPhys, Handle.u.Read.cbGCPtr));
7750 else
7751 LogRel(("SSM: File header: Format %u.%u, %u-bit host, cbGCPhys=%u, cbGCPtr=%u\n" ,
7752 Handle.u.Read.uFmtVerMajor, Handle.u.Read.uFmtVerMinor,
7753 Handle.u.Read.cHostBits, Handle.u.Read.cbGCPhys, Handle.u.Read.cbGCPtr));
7754
7755 if (pfnProgress)
7756 pfnProgress(pVM, Handle.uPercent, pvProgressUser);
7757
7758 /*
7759 * Clear the per unit flags.
7760 */
7761 PSSMUNIT pUnit;
7762 for (pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
7763 pUnit->fCalled = false;
7764
7765 /*
7766 * Do the prepare run.
7767 */
7768 Handle.rc = VINF_SUCCESS;
7769 Handle.enmOp = SSMSTATE_LOAD_PREP;
7770 for (pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
7771 {
7772 if (pUnit->u.Common.pfnLoadPrep)
7773 {
7774 pUnit->fCalled = true;
7775 switch (pUnit->enmType)
7776 {
7777 case SSMUNITTYPE_DEV:
7778 rc = pUnit->u.Dev.pfnLoadPrep(pUnit->u.Dev.pDevIns, &Handle);
7779 break;
7780 case SSMUNITTYPE_DRV:
7781 rc = pUnit->u.Drv.pfnLoadPrep(pUnit->u.Drv.pDrvIns, &Handle);
7782 break;
7783 case SSMUNITTYPE_INTERNAL:
7784 rc = pUnit->u.Internal.pfnLoadPrep(pVM, &Handle);
7785 break;
7786 case SSMUNITTYPE_EXTERNAL:
7787 rc = pUnit->u.External.pfnLoadPrep(&Handle, pUnit->u.External.pvUser);
7788 break;
7789 default:
7790 rc = VERR_INTERNAL_ERROR;
7791 break;
7792 }
7793 if (RT_FAILURE(rc) && RT_SUCCESS_NP(Handle.rc))
7794 Handle.rc = rc;
7795 else
7796 rc = Handle.rc;
7797 if (RT_FAILURE(rc))
7798 {
7799 LogRel(("SSM: Prepare load failed with rc=%Rrc for data unit '%s.\n", rc, pUnit->szName));
7800 break;
7801 }
7802 }
7803 }
7804
7805 /* pending 2% */
7806 if (pfnProgress)
7807 pfnProgress(pVM, Handle.uPercentPrepare-1, pvProgressUser);
7808 Handle.uPercent = Handle.uPercentPrepare;
7809 Handle.cbEstTotal = Handle.u.Read.cbLoadFile;
7810 Handle.offEstUnitEnd = Handle.u.Read.cbLoadFile;
7811
7812 /*
7813 * Do the execute run.
7814 */
7815 if (RT_SUCCESS(rc))
7816 {
7817 if (Handle.u.Read.uFmtVerMajor >= 2)
7818 rc = ssmR3LoadExecV2(pVM, &Handle);
7819 else
7820 rc = ssmR3LoadExecV1(pVM, &Handle);
7821
7822 /* (progress should be pending 99% now) */
7823 AssertMsg( Handle.fLiveSave
7824 || RT_FAILURE(rc)
7825 || Handle.uPercent == (101-Handle.uPercentDone), ("%d\n", Handle.uPercent));
7826 }
7827
7828 /*
7829 * Do the done run.
7830 */
7831 Handle.rc = rc;
7832 Handle.enmOp = SSMSTATE_LOAD_DONE;
7833 for (pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
7834 {
7835 if ( pUnit->u.Common.pfnLoadDone
7836 && ( pUnit->fCalled
7837 || (!pUnit->u.Common.pfnLoadPrep && !pUnit->u.Common.pfnLoadExec)))
7838 {
7839 int const rcOld = Handle.rc;
7840 rc = VINF_SUCCESS;
7841 switch (pUnit->enmType)
7842 {
7843 case SSMUNITTYPE_DEV:
7844 rc = pUnit->u.Dev.pfnLoadDone(pUnit->u.Dev.pDevIns, &Handle);
7845 break;
7846 case SSMUNITTYPE_DRV:
7847 rc = pUnit->u.Drv.pfnLoadDone(pUnit->u.Drv.pDrvIns, &Handle);
7848 break;
7849 case SSMUNITTYPE_INTERNAL:
7850 rc = pUnit->u.Internal.pfnLoadDone(pVM, &Handle);
7851 break;
7852 case SSMUNITTYPE_EXTERNAL:
7853 rc = pUnit->u.External.pfnLoadDone(&Handle, pUnit->u.External.pvUser);
7854 break;
7855 default:
7856 rc = VERR_INTERNAL_ERROR;
7857 break;
7858 }
7859 if (RT_SUCCESS(rc) && Handle.rc != rcOld)
7860 rc = Handle.rc;
7861 if (RT_FAILURE(rc))
7862 {
7863 LogRel(("SSM: LoadDone failed with rc=%Rrc for data unit '%s' instance #%u.\n",
7864 rc, pUnit->szName, pUnit->u32Instance));
7865 if (RT_SUCCESS_NP(Handle.rc))
7866 Handle.rc = rc;
7867 }
7868 }
7869 }
7870 rc = Handle.rc;
7871
7872 /* progress */
7873 if (pfnProgress)
7874 pfnProgress(pVM, 99, pvProgressUser);
7875
7876 ssmR3SetCancellable(pVM, &Handle, false);
7877 ssmR3StrmClose(&Handle.Strm);
7878 }
7879
7880 /*
7881 * Done
7882 */
7883 if (RT_SUCCESS(rc))
7884 {
7885 /* progress */
7886 if (pfnProgress)
7887 pfnProgress(pVM, 100, pvProgressUser);
7888 Log(("SSM: Load of '%s' completed!\n", pszFilename));
7889 }
7890 return rc;
7891}
7892
7893
7894/**
7895 * Validates a file as a validate SSM saved state.
7896 *
7897 * This will only verify the file format, the format and content of individual
7898 * data units are not inspected.
7899 *
7900 * @returns VINF_SUCCESS if valid.
7901 * @returns VBox status code on other failures.
7902 *
7903 * @param pszFilename The path to the file to validate.
7904 * @param fChecksumIt Whether to checksum the file or not.
7905 *
7906 * @thread Any.
7907 */
7908VMMR3DECL(int) SSMR3ValidateFile(const char *pszFilename, bool fChecksumIt)
7909{
7910 LogFlow(("SSMR3ValidateFile: pszFilename=%p:{%s} fChecksumIt=%RTbool\n", pszFilename, pszFilename, fChecksumIt));
7911
7912 /*
7913 * Try open the file and validate it.
7914 */
7915 SSMHANDLE Handle;
7916 int rc = ssmR3OpenFile(NULL, pszFilename, NULL /*pStreamOps*/, NULL /*pvUser*/, fChecksumIt,
7917 false /*fChecksumOnRead*/, 1 /*cBuffers*/, &Handle);
7918 if (RT_SUCCESS(rc))
7919 ssmR3StrmClose(&Handle.Strm);
7920 else
7921 Log(("SSM: Failed to open saved state file '%s', rc=%Rrc.\n", pszFilename, rc));
7922 return rc;
7923}
7924
7925
7926/**
7927 * Opens a saved state file for reading.
7928 *
7929 * @returns VBox status code.
7930 *
7931 * @param pszFilename The path to the saved state file.
7932 * @param fFlags Open flags. Reserved, must be 0.
7933 * @param ppSSM Where to store the SSM handle.
7934 *
7935 * @thread Any.
7936 */
7937VMMR3DECL(int) SSMR3Open(const char *pszFilename, unsigned fFlags, PSSMHANDLE *ppSSM)
7938{
7939 LogFlow(("SSMR3Open: pszFilename=%p:{%s} fFlags=%#x ppSSM=%p\n", pszFilename, pszFilename, fFlags, ppSSM));
7940
7941 /*
7942 * Validate input.
7943 */
7944 AssertMsgReturn(VALID_PTR(pszFilename), ("%p\n", pszFilename), VERR_INVALID_PARAMETER);
7945 AssertMsgReturn(!fFlags, ("%#x\n", fFlags), VERR_INVALID_PARAMETER);
7946 AssertMsgReturn(VALID_PTR(ppSSM), ("%p\n", ppSSM), VERR_INVALID_PARAMETER);
7947
7948 /*
7949 * Allocate a handle.
7950 */
7951 PSSMHANDLE pSSM = (PSSMHANDLE)RTMemAllocZ(sizeof(*pSSM));
7952 AssertReturn(pSSM, VERR_NO_MEMORY);
7953
7954 /*
7955 * Try open the file and validate it.
7956 */
7957 int rc = ssmR3OpenFile(NULL, pszFilename, NULL /*pStreamOps*/, NULL /*pvUser*/, false /*fChecksumIt*/,
7958 true /*fChecksumOnRead*/, 1 /*cBuffers*/, pSSM);
7959 if (RT_SUCCESS(rc))
7960 {
7961 pSSM->enmAfter = SSMAFTER_OPENED;
7962 pSSM->enmOp = SSMSTATE_OPEN_READ;
7963 *ppSSM = pSSM;
7964 LogFlow(("SSMR3Open: returns VINF_SUCCESS *ppSSM=%p\n", *ppSSM));
7965 return VINF_SUCCESS;
7966 }
7967
7968 Log(("SSMR3Open: Failed to open saved state file '%s', rc=%Rrc.\n", pszFilename, rc));
7969 RTMemFree(pSSM);
7970 return rc;
7971
7972}
7973
7974
7975/**
7976 * Closes a saved state file opened by SSMR3Open().
7977 *
7978 * @returns VBox status code.
7979 *
7980 * @param pSSM The SSM handle returned by SSMR3Open().
7981 *
7982 * @thread Any, but the caller is responsible for serializing calls per handle.
7983 */
7984VMMR3DECL(int) SSMR3Close(PSSMHANDLE pSSM)
7985{
7986 LogFlow(("SSMR3Close: pSSM=%p\n", pSSM));
7987
7988 /*
7989 * Validate input.
7990 */
7991 AssertMsgReturn(VALID_PTR(pSSM), ("%p\n", pSSM), VERR_INVALID_PARAMETER);
7992 AssertMsgReturn(pSSM->enmAfter == SSMAFTER_OPENED, ("%d\n", pSSM->enmAfter),VERR_INVALID_PARAMETER);
7993 AssertMsgReturn(pSSM->enmOp == SSMSTATE_OPEN_READ, ("%d\n", pSSM->enmOp), VERR_INVALID_PARAMETER);
7994 Assert(pSSM->fCancelled == SSMHANDLE_OK);
7995
7996 /*
7997 * Close the stream and free the handle.
7998 */
7999 int rc = ssmR3StrmClose(&pSSM->Strm);
8000 if (pSSM->u.Read.pZipDecompV1)
8001 {
8002 RTZipDecompDestroy(pSSM->u.Read.pZipDecompV1);
8003 pSSM->u.Read.pZipDecompV1 = NULL;
8004 }
8005 RTMemFree(pSSM);
8006 return rc;
8007}
8008
8009
8010/**
8011 * Worker for SSMR3Seek that seeks version 1 saved state files.
8012 *
8013 * @returns VBox status code.
8014 * @param pSSM The SSM handle.
8015 * @param pszUnit The unit to seek to.
8016 * @param iInstance The particulart insance we seek.
8017 * @param piVersion Where to store the unit version number.
8018 */
8019static int ssmR3FileSeekV1(PSSMHANDLE pSSM, const char *pszUnit, uint32_t iInstance, uint32_t *piVersion)
8020{
8021 /*
8022 * Walk the data units until we find EOF or a match.
8023 */
8024 size_t cbUnitNm = strlen(pszUnit) + 1;
8025 AssertLogRelReturn(cbUnitNm <= SSM_MAX_NAME_SIZE, VERR_SSM_UNIT_NOT_FOUND);
8026 char szName[SSM_MAX_NAME_SIZE];
8027 SSMFILEUNITHDRV1 UnitHdr;
8028 for (RTFOFF off = pSSM->u.Read.cbFileHdr; ; off += UnitHdr.cbUnit)
8029 {
8030 /*
8031 * Read the unit header and verify it.
8032 */
8033 int rc = ssmR3StrmPeekAt(&pSSM->Strm, off, &UnitHdr, RT_OFFSETOF(SSMFILEUNITHDRV1, szName), NULL);
8034 AssertRCReturn(rc, rc);
8035 if (!memcmp(&UnitHdr.achMagic[0], SSMFILEUNITHDR_MAGIC, sizeof(SSMFILEUNITHDR_MAGIC)))
8036 {
8037 /*
8038 * Does what we've got match, if so read the name.
8039 */
8040 if ( UnitHdr.u32Instance == iInstance
8041 && UnitHdr.cchName == cbUnitNm)
8042 {
8043 rc = ssmR3StrmPeekAt(&pSSM->Strm, off + RT_OFFSETOF(SSMFILEUNITHDRV1, szName), szName, cbUnitNm, NULL);
8044 AssertRCReturn(rc, rc);
8045 AssertLogRelMsgReturn(!szName[UnitHdr.cchName - 1],
8046 (" Unit name '%.*s' was not properly terminated.\n", cbUnitNm, szName),
8047 VERR_SSM_INTEGRITY_UNIT);
8048
8049 /*
8050 * Does the name match?
8051 */
8052 if (!memcmp(szName, pszUnit, cbUnitNm))
8053 {
8054 rc = ssmR3StrmSeek(&pSSM->Strm, off + RT_OFFSETOF(SSMFILEUNITHDRV1, szName) + cbUnitNm, RTFILE_SEEK_BEGIN, 0);
8055 pSSM->cbUnitLeftV1 = UnitHdr.cbUnit - RT_OFFSETOF(SSMFILEUNITHDRV1, szName[cbUnitNm]);
8056 pSSM->offUnit = 0;
8057 if (piVersion)
8058 *piVersion = UnitHdr.u32Version;
8059 return VINF_SUCCESS;
8060 }
8061 }
8062 }
8063 else if (!memcmp(&UnitHdr.achMagic[0], SSMFILEUNITHDR_END, sizeof(SSMFILEUNITHDR_END)))
8064 return VERR_SSM_UNIT_NOT_FOUND;
8065 else
8066 AssertLogRelMsgFailedReturn(("Invalid unit magic at offset %RTfoff, '%.*s'!\n",
8067 off, sizeof(UnitHdr.achMagic) - 1, &UnitHdr.achMagic[0]),
8068 VERR_SSM_INTEGRITY_UNIT_MAGIC);
8069 }
8070 /* won't get here. */
8071}
8072
8073
8074/**
8075 * Worker for ssmR3FileSeekV2 for simplifying memory cleanup.
8076 *
8077 * @returns VBox status code.
8078 * @param pSSM The SSM handle.
8079 * @param pDir The directory buffer.
8080 * @param cbDir The size of the directory.
8081 * @param cDirEntries The number of directory entries.
8082 * @param offDir The directory offset in the file.
8083 * @param pszUnit The unit to seek to.
8084 * @param iInstance The particulart insance we seek.
8085 * @param piVersion Where to store the unit version number.
8086 */
8087static int ssmR3FileSeekSubV2(PSSMHANDLE pSSM, PSSMFILEDIR pDir, size_t cbDir, uint32_t cDirEntries, uint64_t offDir,
8088 const char *pszUnit, uint32_t iInstance, uint32_t *piVersion)
8089{
8090 /*
8091 * Read it.
8092 */
8093 int rc = ssmR3StrmPeekAt(&pSSM->Strm, offDir, pDir, cbDir, NULL);
8094 AssertLogRelRCReturn(rc, rc);
8095 rc = ssmR3ValidateDirectory(pDir, cbDir, offDir, cDirEntries, pSSM->u.Read.cbFileHdr, pSSM->u.Read.u32SvnRev);
8096 if (RT_FAILURE(rc))
8097 return rc;
8098
8099 /*
8100 * Search the directory.
8101 */
8102 size_t cbUnitNm = strlen(pszUnit) + 1;
8103 uint32_t const u32NameCRC = RTCrc32(pszUnit, cbUnitNm - 1);
8104 for (uint32_t i = 0; i < cDirEntries; i++)
8105 {
8106 if ( pDir->aEntries[i].u32NameCRC == u32NameCRC
8107 && pDir->aEntries[i].u32Instance == iInstance
8108 && pDir->aEntries[i].off != 0 /* bug in unreleased code */
8109 )
8110 {
8111 /*
8112 * Read and validate the unit header.
8113 */
8114 SSMFILEUNITHDRV2 UnitHdr;
8115 size_t cbToRead = sizeof(UnitHdr);
8116 if (pDir->aEntries[i].off + cbToRead > offDir)
8117 {
8118 cbToRead = offDir - pDir->aEntries[i].off;
8119 RT_ZERO(UnitHdr);
8120 }
8121 rc = ssmR3StrmPeekAt(&pSSM->Strm, pDir->aEntries[i].off, &UnitHdr, cbToRead, NULL);
8122 AssertLogRelRCReturn(rc, rc);
8123
8124 AssertLogRelMsgReturn(!memcmp(UnitHdr.szMagic, SSMFILEUNITHDR_MAGIC, sizeof(UnitHdr.szMagic)),
8125 ("Bad unit header or dictionary offset: i=%u off=%lld\n", i, pDir->aEntries[i].off),
8126 VERR_SSM_INTEGRITY_UNIT);
8127 AssertLogRelMsgReturn(UnitHdr.offStream == pDir->aEntries[i].off,
8128 ("Bad unit header: i=%d off=%lld offStream=%lld\n", i, pDir->aEntries[i].off, UnitHdr.offStream),
8129 VERR_SSM_INTEGRITY_UNIT);
8130 AssertLogRelMsgReturn(UnitHdr.u32Instance == pDir->aEntries[i].u32Instance,
8131 ("Bad unit header: i=%d off=%lld u32Instance=%u Dir.u32Instance=%u\n",
8132 i, pDir->aEntries[i].off, UnitHdr.u32Instance, pDir->aEntries[i].u32Instance),
8133 VERR_SSM_INTEGRITY_UNIT);
8134 uint32_t cbUnitHdr = RT_UOFFSETOF(SSMFILEUNITHDRV2, szName[UnitHdr.cbName]);
8135 AssertLogRelMsgReturn( UnitHdr.cbName > 0
8136 && UnitHdr.cbName < sizeof(UnitHdr)
8137 && cbUnitHdr <= cbToRead,
8138 ("Bad unit header: i=%u off=%lld cbName=%#x cbToRead=%#x\n", i, pDir->aEntries[i].off, UnitHdr.cbName, cbToRead),
8139 VERR_SSM_INTEGRITY_UNIT);
8140 SSM_CHECK_CRC32_RET(&UnitHdr, RT_OFFSETOF(SSMFILEUNITHDRV2, szName[UnitHdr.cbName]),
8141 ("Bad unit header CRC: i=%u off=%lld u32CRC=%#x u32ActualCRC=%#x\n",
8142 i, pDir->aEntries[i].off, u32CRC, u32ActualCRC));
8143
8144 /*
8145 * Ok, it is valid, get on with the comparing now.
8146 */
8147 if ( UnitHdr.cbName == cbUnitNm
8148 && !memcmp(UnitHdr.szName, pszUnit, cbUnitNm))
8149 {
8150 if (piVersion)
8151 *piVersion = UnitHdr.u32Version;
8152 rc = ssmR3StrmSeek(&pSSM->Strm, pDir->aEntries[i].off + cbUnitHdr, RTFILE_SEEK_BEGIN,
8153 RTCrc32Process(UnitHdr.u32CurStreamCRC, &UnitHdr, cbUnitHdr));
8154 AssertLogRelRCReturn(rc, rc);
8155 ssmR3DataReadBeginV2(pSSM);
8156 return VINF_SUCCESS;
8157 }
8158 }
8159 }
8160
8161 return VERR_SSM_UNIT_NOT_FOUND;
8162}
8163
8164
8165/**
8166 * Worker for SSMR3Seek that seeks version 2 saved state files.
8167 *
8168 * @returns VBox status code.
8169 * @param pSSM The SSM handle.
8170 * @param pszUnit The unit to seek to.
8171 * @param iInstance The particulart insance we seek.
8172 * @param piVersion Where to store the unit version number.
8173 */
8174static int ssmR3FileSeekV2(PSSMHANDLE pSSM, const char *pszUnit, uint32_t iInstance, uint32_t *piVersion)
8175{
8176 /*
8177 * Read the footer, allocate a temporary buffer for the dictionary and
8178 * pass it down to a worker to simplify cleanup.
8179 */
8180 uint64_t offFooter;
8181 SSMFILEFTR Footer;
8182 int rc = ssmR3StrmPeekAt(&pSSM->Strm, -(RTFOFF)sizeof(Footer), &Footer, sizeof(Footer), &offFooter);
8183 AssertLogRelRCReturn(rc, rc);
8184 AssertLogRelReturn(!memcmp(Footer.szMagic, SSMFILEFTR_MAGIC, sizeof(Footer.szMagic)), VERR_SSM_INTEGRITY);
8185 SSM_CHECK_CRC32_RET(&Footer, sizeof(Footer), ("Bad footer CRC: %08x, actual %08x\n", u32CRC, u32ActualCRC));
8186
8187 size_t const cbDir = RT_OFFSETOF(SSMFILEDIR, aEntries[Footer.cDirEntries]);
8188 PSSMFILEDIR pDir = (PSSMFILEDIR)RTMemTmpAlloc(cbDir);
8189 if (RT_UNLIKELY(!pDir))
8190 return VERR_NO_TMP_MEMORY;
8191 rc = ssmR3FileSeekSubV2(pSSM, pDir, cbDir, Footer.cDirEntries, offFooter - cbDir,
8192 pszUnit, iInstance, piVersion);
8193 RTMemTmpFree(pDir);
8194
8195 return rc;
8196}
8197
8198
8199/**
8200 * Seeks to a specific data unit.
8201 *
8202 * After seeking it's possible to use the getters to on
8203 * that data unit.
8204 *
8205 * @returns VBox status code.
8206 * @returns VERR_SSM_UNIT_NOT_FOUND if the unit+instance wasn't found.
8207 *
8208 * @param pSSM The SSM handle returned by SSMR3Open().
8209 * @param pszUnit The name of the data unit.
8210 * @param iInstance The instance number.
8211 * @param piVersion Where to store the version number. (Optional)
8212 *
8213 * @thread Any, but the caller is responsible for serializing calls per handle.
8214 */
8215VMMR3DECL(int) SSMR3Seek(PSSMHANDLE pSSM, const char *pszUnit, uint32_t iInstance, uint32_t *piVersion)
8216{
8217 LogFlow(("SSMR3Seek: pSSM=%p pszUnit=%p:{%s} iInstance=%RU32 piVersion=%p\n",
8218 pSSM, pszUnit, pszUnit, iInstance, piVersion));
8219
8220 /*
8221 * Validate input.
8222 */
8223 AssertPtrReturn(pSSM, VERR_INVALID_PARAMETER);
8224 AssertMsgReturn(pSSM->enmAfter == SSMAFTER_OPENED, ("%d\n", pSSM->enmAfter),VERR_INVALID_PARAMETER);
8225 AssertMsgReturn(pSSM->enmOp == SSMSTATE_OPEN_READ, ("%d\n", pSSM->enmOp), VERR_INVALID_PARAMETER);
8226 AssertPtrReturn(pszUnit, VERR_INVALID_POINTER);
8227 AssertMsgReturn(!piVersion || VALID_PTR(piVersion), ("%p\n", piVersion), VERR_INVALID_POINTER);
8228
8229 /*
8230 * Reset the state.
8231 */
8232 if (pSSM->u.Read.pZipDecompV1)
8233 {
8234 RTZipDecompDestroy(pSSM->u.Read.pZipDecompV1);
8235 pSSM->u.Read.pZipDecompV1 = NULL;
8236 }
8237 pSSM->cbUnitLeftV1 = 0;
8238 pSSM->offUnit = UINT64_MAX;
8239
8240 /*
8241 * Call the version specific workers.
8242 */
8243 if (pSSM->u.Read.uFmtVerMajor >= 2)
8244 pSSM->rc = ssmR3FileSeekV2(pSSM, pszUnit, iInstance, piVersion);
8245 else
8246 pSSM->rc = ssmR3FileSeekV1(pSSM, pszUnit, iInstance, piVersion);
8247 return pSSM->rc;
8248}
8249
8250
8251
8252/* ... Misc APIs ... */
8253/* ... Misc APIs ... */
8254/* ... Misc APIs ... */
8255/* ... Misc APIs ... */
8256/* ... Misc APIs ... */
8257/* ... Misc APIs ... */
8258/* ... Misc APIs ... */
8259/* ... Misc APIs ... */
8260/* ... Misc APIs ... */
8261/* ... Misc APIs ... */
8262/* ... Misc APIs ... */
8263
8264
8265
8266/**
8267 * Query what the VBox status code of the operation is.
8268 *
8269 * This can be used for putting and getting a batch of values
8270 * without bother checking the result till all the calls have
8271 * been made.
8272 *
8273 * @returns SSMAFTER enum value.
8274 * @param pSSM The saved state handle.
8275 */
8276VMMR3DECL(int) SSMR3HandleGetStatus(PSSMHANDLE pSSM)
8277{
8278 SSM_ASSERT_VALID_HANDLE(pSSM);
8279 return pSSM->rc;
8280}
8281
8282
8283/**
8284 * Fail the load operation.
8285 *
8286 * This is mainly intended for sub item loaders (like timers) which
8287 * return code isn't necessarily heeded by the caller but is important
8288 * to SSM.
8289 *
8290 * @returns VBox status code of the handle, or VERR_INVALID_PARAMETER.
8291 * @param pSSM The saved state handle.
8292 * @param iStatus Failure status code. This MUST be a VERR_*.
8293 */
8294VMMR3DECL(int) SSMR3HandleSetStatus(PSSMHANDLE pSSM, int iStatus)
8295{
8296 SSM_ASSERT_VALID_HANDLE(pSSM);
8297 Assert(pSSM->enmOp != SSMSTATE_LIVE_VOTE);
8298 if (RT_FAILURE(iStatus))
8299 {
8300 int rc = pSSM->rc;
8301 if (RT_SUCCESS(rc))
8302 pSSM->rc = rc = iStatus;
8303 return rc;
8304 }
8305 AssertMsgFailed(("iStatus=%d %Rrc\n", iStatus, iStatus));
8306 return VERR_INVALID_PARAMETER;
8307}
8308
8309
8310/**
8311 * Get what to do after this operation.
8312 *
8313 * @returns SSMAFTER enum value.
8314 * @param pSSM The saved state handle.
8315 */
8316VMMR3DECL(SSMAFTER) SSMR3HandleGetAfter(PSSMHANDLE pSSM)
8317{
8318 SSM_ASSERT_VALID_HANDLE(pSSM);
8319 return pSSM->enmAfter;
8320}
8321
8322
8323/**
8324 * Checks if it is a live save operation or not.
8325 *
8326 * @returns True if it is, false if it isn't.
8327 * @param pSSM The saved state handle.
8328 */
8329VMMR3DECL(bool) SSMR3HandleIsLiveSave(PSSMHANDLE pSSM)
8330{
8331 SSM_ASSERT_VALID_HANDLE(pSSM);
8332 return pSSM->fLiveSave;
8333}
8334
8335
8336/**
8337 * Gets the host bit count of a saved state.
8338 *
8339 * @returns 32 or 64. If pSSM is invalid, 0 is returned.
8340 * @param pSSM The saved state handle.
8341 */
8342VMMR3DECL(uint32_t) SSMR3HandleHostBits(PSSMHANDLE pSSM)
8343{
8344 SSM_ASSERT_VALID_HANDLE(pSSM);
8345 return ssmR3GetHostBits(pSSM);
8346}
8347
8348
8349/**
8350 * Asynchronously cancels the current SSM operation ASAP.
8351 *
8352 * @returns VBox status code.
8353 * @retval VINF_SUCCESS on success.
8354 * @retval VERR_SSM_NO_PENDING_OPERATION if nothing around that can be
8355 * cancelled.
8356 * @retval VERR_SSM_ALREADY_CANCELLED if the operation as already been
8357 * cancelled.
8358 *
8359 * @param pVM The VM handle.
8360 *
8361 * @thread Any.
8362 */
8363VMMR3DECL(int) SSMR3Cancel(PVM pVM)
8364{
8365 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
8366
8367 int rc = RTCritSectEnter(&pVM->ssm.s.CancelCritSect);
8368 AssertRCReturn(rc, rc);
8369
8370 PSSMHANDLE pSSM = pVM->ssm.s.pSSM;
8371 if (pSSM)
8372 {
8373 uint32_t u32Old;
8374 if (ASMAtomicCmpXchgExU32(&pSSM->fCancelled, SSMHANDLE_CANCELLED, SSMHANDLE_OK, &u32Old))
8375 {
8376 LogRel(("SSM: Cancelled pending operation\n"));
8377 rc = VINF_SUCCESS;
8378 }
8379 else if (u32Old == SSMHANDLE_CANCELLED)
8380 rc = VERR_SSM_ALREADY_CANCELLED;
8381 else
8382 {
8383 AssertLogRelMsgFailed(("fCancelled=%RX32 enmOp=%d\n", u32Old, pSSM->enmOp));
8384 rc = VERR_INTERNAL_ERROR_2;
8385 }
8386 }
8387 else
8388 rc = VERR_SSM_NO_PENDING_OPERATION;
8389
8390 RTCritSectLeave(&pVM->ssm.s.CancelCritSect);
8391 return rc;
8392}
8393
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette