VirtualBox

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

Last change on this file since 23781 was 23780, checked in by vboxsync, 16 years ago

SSM: Adding IGN_GCPTR and IGN_GCPHYS just in case.

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

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