VirtualBox

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

Last change on this file since 56965 was 56965, checked in by vboxsync, 9 years ago

SSM.cpp: Dump (part of) the data unit on load failure to make it easier to debug.

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

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