VirtualBox

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

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

ssmR3StrmClose: Signal the right semaphore. Fixes deadlock when cancelled on the source side of a teleportation.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use