VirtualBox

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

最後變更 在這個檔案從39078是 39078,由 vboxsync 提交於 13 年 前

VMM: -Wunused-parameter

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

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