VirtualBox

source: vbox/trunk/src/VBox/Main/src-all/NvramStoreImpl.cpp@ 99040

Last change on this file since 99040 was 98262, checked in by vboxsync, 22 months ago

Main: rc() -> hrc()/vrc(). bugref:10223

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 49.9 KB
Line 
1/* $Id: NvramStoreImpl.cpp 98262 2023-01-24 01:42:14Z vboxsync $ */
2/** @file
3 * VirtualBox COM NVRAM store class implementation
4 */
5
6/*
7 * Copyright (C) 2021-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28#define LOG_GROUP LOG_GROUP_MAIN_NVRAMSTORE
29#include "LoggingNew.h"
30
31#include "NvramStoreImpl.h"
32#ifdef VBOX_COM_INPROC
33# include "ConsoleImpl.h"
34#else
35# include "MachineImpl.h"
36# include "GuestOSTypeImpl.h"
37# include "AutoStateDep.h"
38#endif
39#include "UefiVariableStoreImpl.h"
40#include "VirtualBoxImpl.h"
41
42#include "AutoCaller.h"
43
44#include <VBox/com/array.h>
45#include <VBox/vmm/pdmdrv.h>
46#include <VBox/err.h>
47
48#include <iprt/cpp/utils.h>
49#include <iprt/efi.h>
50#include <iprt/file.h>
51#include <iprt/vfs.h>
52#include <iprt/zip.h>
53
54
55// defines
56////////////////////////////////////////////////////////////////////////////////
57
58/** Version of the NVRAM saved state unit. */
59#define NVRAM_STORE_SAVED_STATE_VERSION 1
60
61
62// globals
63////////////////////////////////////////////////////////////////////////////////
64
65/**
66 * NVRAM store driver instance data.
67 */
68typedef struct DRVMAINNVRAMSTORE
69{
70 /** Pointer to the keyboard object. */
71 NvramStore *pNvramStore;
72 /** Pointer to the driver instance structure. */
73 PPDMDRVINS pDrvIns;
74 /** Our VFS connector interface. */
75 PDMIVFSCONNECTOR IVfs;
76} DRVMAINNVRAMSTORE, *PDRVMAINNVRAMSTORE;
77
78/** The NVRAM store map keyed by namespace/entity. */
79typedef std::map<Utf8Str, RTVFSFILE> NvramStoreMap;
80/** The NVRAM store map iterator. */
81typedef std::map<Utf8Str, RTVFSFILE>::iterator NvramStoreIter;
82
83struct BackupableNvramStoreData
84{
85 BackupableNvramStoreData()
86 { }
87
88 /** The NVRAM file path. */
89 com::Utf8Str strNvramPath;
90#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
91 /** The key id used for encrypting the NVRAM file */
92 com::Utf8Str strKeyId;
93 /** The key store containing the encrypting DEK */
94 com::Utf8Str strKeyStore;
95#endif
96 /** The NVRAM store. */
97 NvramStoreMap mapNvram;
98};
99
100/////////////////////////////////////////////////////////////////////////////
101// NvramStore::Data structure
102/////////////////////////////////////////////////////////////////////////////
103
104struct NvramStore::Data
105{
106 Data()
107 : pParent(NULL)
108#ifdef VBOX_COM_INPROC
109 , cRefs(0)
110 , fSsmSaved(false)
111#endif
112#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
113 , mpKeyStore(NULL)
114#endif
115 { }
116
117#ifdef VBOX_COM_INPROC
118 /** The Console owning this NVRAM store. */
119 Console * const pParent;
120 /** Number of references held to this NVRAM store from the various devices/drivers. */
121 volatile uint32_t cRefs;
122 /** Flag whether the NVRAM data was saved during a save state operation
123 * preventing it from getting written to the backing file. */
124 bool fSsmSaved;
125#else
126 /** The Machine object owning this NVRAM store. */
127 Machine * const pParent;
128 /** The peer NVRAM store object. */
129 ComObjPtr<NvramStore> pPeer;
130 /** The UEFI variable store. */
131 const ComObjPtr<UefiVariableStore> pUefiVarStore;
132#endif
133
134#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
135 /* Store for secret keys. */
136 SecretKeyStore *mpKeyStore;
137#endif
138
139 Backupable<BackupableNvramStoreData> bd;
140};
141
142// constructor / destructor
143////////////////////////////////////////////////////////////////////////////////
144
145DEFINE_EMPTY_CTOR_DTOR(NvramStore)
146
147HRESULT NvramStore::FinalConstruct()
148{
149 return BaseFinalConstruct();
150}
151
152void NvramStore::FinalRelease()
153{
154 uninit();
155 BaseFinalRelease();
156}
157
158// public initializer/uninitializer for internal purposes only
159/////////////////////////////////////////////////////////////////////////////
160
161/**
162 * Initialization stuff shared across the different methods.
163 *
164 * @returns COM result indicator
165 */
166int NvramStore::initImpl()
167{
168 m = new Data();
169
170#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
171# ifdef VBOX_COM_INPROC
172 bool fNonPageable = true;
173# else
174 /* Non-pageable memory is not accessible for non-VM process */
175 bool fNonPageable = false;
176# endif
177
178 m->mpKeyStore = new SecretKeyStore(fNonPageable /* fKeyBufNonPageable */);
179 AssertReturn(m->mpKeyStore, VERR_NO_MEMORY);
180#endif
181
182 return VINF_SUCCESS;
183}
184
185
186#if !defined(VBOX_COM_INPROC)
187/**
188 * Initializes the NVRAM store object.
189 *
190 * @returns COM result indicator
191 */
192HRESULT NvramStore::init(Machine *aParent)
193{
194 LogFlowThisFuncEnter();
195 LogFlowThisFunc(("aParent: %p\n", aParent));
196
197 ComAssertRet(aParent, E_INVALIDARG);
198
199 /* Enclose the state transition NotReady->InInit->Ready */
200 AutoInitSpan autoInitSpan(this);
201 AssertReturn(autoInitSpan.isOk(), E_FAIL);
202
203 int vrc = initImpl();
204 if (RT_FAILURE(vrc))
205 return E_FAIL;
206
207 /* share the parent weakly */
208 unconst(m->pParent) = aParent;
209
210 m->bd.allocate();
211
212 autoInitSpan.setSucceeded();
213
214 LogFlowThisFuncLeave();
215 return S_OK;
216}
217
218/**
219 * Initializes the NVRAM store object given another NVRAM store object
220 * (a kind of copy constructor). This object shares data with
221 * the object passed as an argument.
222 *
223 * @note This object must be destroyed before the original object
224 * it shares data with is destroyed.
225 */
226HRESULT NvramStore::init(Machine *aParent, NvramStore *that)
227{
228 LogFlowThisFuncEnter();
229 LogFlowThisFunc(("aParent: %p, that: %p\n", aParent, that));
230
231 ComAssertRet(aParent && that, E_INVALIDARG);
232
233 /* Enclose the state transition NotReady->InInit->Ready */
234 AutoInitSpan autoInitSpan(this);
235 AssertReturn(autoInitSpan.isOk(), E_FAIL);
236
237 initImpl();
238
239 unconst(m->pParent) = aParent;
240 m->pPeer = that;
241
242 AutoWriteLock thatlock(that COMMA_LOCKVAL_SRC_POS);
243 m->bd.share(that->m->bd);
244
245 autoInitSpan.setSucceeded();
246
247 LogFlowThisFuncLeave();
248 return S_OK;
249}
250
251/**
252 * Initializes the guest object given another guest object
253 * (a kind of copy constructor). This object makes a private copy of data
254 * of the original object passed as an argument.
255 */
256HRESULT NvramStore::initCopy(Machine *aParent, NvramStore *that)
257{
258 LogFlowThisFuncEnter();
259 LogFlowThisFunc(("aParent: %p, that: %p\n", aParent, that));
260
261 ComAssertRet(aParent && that, E_INVALIDARG);
262
263 /* Enclose the state transition NotReady->InInit->Ready */
264 AutoInitSpan autoInitSpan(this);
265 AssertReturn(autoInitSpan.isOk(), E_FAIL);
266
267 initImpl();
268
269 unconst(m->pParent) = aParent;
270 // mPeer is left null
271
272 AutoWriteLock thatlock(that COMMA_LOCKVAL_SRC_POS);
273 m->bd.attachCopy(that->m->bd);
274
275 autoInitSpan.setSucceeded();
276
277 LogFlowThisFuncLeave();
278 return S_OK;
279}
280
281#else
282
283/**
284 * Initializes the NVRAM store object.
285 *
286 * @returns COM result indicator
287 * @param aParent Handle of our parent object
288 * @param strNonVolatileStorageFile The NVRAM file path.
289 */
290HRESULT NvramStore::init(Console *aParent, const com::Utf8Str &strNonVolatileStorageFile)
291{
292 LogFlowThisFunc(("aParent=%p\n", aParent));
293
294 ComAssertRet(aParent, E_INVALIDARG);
295
296 /* Enclose the state transition NotReady->InInit->Ready */
297 AutoInitSpan autoInitSpan(this);
298 AssertReturn(autoInitSpan.isOk(), E_FAIL);
299
300 initImpl();
301
302 unconst(m->pParent) = aParent;
303
304 m->bd.allocate();
305 m->bd->strNvramPath = strNonVolatileStorageFile;
306
307 /* Confirm a successful initialization */
308 autoInitSpan.setSucceeded();
309
310 return S_OK;
311}
312#endif /* VBOX_COM_INPROC */
313
314
315/**
316 * Uninitializes the instance and sets the ready flag to FALSE.
317 * Called either from FinalRelease() or by the parent when it gets destroyed.
318 */
319void NvramStore::uninit()
320{
321 LogFlowThisFuncEnter();
322
323 /* Enclose the state transition Ready->InUninit->NotReady */
324 AutoUninitSpan autoUninitSpan(this);
325 if (autoUninitSpan.uninitDone())
326 return;
327
328 unconst(m->pParent) = NULL;
329#ifndef VBOX_COM_INPROC
330 unconst(m->pUefiVarStore) = NULL;
331#endif
332
333 /* Delete the NVRAM content. */
334 NvramStoreIter it = m->bd->mapNvram.begin();
335 while (it != m->bd->mapNvram.end())
336 {
337 RTVfsFileRelease(it->second);
338 it++;
339 }
340
341 m->bd->mapNvram.clear();
342 m->bd.free();
343
344#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
345 if (m->mpKeyStore != NULL)
346 delete m->mpKeyStore;
347#endif
348
349 delete m;
350 m = NULL;
351
352 LogFlowThisFuncLeave();
353}
354
355
356HRESULT NvramStore::getNonVolatileStorageFile(com::Utf8Str &aNonVolatileStorageFile)
357{
358#ifndef VBOX_COM_INPROC
359 Utf8Str strTmp;
360 {
361 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
362 strTmp = m->bd->strNvramPath;
363 }
364
365 AutoReadLock mlock(m->pParent COMMA_LOCKVAL_SRC_POS);
366 if (strTmp.isEmpty())
367 strTmp = m->pParent->i_getDefaultNVRAMFilename();
368 if (strTmp.isNotEmpty())
369 m->pParent->i_calculateFullPath(strTmp, aNonVolatileStorageFile);
370#else
371 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
372 aNonVolatileStorageFile = m->bd->strNvramPath;
373#endif
374
375 return S_OK;
376}
377
378
379HRESULT NvramStore::getUefiVariableStore(ComPtr<IUefiVariableStore> &aUefiVarStore)
380{
381#ifndef VBOX_COM_INPROC
382 /* the machine needs to be mutable */
383 AutoMutableStateDependency adep(m->pParent);
384 if (FAILED(adep.hrc())) return adep.hrc();
385
386 Utf8Str strPath;
387 NvramStore::getNonVolatileStorageFile(strPath);
388
389 /* We need a write lock because of the lazy initialization. */
390 AutoWriteLock wlock(this COMMA_LOCKVAL_SRC_POS);
391
392 /* Check if we have to create the UEFI variable store object */
393 HRESULT hrc = S_OK;
394 if (!m->pUefiVarStore)
395 {
396 /* Load the NVRAM file first if it isn't already. */
397 if (!m->bd->mapNvram.size())
398 {
399 int vrc = i_loadStore(strPath.c_str());
400 if (RT_FAILURE(vrc))
401 hrc = setError(E_FAIL, tr("Loading the NVRAM store failed (%Rrc)\n"), vrc);
402 }
403
404 if (SUCCEEDED(hrc))
405 {
406 NvramStoreIter it = m->bd->mapNvram.find("efi/nvram");
407 if (it != m->bd->mapNvram.end())
408 {
409 unconst(m->pUefiVarStore).createObject();
410 m->pUefiVarStore->init(this, m->pParent);
411 }
412 else
413 hrc = setError(VBOX_E_OBJECT_NOT_FOUND, tr("The UEFI NVRAM file is not existing for this machine."));
414 }
415 }
416
417 if (SUCCEEDED(hrc))
418 {
419 m->pUefiVarStore.queryInterfaceTo(aUefiVarStore.asOutParam());
420
421 /* Mark the NVRAM store as potentially modified. */
422 m->pParent->i_setModified(Machine::IsModified_NvramStore);
423 }
424
425 return hrc;
426#else
427 NOREF(aUefiVarStore);
428 return E_NOTIMPL;
429#endif
430}
431
432
433HRESULT NvramStore::getKeyId(com::Utf8Str &aKeyId)
434{
435 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
436
437#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
438 aKeyId = m->bd->strKeyId;
439#else
440 aKeyId = com::Utf8Str::Empty;
441#endif
442
443 return S_OK;
444}
445
446
447HRESULT NvramStore::getKeyStore(com::Utf8Str &aKeyStore)
448{
449 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
450
451#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
452 aKeyStore = m->bd->strKeyStore;
453#else
454 aKeyStore = com::Utf8Str::Empty;
455#endif
456
457 return S_OK;
458}
459
460
461HRESULT NvramStore::initUefiVariableStore(ULONG aSize)
462{
463#ifndef VBOX_COM_INPROC
464 if (aSize != 0)
465 return setError(E_NOTIMPL, tr("Supporting another NVRAM size apart from the default one is not supported right now"));
466
467 /* the machine needs to be mutable */
468 AutoMutableStateDependency adep(m->pParent);
469 if (FAILED(adep.hrc())) return adep.hrc();
470
471 Utf8Str strPath;
472 NvramStore::getNonVolatileStorageFile(strPath);
473
474 /* We need a write lock because of the lazy initialization. */
475 AutoReadLock mlock(m->pParent COMMA_LOCKVAL_SRC_POS);
476 AutoWriteLock wlock(this COMMA_LOCKVAL_SRC_POS);
477
478 if (m->pParent->i_getFirmwareType() == FirmwareType_BIOS)
479 return setError(VBOX_E_NOT_SUPPORTED, tr("The selected firmware type doesn't support a UEFI variable store"));
480
481 /* Load the NVRAM file first if it isn't already. */
482 HRESULT hrc = S_OK;
483 if (!m->bd->mapNvram.size())
484 {
485 int vrc = i_loadStore(strPath.c_str());
486 if (RT_FAILURE(vrc))
487 hrc = setError(E_FAIL, tr("Loading the NVRAM store failed (%Rrc)\n"), vrc);
488 }
489
490 if (SUCCEEDED(hrc))
491 {
492 int vrc = VINF_SUCCESS;
493 RTVFSFILE hVfsUefiVarStore = NIL_RTVFSFILE;
494 NvramStoreIter it = m->bd->mapNvram.find("efi/nvram");
495 if (it != m->bd->mapNvram.end())
496 hVfsUefiVarStore = it->second;
497 else
498 {
499 /* Create a new file. */
500 vrc = RTVfsMemFileCreate(NIL_RTVFSIOSTREAM, 0 /*cbEstimate*/, &hVfsUefiVarStore);
501 if (RT_SUCCESS(vrc))
502 {
503 /** @todo The size is hardcoded to match what the firmware image uses right now which is a gross hack... */
504 vrc = RTVfsFileSetSize(hVfsUefiVarStore, 540672, RTVFSFILE_SIZE_F_NORMAL);
505 if (RT_SUCCESS(vrc))
506 m->bd->mapNvram["efi/nvram"] = hVfsUefiVarStore;
507 else
508 RTVfsFileRelease(hVfsUefiVarStore);
509 }
510 }
511
512 if (RT_SUCCESS(vrc))
513 {
514 vrc = RTEfiVarStoreCreate(hVfsUefiVarStore, 0 /*offStore*/, 0 /*cbStore*/, RTEFIVARSTORE_CREATE_F_DEFAULT, 0 /*cbBlock*/,
515 NULL /*pErrInfo*/);
516 if (RT_FAILURE(vrc))
517 return setError(E_FAIL, tr("Failed to initialize the UEFI variable store (%Rrc)"), vrc);
518 }
519 else
520 return setError(E_FAIL, tr("Failed to initialize the UEFI variable store (%Rrc)"), vrc);
521
522 m->pParent->i_setModified(Machine::IsModified_NvramStore);
523 }
524
525 return hrc;
526#else
527 NOREF(aSize);
528 return E_NOTIMPL;
529#endif
530}
531
532
533Utf8Str NvramStore::i_getNonVolatileStorageFile()
534{
535 AutoCaller autoCaller(this);
536 AssertReturn(autoCaller.isOk(), Utf8Str::Empty);
537
538 Utf8Str strTmp;
539 NvramStore::getNonVolatileStorageFile(strTmp);
540 return strTmp;
541}
542
543
544/**
545 * Loads the NVRAM store from the given TAR filesystem stream.
546 *
547 * @returns IPRT status code.
548 * @param hVfsFssTar Handle to the tar filesystem stream.
549 */
550int NvramStore::i_loadStoreFromTar(RTVFSFSSTREAM hVfsFssTar)
551{
552 int vrc = VINF_SUCCESS;
553
554 /*
555 * Process the stream.
556 */
557 for (;;)
558 {
559 /*
560 * Retrieve the next object.
561 */
562 char *pszName;
563 RTVFSOBJ hVfsObj;
564 vrc = RTVfsFsStrmNext(hVfsFssTar, &pszName, NULL, &hVfsObj);
565 if (RT_FAILURE(vrc))
566 {
567 if (vrc == VERR_EOF)
568 vrc = VINF_SUCCESS;
569 break;
570 }
571
572 RTFSOBJINFO UnixInfo;
573 vrc = RTVfsObjQueryInfo(hVfsObj, &UnixInfo, RTFSOBJATTRADD_UNIX);
574 if (RT_SUCCESS(vrc))
575 {
576 switch (UnixInfo.Attr.fMode & RTFS_TYPE_MASK)
577 {
578 case RTFS_TYPE_FILE:
579 {
580 LogRel(("NvramStore: Loading '%s' from archive\n", pszName));
581 RTVFSIOSTREAM hVfsIosEntry = RTVfsObjToIoStream(hVfsObj);
582 Assert(hVfsIosEntry != NIL_RTVFSIOSTREAM);
583
584 RTVFSFILE hVfsFileEntry;
585 vrc = RTVfsMemorizeIoStreamAsFile(hVfsIosEntry, RTFILE_O_READ | RTFILE_O_WRITE, &hVfsFileEntry);
586 if (RT_FAILURE(vrc))
587 break;
588 RTVfsIoStrmRelease(hVfsIosEntry);
589
590 m->bd->mapNvram[Utf8Str(pszName)] = hVfsFileEntry;
591 break;
592 }
593 case RTFS_TYPE_DIRECTORY:
594 break;
595 default:
596 vrc = VERR_NOT_SUPPORTED;
597 break;
598 }
599 }
600
601 /*
602 * Release the current object and string.
603 */
604 RTVfsObjRelease(hVfsObj);
605 RTStrFree(pszName);
606
607 if (RT_FAILURE(vrc))
608 break;
609 }
610
611 return vrc;
612}
613
614
615#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
616/**
617 * Sets up the encryption or decryption machinery.
618 *
619 * @returns VBox status code.
620 * @param hVfsIosInOut Handle to the input stream to be decrypted or the destination to the encrypted
621 * output is written to.
622 * @param fEncrypt Flag whether to setup encryption or decryption.
623 * @param ppCryptoIf Where to store the pointer to the cryptographic interface which needs to be released
624 * when done.
625 * @param ppKey Where to store the pointer to the secret key buffer which needs to be released when done.
626 * @param phVfsIos Where to store the handle to the plaintext I/O stream (either input or output) on success.
627 */
628int NvramStore::i_setupEncryptionOrDecryption(RTVFSIOSTREAM hVfsIosInOut, bool fEncrypt,
629 PCVBOXCRYPTOIF *ppCryptoIf, SecretKey **ppKey,
630 PRTVFSIOSTREAM phVfsIos)
631{
632 int vrc = VINF_SUCCESS;
633 PCVBOXCRYPTOIF pCryptoIf = NULL;
634 SecretKey *pKey = NULL;
635 const char *pszPassword = NULL;
636
637 vrc = i_retainCryptoIf(&pCryptoIf);
638 if (RT_SUCCESS(vrc))
639 {
640 vrc = m->mpKeyStore->retainSecretKey(m->bd->strKeyId, &pKey);
641 if (RT_SUCCESS(vrc))
642 {
643 pszPassword = (const char *)pKey->getKeyBuffer();
644 if (fEncrypt)
645 vrc = pCryptoIf->pfnCryptoIoStrmFromVfsIoStrmEncrypt(hVfsIosInOut, m->bd->strKeyStore.c_str(), pszPassword,
646 phVfsIos);
647 else
648 vrc = pCryptoIf->pfnCryptoIoStrmFromVfsIoStrmDecrypt(hVfsIosInOut, m->bd->strKeyStore.c_str(), pszPassword,
649 phVfsIos);
650 if (RT_SUCCESS(vrc))
651 {
652 *ppCryptoIf = pCryptoIf;
653 *ppKey = pKey;
654 return VINF_SUCCESS;
655 }
656 else
657 LogRelMax(10, ("Failed to decrypt the NVRAM store using secret key ID '%s' with %Rrc\n",
658 m->bd->strKeyId.c_str(), vrc));
659
660 m->mpKeyStore->releaseSecretKey(m->bd->strKeyId);
661 }
662 else
663 LogRelMax(10, ("Failed to retain the secret key ID '%s' with %Rrc\n",
664 m->bd->strKeyId.c_str(), vrc));
665
666 i_releaseCryptoIf(pCryptoIf);
667 }
668 else
669 LogRelMax(10, ("Failed to retain the cryptographic interface with %Rrc\n", vrc));
670
671 return vrc;
672}
673
674/**
675 * Releases all resources acquired in NvramStore::i_setupEncryptionOrDecryption().
676 *
677 * @returns nothing.
678 * @param hVfsIos Handle to the I/O stream previously created.
679 * @param pCryptoIf Pointer to the cryptographic interface being released.
680 * @param pKey Pointer to the key buffer being released.
681 */
682void NvramStore::i_releaseEncryptionOrDecryptionResources(RTVFSIOSTREAM hVfsIos, PCVBOXCRYPTOIF pCryptoIf,
683 SecretKey *pKey)
684{
685 Assert(hVfsIos != NIL_RTVFSIOSTREAM);
686 AssertPtr(pCryptoIf);
687 AssertPtr(pKey);
688
689 i_releaseCryptoIf(pCryptoIf);
690 pKey->release();
691 RTVfsIoStrmRelease(hVfsIos);
692}
693#endif
694
695
696/**
697 * Loads the NVRAM store.
698 *
699 * @returns IPRT status code.
700 */
701int NvramStore::i_loadStore(const char *pszPath)
702{
703 uint64_t cbStore = 0;
704 int vrc = RTFileQuerySizeByPath(pszPath, &cbStore);
705 if (RT_SUCCESS(vrc))
706 {
707 if (cbStore <= _1M) /* Arbitrary limit to fend off bogus files because the file will be read into memory completely. */
708 {
709 /*
710 * Old NVRAM files just consist of the EFI variable store whereas starting
711 * with VirtualBox 7.0 and the introduction of the TPM the need to handle multiple
712 * independent NVRAM files came up. For those scenarios all NVRAM states are collected
713 * in a tar archive.
714 *
715 * Here we detect whether the file is the new tar archive format or whether it is just
716 * the plain EFI variable store file.
717 */
718 RTVFSIOSTREAM hVfsIosNvram;
719 vrc = RTVfsIoStrmOpenNormal(pszPath, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE,
720 &hVfsIosNvram);
721 if (RT_SUCCESS(vrc))
722 {
723 RTVFSIOSTREAM hVfsIosDecrypted = NIL_RTVFSIOSTREAM;
724
725#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
726 PCVBOXCRYPTOIF pCryptoIf = NULL;
727 SecretKey *pKey = NULL;
728
729 if ( m->bd->strKeyId.isNotEmpty()
730 && m->bd->strKeyStore.isNotEmpty())
731 vrc = i_setupEncryptionOrDecryption(hVfsIosNvram, false /*fEncrypt*/,
732 &pCryptoIf, &pKey, &hVfsIosDecrypted);
733#endif
734 if (RT_SUCCESS(vrc))
735 {
736 /* Read the content. */
737 RTVFSFILE hVfsFileNvram;
738 vrc = RTVfsMemorizeIoStreamAsFile( hVfsIosDecrypted != NIL_RTVFSIOSTREAM
739 ? hVfsIosDecrypted
740 : hVfsIosNvram,
741 RTFILE_O_READ, &hVfsFileNvram);
742 if (RT_SUCCESS(vrc))
743 {
744 if (RT_SUCCESS(vrc))
745 {
746 /* Try to parse it as an EFI variable store. */
747 RTVFS hVfsEfiVarStore;
748 vrc = RTEfiVarStoreOpenAsVfs(hVfsFileNvram, RTVFSMNT_F_READ_ONLY, 0 /*fVarStoreFlags*/, &hVfsEfiVarStore,
749 NULL /*pErrInfo*/);
750 if (RT_SUCCESS(vrc))
751 {
752 vrc = RTVfsFileSeek(hVfsFileNvram, 0 /*offSeek*/, RTFILE_SEEK_BEGIN, NULL /*poffActual*/);
753 AssertRC(vrc);
754
755 RTVfsFileRetain(hVfsFileNvram); /* Retain a new reference for the map. */
756 m->bd->mapNvram[Utf8Str("efi/nvram")] = hVfsFileNvram;
757
758 RTVfsRelease(hVfsEfiVarStore);
759 }
760 else if (vrc == VERR_VFS_UNKNOWN_FORMAT)
761 {
762 /* Check for the new style tar archive. */
763 vrc = RTVfsFileSeek(hVfsFileNvram, 0 /*offSeek*/, RTFILE_SEEK_BEGIN, NULL /*poffActual*/);
764 AssertRC(vrc);
765
766 RTVFSIOSTREAM hVfsIosTar = RTVfsFileToIoStream(hVfsFileNvram);
767 Assert(hVfsIosTar != NIL_RTVFSIOSTREAM);
768
769 RTVFSFSSTREAM hVfsFssTar;
770 vrc = RTZipTarFsStreamFromIoStream(hVfsIosTar, 0 /*fFlags*/, &hVfsFssTar);
771 RTVfsIoStrmRelease(hVfsIosTar);
772 if (RT_SUCCESS(vrc))
773 {
774 vrc = i_loadStoreFromTar(hVfsFssTar);
775 RTVfsFsStrmRelease(hVfsFssTar);
776 }
777 else
778 LogRel(("The given NVRAM file is neither a raw UEFI variable store nor a tar archive (opening failed with %Rrc)\n", vrc));
779 }
780 else
781 LogRel(("Opening the UEFI variable store '%s' failed with %Rrc\n", pszPath, vrc));
782
783 RTVfsFileRelease(hVfsFileNvram);
784 }
785 else
786 LogRel(("Failed to memorize NVRAM store '%s' with %Rrc\n", pszPath, vrc));
787 }
788 }
789
790#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
791 if (hVfsIosDecrypted != NIL_RTVFSIOSTREAM)
792 i_releaseEncryptionOrDecryptionResources(hVfsIosDecrypted, pCryptoIf, pKey);
793#endif
794
795 RTVfsIoStrmRelease(hVfsIosNvram);
796 }
797 else
798 LogRelMax(10, ("NVRAM store '%s' couldn't be opened with %Rrc\n", pszPath, vrc));
799 }
800 else
801 LogRelMax(10, ("NVRAM store '%s' exceeds limit of %u bytes, actual size is %u\n",
802 pszPath, _1M, cbStore));
803 }
804 else if (vrc == VERR_FILE_NOT_FOUND) /* Valid for the first run where no NVRAM file is there. */
805 vrc = VINF_SUCCESS;
806
807 return vrc;
808}
809
810
811/**
812 * Saves the NVRAM store as a tar archive.
813 */
814int NvramStore::i_saveStoreAsTar(const char *pszPath)
815{
816 uint32_t offError = 0;
817 RTERRINFOSTATIC ErrInfo;
818 RTVFSIOSTREAM hVfsIos;
819
820 int vrc = RTVfsChainOpenIoStream(pszPath, RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE_REPLACE,
821 &hVfsIos, &offError, RTErrInfoInitStatic(&ErrInfo));
822 if (RT_SUCCESS(vrc))
823 {
824 RTVFSIOSTREAM hVfsIosEncrypted = NIL_RTVFSIOSTREAM;
825
826#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
827 PCVBOXCRYPTOIF pCryptoIf = NULL;
828 SecretKey *pKey = NULL;
829
830 if ( m->bd->strKeyId.isNotEmpty()
831 && m->bd->strKeyStore.isNotEmpty())
832 vrc = i_setupEncryptionOrDecryption(hVfsIos, true /*fEncrypt*/,
833 &pCryptoIf, &pKey, &hVfsIosEncrypted);
834#endif
835
836 if (RT_SUCCESS(vrc))
837 {
838 RTVFSFSSTREAM hVfsFss;
839 vrc = RTZipTarFsStreamToIoStream( hVfsIosEncrypted != NIL_RTVFSIOSTREAM
840 ? hVfsIosEncrypted
841 : hVfsIos,
842 RTZIPTARFORMAT_GNU, 0 /*fFlags*/, &hVfsFss);
843 if (RT_SUCCESS(vrc))
844 {
845 NvramStoreIter it = m->bd->mapNvram.begin();
846
847 while (it != m->bd->mapNvram.end())
848 {
849 RTVFSFILE hVfsFile = it->second;
850
851 vrc = RTVfsFileSeek(hVfsFile, 0 /*offSeek*/, RTFILE_SEEK_BEGIN, NULL /*poffActual*/);
852 AssertRC(vrc);
853
854 RTVFSOBJ hVfsObj = RTVfsObjFromFile(hVfsFile);
855 vrc = RTVfsFsStrmAdd(hVfsFss, it->first.c_str(), hVfsObj, 0 /*fFlags*/);
856 RTVfsObjRelease(hVfsObj);
857 if (RT_FAILURE(vrc))
858 break;
859
860 it++;
861 }
862
863 RTVfsFsStrmRelease(hVfsFss);
864 }
865
866#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
867 if (hVfsIosEncrypted != NIL_RTVFSIOSTREAM)
868 i_releaseEncryptionOrDecryptionResources(hVfsIosEncrypted, pCryptoIf, pKey);
869#endif
870 }
871
872 RTVfsIoStrmRelease(hVfsIos);
873 }
874
875 return vrc;
876}
877
878
879int NvramStore::i_retainCryptoIf(PCVBOXCRYPTOIF *ppCryptoIf)
880{
881#ifdef VBOX_COM_INPROC
882 return m->pParent->i_retainCryptoIf(ppCryptoIf);
883#else
884 HRESULT hrc = m->pParent->i_getVirtualBox()->i_retainCryptoIf(ppCryptoIf);
885 if (SUCCEEDED(hrc))
886 return VINF_SUCCESS;
887
888 return VERR_COM_IPRT_ERROR;
889#endif
890}
891
892
893int NvramStore::i_releaseCryptoIf(PCVBOXCRYPTOIF pCryptoIf)
894{
895#ifdef VBOX_COM_INPROC
896 return m->pParent->i_releaseCryptoIf(pCryptoIf);
897#else
898 HRESULT hrc = m->pParent->i_getVirtualBox()->i_releaseCryptoIf(pCryptoIf);
899 if (SUCCEEDED(hrc))
900 return VINF_SUCCESS;
901
902 return VERR_COM_IPRT_ERROR;
903#endif
904}
905
906
907/**
908 * Saves the NVRAM store.
909 *
910 * @returns IPRT status code.
911 */
912int NvramStore::i_saveStore(void)
913{
914 int vrc = VINF_SUCCESS;
915
916 Utf8Str strTmp;
917 NvramStore::getNonVolatileStorageFile(strTmp);
918
919 /*
920 * Only store the NVRAM content if the path is not empty, if it is
921 * this means the VM was just created and the store was nnot saved yet,
922 * see @bugref{10191}.
923 */
924 if (strTmp.isNotEmpty())
925 {
926 /*
927 * Skip creating the tar archive if only the UEFI NVRAM content is available in order
928 * to maintain backwards compatibility. As soon as there is more than one entry or
929 * it doesn't belong to the UEFI the tar archive will be created.
930 */
931 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
932 if ( m->bd->mapNvram.size() == 1
933 && m->bd->mapNvram.find(Utf8Str("efi/nvram")) != m->bd->mapNvram.end())
934 {
935 RTVFSFILE hVfsFileNvram = m->bd->mapNvram[Utf8Str("efi/nvram")];
936
937 vrc = RTVfsFileSeek(hVfsFileNvram, 0 /*offSeek*/, RTFILE_SEEK_BEGIN, NULL /*poffActual*/);
938 AssertRC(vrc); RT_NOREF(vrc);
939
940 RTVFSIOSTREAM hVfsIosDst;
941 vrc = RTVfsIoStrmOpenNormal(strTmp.c_str(), RTFILE_O_CREATE_REPLACE | RTFILE_O_WRITE | RTFILE_O_DENY_NONE,
942 &hVfsIosDst);
943 if (RT_SUCCESS(vrc))
944 {
945 RTVFSIOSTREAM hVfsIosSrc = RTVfsFileToIoStream(hVfsFileNvram);
946 Assert(hVfsIosSrc != NIL_RTVFSIOSTREAM);
947
948 RTVFSIOSTREAM hVfsIosEncrypted = NIL_RTVFSIOSTREAM;
949
950#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
951 PCVBOXCRYPTOIF pCryptoIf = NULL;
952 SecretKey *pKey = NULL;
953
954 if ( m->bd->strKeyId.isNotEmpty()
955 && m->bd->strKeyStore.isNotEmpty())
956 vrc = i_setupEncryptionOrDecryption(hVfsIosDst, true /*fEncrypt*/,
957 &pCryptoIf, &pKey, &hVfsIosEncrypted);
958#endif
959
960 vrc = RTVfsUtilPumpIoStreams(hVfsIosSrc,
961 hVfsIosEncrypted != NIL_RTVFSIOSTREAM
962 ? hVfsIosEncrypted
963 : hVfsIosDst
964 , 0 /*cbBufHint*/);
965
966#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
967 if (hVfsIosEncrypted != NIL_RTVFSIOSTREAM)
968 i_releaseEncryptionOrDecryptionResources(hVfsIosEncrypted, pCryptoIf, pKey);
969#endif
970
971 RTVfsIoStrmRelease(hVfsIosSrc);
972 RTVfsIoStrmRelease(hVfsIosDst);
973 }
974 }
975 else if (m->bd->mapNvram.size())
976 vrc = i_saveStoreAsTar(strTmp.c_str());
977 /* else: No NVRAM content to store so we are done here. */
978 }
979
980 return vrc;
981}
982
983
984#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
985HRESULT NvramStore::i_updateEncryptionSettings(const com::Utf8Str &strKeyId,
986 const com::Utf8Str &strKeyStore)
987{
988 /* sanity */
989 AutoCaller autoCaller(this);
990 AssertComRCReturnRC(autoCaller.hrc());
991
992 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
993
994 m->bd.backup();
995 m->bd->strKeyId = strKeyId;
996 m->bd->strKeyStore = strKeyStore;
997
998 /* clear all passwords because they are invalid now */
999 m->mpKeyStore->deleteAllSecretKeys(false, true);
1000
1001 alock.release();
1002 AutoWriteLock mlock(m->pParent COMMA_LOCKVAL_SRC_POS);
1003#ifndef VBOX_COM_INPROC
1004 m->pParent->i_setModified(Machine::IsModified_NvramStore);
1005#endif
1006 return S_OK;
1007}
1008
1009
1010HRESULT NvramStore::i_getEncryptionSettings(com::Utf8Str &strKeyId,
1011 com::Utf8Str &strKeyStore)
1012{
1013 AutoCaller autoCaller(this);
1014 AssertComRCReturnRC(autoCaller.hrc());
1015
1016 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1017
1018 strKeyId = m->bd->strKeyId;
1019 strKeyStore = m->bd->strKeyStore;
1020
1021 return S_OK;
1022}
1023
1024
1025int NvramStore::i_addPassword(const Utf8Str &strKeyId, const Utf8Str &strPassword)
1026{
1027 AutoCaller autoCaller(this);
1028 AssertComRCReturn(autoCaller.hrc(), VERR_INVALID_STATE);
1029
1030 /* keep only required password */
1031 if (strKeyId != m->bd->strKeyId)
1032 return VINF_SUCCESS;
1033
1034 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1035 return m->mpKeyStore->addSecretKey(strKeyId, (const uint8_t *)strPassword.c_str(), strPassword.length() + 1);
1036}
1037
1038
1039int NvramStore::i_removePassword(const Utf8Str &strKeyId)
1040{
1041 AutoCaller autoCaller(this);
1042 AssertComRCReturn(autoCaller.hrc(), VERR_INVALID_STATE);
1043
1044 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1045 return m->mpKeyStore->deleteSecretKey(strKeyId);
1046}
1047
1048
1049int NvramStore::i_removeAllPasswords()
1050{
1051 AutoCaller autoCaller(this);
1052 AssertComRCReturn(autoCaller.hrc(), VERR_INVALID_STATE);
1053
1054 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1055 m->mpKeyStore->deleteAllSecretKeys(false, true);
1056 return VINF_SUCCESS;
1057}
1058#endif
1059
1060
1061#ifndef VBOX_COM_INPROC
1062HRESULT NvramStore::i_retainUefiVarStore(PRTVFS phVfs, bool fReadonly)
1063{
1064 /* the machine needs to be mutable */
1065 AutoMutableStateDependency adep(m->pParent);
1066 if (FAILED(adep.hrc())) return adep.hrc();
1067
1068 AutoWriteLock wlock(this COMMA_LOCKVAL_SRC_POS);
1069
1070 HRESULT hrc = S_OK;
1071 NvramStoreIter it = m->bd->mapNvram.find("efi/nvram");
1072 if (it != m->bd->mapNvram.end())
1073 {
1074 RTVFSFILE hVfsFileNvram = it->second;
1075 RTVFS hVfsEfiVarStore;
1076 uint32_t fMntFlags = fReadonly ? RTVFSMNT_F_READ_ONLY : 0;
1077
1078 int vrc = RTEfiVarStoreOpenAsVfs(hVfsFileNvram, fMntFlags, 0 /*fVarStoreFlags*/, &hVfsEfiVarStore,
1079 NULL /*pErrInfo*/);
1080 if (RT_SUCCESS(vrc))
1081 {
1082 *phVfs = hVfsEfiVarStore;
1083 if (!fReadonly)
1084 m->pParent->i_setModified(Machine::IsModified_NvramStore);
1085 }
1086 else
1087 hrc = setError(E_FAIL, tr("Opening the UEFI variable store failed (%Rrc)."), vrc);
1088 }
1089 else
1090 hrc = setError(VBOX_E_OBJECT_NOT_FOUND, tr("The UEFI NVRAM file is not existing for this machine."));
1091
1092 return hrc;
1093}
1094
1095
1096HRESULT NvramStore::i_releaseUefiVarStore(RTVFS hVfs)
1097{
1098 RTVfsRelease(hVfs);
1099 return S_OK;
1100}
1101
1102
1103/**
1104 * Loads settings from the given machine node.
1105 * May be called once right after this object creation.
1106 *
1107 * @param data Configuration settings.
1108 *
1109 * @note Locks this object for writing.
1110 */
1111HRESULT NvramStore::i_loadSettings(const settings::NvramSettings &data)
1112{
1113 AutoCaller autoCaller(this);
1114 AssertComRCReturnRC(autoCaller.hrc());
1115
1116 AutoReadLock mlock(m->pParent COMMA_LOCKVAL_SRC_POS);
1117 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1118
1119 m->bd->strNvramPath = data.strNvramPath;
1120#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
1121 m->bd->strKeyId = data.strKeyId;
1122 m->bd->strKeyStore = data.strKeyStore;
1123#endif
1124
1125 Utf8Str strTmp(m->bd->strNvramPath);
1126 if (strTmp.isNotEmpty())
1127 m->pParent->i_copyPathRelativeToMachine(strTmp, m->bd->strNvramPath);
1128 if ( m->pParent->i_getFirmwareType() == FirmwareType_BIOS
1129 || m->bd->strNvramPath == m->pParent->i_getDefaultNVRAMFilename())
1130 m->bd->strNvramPath.setNull();
1131
1132 return S_OK;
1133}
1134
1135/**
1136 * Saves settings to the given machine node.
1137 *
1138 * @param data Configuration settings.
1139 *
1140 * @note Locks this object for writing.
1141 */
1142HRESULT NvramStore::i_saveSettings(settings::NvramSettings &data)
1143{
1144 AutoCaller autoCaller(this);
1145 AssertComRCReturnRC(autoCaller.hrc());
1146
1147 AutoWriteLock wlock(this COMMA_LOCKVAL_SRC_POS);
1148
1149 data.strNvramPath = m->bd->strNvramPath;
1150#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
1151 data.strKeyId = m->bd->strKeyId;
1152 data.strKeyStore = m->bd->strKeyStore;
1153#endif
1154
1155 int vrc = i_saveStore();
1156 if (RT_FAILURE(vrc))
1157 return setError(E_FAIL, tr("Failed to save the NVRAM content to disk (%Rrc)"), vrc);
1158
1159 return S_OK;
1160}
1161
1162void NvramStore::i_rollback()
1163{
1164 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1165 m->bd.rollback();
1166}
1167
1168void NvramStore::i_commit()
1169{
1170 /* sanity */
1171 AutoCaller autoCaller(this);
1172 AssertReturnVoid(autoCaller.isOk());
1173
1174 /* sanity too */
1175 AutoCaller peerCaller(m->pPeer);
1176 AssertReturnVoid(peerCaller.isOk());
1177
1178 /* lock both for writing since we modify both (mPeer is "master" so locked
1179 * first) */
1180 AutoMultiWriteLock2 alock(m->pPeer, this COMMA_LOCKVAL_SRC_POS);
1181
1182 if (m->bd.isBackedUp())
1183 {
1184 m->bd.commit();
1185 if (m->pPeer)
1186 {
1187 /* attach new data to the peer and reshare it */
1188 AutoWriteLock peerlock(m->pPeer COMMA_LOCKVAL_SRC_POS);
1189 m->pPeer->m->bd.attach(m->bd);
1190 }
1191 }
1192}
1193
1194void NvramStore::i_copyFrom(NvramStore *aThat)
1195{
1196 AssertReturnVoid(aThat != NULL);
1197
1198 /* sanity */
1199 AutoCaller autoCaller(this);
1200 AssertReturnVoid(autoCaller.isOk());
1201
1202 /* sanity too */
1203 AutoCaller thatCaller(aThat);
1204 AssertReturnVoid(thatCaller.isOk());
1205
1206 /* peer is not modified, lock it for reading (aThat is "master" so locked
1207 * first) */
1208 AutoReadLock rl(aThat COMMA_LOCKVAL_SRC_POS);
1209 AutoWriteLock wl(this COMMA_LOCKVAL_SRC_POS);
1210
1211 /* this will back up current data */
1212 m->bd.assignCopy(aThat->m->bd);
1213
1214 // Intentionally "forget" the NVRAM file since it must be unique and set
1215 // to the correct value before the copy of the settings makes sense.
1216 m->bd->strNvramPath.setNull();
1217}
1218
1219HRESULT NvramStore::i_applyDefaults(GuestOSType *aOSType)
1220{
1221 HRESULT hrc = S_OK;
1222
1223 if (aOSType->i_recommendedEFISecureBoot())
1224 {
1225 /* Initialize the UEFI variable store and enroll default keys. */
1226 hrc = initUefiVariableStore(0 /*aSize*/);
1227 if (SUCCEEDED(hrc))
1228 {
1229 ComPtr<IUefiVariableStore> pVarStore;
1230
1231 hrc = getUefiVariableStore(pVarStore);
1232 if (SUCCEEDED(hrc))
1233 {
1234 hrc = pVarStore->EnrollOraclePlatformKey();
1235 if (SUCCEEDED(hrc))
1236 hrc = pVarStore->EnrollDefaultMsSignatures();
1237 }
1238 }
1239 }
1240
1241 return hrc;
1242}
1243
1244void NvramStore::i_updateNonVolatileStorageFile(const Utf8Str &aNonVolatileStorageFile)
1245{
1246 /* sanity */
1247 AutoCaller autoCaller(this);
1248 AssertComRCReturnVoid(autoCaller.hrc());
1249
1250 AutoReadLock mlock(m->pParent COMMA_LOCKVAL_SRC_POS);
1251 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1252
1253 Utf8Str strTmp(aNonVolatileStorageFile);
1254 if (strTmp == m->pParent->i_getDefaultNVRAMFilename())
1255 strTmp.setNull();
1256
1257 if (strTmp == m->bd->strNvramPath)
1258 return;
1259
1260 m->bd.backup();
1261 m->bd->strNvramPath = strTmp;
1262}
1263
1264#else
1265//
1266// private methods
1267//
1268/*static*/
1269DECLCALLBACK(int) NvramStore::i_nvramStoreQuerySize(PPDMIVFSCONNECTOR pInterface, const char *pszNamespace, const char *pszPath,
1270 uint64_t *pcb)
1271{
1272 PDRVMAINNVRAMSTORE pThis = RT_FROM_MEMBER(pInterface, DRVMAINNVRAMSTORE, IVfs);
1273
1274 AutoReadLock rlock(pThis->pNvramStore COMMA_LOCKVAL_SRC_POS);
1275 NvramStoreIter it = pThis->pNvramStore->m->bd->mapNvram.find(Utf8StrFmt("%s/%s", pszNamespace, pszPath));
1276 if (it != pThis->pNvramStore->m->bd->mapNvram.end())
1277 {
1278 RTVFSFILE hVfsFile = it->second;
1279 return RTVfsFileQuerySize(hVfsFile, pcb);
1280 }
1281
1282 return VERR_NOT_FOUND;
1283}
1284
1285
1286/*static*/
1287DECLCALLBACK(int) NvramStore::i_nvramStoreReadAll(PPDMIVFSCONNECTOR pInterface, const char *pszNamespace, const char *pszPath,
1288 void *pvBuf, size_t cbRead)
1289{
1290 PDRVMAINNVRAMSTORE pThis = RT_FROM_MEMBER(pInterface, DRVMAINNVRAMSTORE, IVfs);
1291
1292 AutoReadLock rlock(pThis->pNvramStore COMMA_LOCKVAL_SRC_POS);
1293 NvramStoreIter it = pThis->pNvramStore->m->bd->mapNvram.find(Utf8StrFmt("%s/%s", pszNamespace, pszPath));
1294 if (it != pThis->pNvramStore->m->bd->mapNvram.end())
1295 {
1296 RTVFSFILE hVfsFile = it->second;
1297
1298 int vrc = RTVfsFileSeek(hVfsFile, 0 /*offSeek*/, RTFILE_SEEK_BEGIN, NULL /*poffActual*/);
1299 AssertRC(vrc); RT_NOREF(vrc);
1300
1301 return RTVfsFileRead(hVfsFile, pvBuf, cbRead, NULL /*pcbRead*/);
1302 }
1303
1304 return VERR_NOT_FOUND;
1305}
1306
1307
1308/*static*/
1309DECLCALLBACK(int) NvramStore::i_nvramStoreWriteAll(PPDMIVFSCONNECTOR pInterface, const char *pszNamespace, const char *pszPath,
1310 const void *pvBuf, size_t cbWrite)
1311{
1312 PDRVMAINNVRAMSTORE pThis = RT_FROM_MEMBER(pInterface, DRVMAINNVRAMSTORE, IVfs);
1313
1314 AutoWriteLock wlock(pThis->pNvramStore COMMA_LOCKVAL_SRC_POS);
1315
1316 int vrc = VINF_SUCCESS;
1317 NvramStoreIter it = pThis->pNvramStore->m->bd->mapNvram.find(Utf8StrFmt("%s/%s", pszNamespace, pszPath));
1318 if (it != pThis->pNvramStore->m->bd->mapNvram.end())
1319 {
1320 RTVFSFILE hVfsFile = it->second;
1321
1322 vrc = RTVfsFileSeek(hVfsFile, 0 /*offSeek*/, RTFILE_SEEK_BEGIN, NULL /*poffActual*/);
1323 AssertRC(vrc);
1324 vrc = RTVfsFileSetSize(hVfsFile, cbWrite, RTVFSFILE_SIZE_F_NORMAL);
1325 if (RT_SUCCESS(vrc))
1326 vrc = RTVfsFileWrite(hVfsFile, pvBuf, cbWrite, NULL /*pcbWritten*/);
1327 }
1328 else
1329 {
1330 /* Create a new entry. */
1331 RTVFSFILE hVfsFile = NIL_RTVFSFILE;
1332 vrc = RTVfsFileFromBuffer(RTFILE_O_READ | RTFILE_O_WRITE, pvBuf, cbWrite, &hVfsFile);
1333 if (RT_SUCCESS(vrc))
1334 pThis->pNvramStore->m->bd->mapNvram[Utf8StrFmt("%s/%s", pszNamespace, pszPath)] = hVfsFile;
1335 }
1336
1337 return vrc;
1338}
1339
1340
1341/*static*/
1342DECLCALLBACK(int) NvramStore::i_nvramStoreDelete(PPDMIVFSCONNECTOR pInterface, const char *pszNamespace, const char *pszPath)
1343{
1344 PDRVMAINNVRAMSTORE pThis = RT_FROM_MEMBER(pInterface, DRVMAINNVRAMSTORE, IVfs);
1345
1346 AutoWriteLock wlock(pThis->pNvramStore COMMA_LOCKVAL_SRC_POS);
1347 NvramStoreIter it = pThis->pNvramStore->m->bd->mapNvram.find(Utf8StrFmt("%s/%s", pszNamespace, pszPath));
1348 if (it != pThis->pNvramStore->m->bd->mapNvram.end())
1349 {
1350 RTVFSFILE hVfsFile = it->second;
1351 pThis->pNvramStore->m->bd->mapNvram.erase(it);
1352 RTVfsFileRelease(hVfsFile);
1353 return VINF_SUCCESS;
1354 }
1355
1356 return VERR_NOT_FOUND;
1357}
1358
1359
1360/*static*/
1361DECLCALLBACK(int) NvramStore::i_SsmSaveExec(PPDMDRVINS pDrvIns, PSSMHANDLE pSSM)
1362{
1363 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1364 PDRVMAINNVRAMSTORE pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINNVRAMSTORE);
1365 PCPDMDRVHLPR3 pHlp = pDrvIns->pHlpR3;
1366
1367 AutoWriteLock wlock(pThis->pNvramStore COMMA_LOCKVAL_SRC_POS);
1368
1369 size_t cEntries = pThis->pNvramStore->m->bd->mapNvram.size();
1370 AssertReturn(cEntries < 32, VERR_OUT_OF_RANGE); /* Some sanity checking. */
1371 pHlp->pfnSSMPutU32(pSSM, (uint32_t)cEntries);
1372
1373 void *pvData = NULL;
1374 size_t cbDataMax = 0;
1375 NvramStoreIter it = pThis->pNvramStore->m->bd->mapNvram.begin();
1376
1377 while (it != pThis->pNvramStore->m->bd->mapNvram.end())
1378 {
1379 RTVFSFILE hVfsFile = it->second;
1380 uint64_t cbFile;
1381
1382 int vrc = RTVfsFileQuerySize(hVfsFile, &cbFile);
1383 AssertRCReturn(vrc, vrc);
1384 AssertReturn(cbFile < _1M, VERR_OUT_OF_RANGE);
1385
1386 if (cbDataMax < cbFile)
1387 {
1388 pvData = RTMemRealloc(pvData, cbFile);
1389 AssertPtrReturn(pvData, VERR_NO_MEMORY);
1390 cbDataMax = cbFile;
1391 }
1392
1393 vrc = RTVfsFileReadAt(hVfsFile, 0 /*off*/, pvData, cbFile, NULL /*pcbRead*/);
1394 AssertRCReturn(vrc, vrc);
1395
1396 pHlp->pfnSSMPutStrZ(pSSM, it->first.c_str());
1397 pHlp->pfnSSMPutU64(pSSM, cbFile);
1398 pHlp->pfnSSMPutMem(pSSM, pvData, cbFile);
1399 it++;
1400 }
1401
1402 if (pvData)
1403 RTMemFree(pvData);
1404
1405 pThis->pNvramStore->m->fSsmSaved = true;
1406 return pHlp->pfnSSMPutU32(pSSM, UINT32_MAX); /* sanity/terminator */
1407}
1408
1409
1410/*static*/
1411DECLCALLBACK(int) NvramStore::i_SsmLoadExec(PPDMDRVINS pDrvIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
1412{
1413 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1414 PDRVMAINNVRAMSTORE pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINNVRAMSTORE);
1415 PCPDMDRVHLPR3 pHlp = pDrvIns->pHlpR3;
1416
1417 AssertMsgReturn(uVersion >= NVRAM_STORE_SAVED_STATE_VERSION, ("%d\n", uVersion),
1418 VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION);
1419
1420 if (uPass == SSM_PASS_FINAL)
1421 {
1422 AutoWriteLock wlock(pThis->pNvramStore COMMA_LOCKVAL_SRC_POS);
1423
1424 /* Clear any content first. */
1425 NvramStoreIter it = pThis->pNvramStore->m->bd->mapNvram.begin();
1426 while (it != pThis->pNvramStore->m->bd->mapNvram.end())
1427 {
1428 RTVfsFileRelease(it->second);
1429 it++;
1430 }
1431
1432 pThis->pNvramStore->m->bd->mapNvram.clear();
1433
1434 uint32_t cEntries = 0;
1435 int vrc = pHlp->pfnSSMGetU32(pSSM, &cEntries);
1436 AssertRCReturn(vrc, vrc);
1437 AssertReturn(cEntries < 32, VERR_OUT_OF_RANGE);
1438
1439 void *pvData = NULL;
1440 size_t cbDataMax = 0;
1441 while (cEntries--)
1442 {
1443 char szId[_1K]; /* Lazy developer */
1444 uint64_t cbFile = 0;
1445
1446 vrc = pHlp->pfnSSMGetStrZ(pSSM, &szId[0], sizeof(szId));
1447 AssertRCReturn(vrc, vrc);
1448
1449 vrc = pHlp->pfnSSMGetU64(pSSM, &cbFile);
1450 AssertRCReturn(vrc, vrc);
1451 AssertReturn(cbFile < _1M, VERR_OUT_OF_RANGE);
1452
1453 if (cbDataMax < cbFile)
1454 {
1455 pvData = RTMemRealloc(pvData, cbFile);
1456 AssertPtrReturn(pvData, VERR_NO_MEMORY);
1457 cbDataMax = cbFile;
1458 }
1459
1460 vrc = pHlp->pfnSSMGetMem(pSSM, pvData, cbFile);
1461 AssertRCReturn(vrc, vrc);
1462
1463 RTVFSFILE hVfsFile;
1464 vrc = RTVfsFileFromBuffer(RTFILE_O_READWRITE, pvData, cbFile, &hVfsFile);
1465 AssertRCReturn(vrc, vrc);
1466
1467 pThis->pNvramStore->m->bd->mapNvram[Utf8Str(szId)] = hVfsFile;
1468 }
1469
1470 if (pvData)
1471 RTMemFree(pvData);
1472
1473 /* The marker. */
1474 uint32_t u32;
1475 vrc = pHlp->pfnSSMGetU32(pSSM, &u32);
1476 AssertRCReturn(vrc, vrc);
1477 AssertMsgReturn(u32 == UINT32_MAX, ("%#x\n", u32), VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
1478 }
1479
1480 return VINF_SUCCESS;
1481}
1482
1483
1484/**
1485 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
1486 */
1487DECLCALLBACK(void *) NvramStore::i_drvQueryInterface(PPDMIBASE pInterface, const char *pszIID)
1488{
1489 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
1490 PDRVMAINNVRAMSTORE pDrv = PDMINS_2_DATA(pDrvIns, PDRVMAINNVRAMSTORE);
1491
1492 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
1493 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIVFSCONNECTOR, &pDrv->IVfs);
1494 return NULL;
1495}
1496
1497
1498/**
1499 * Destruct a NVRAM store driver instance.
1500 *
1501 * @returns VBox status code.
1502 * @param pDrvIns The driver instance data.
1503 */
1504DECLCALLBACK(void) NvramStore::i_drvDestruct(PPDMDRVINS pDrvIns)
1505{
1506 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1507 PDRVMAINNVRAMSTORE pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINNVRAMSTORE);
1508 LogFlow(("NvramStore::drvDestruct: iInstance=%d\n", pDrvIns->iInstance));
1509
1510 if (pThis->pNvramStore)
1511 {
1512 uint32_t cRefs = ASMAtomicDecU32(&pThis->pNvramStore->m->cRefs);
1513 if ( !cRefs
1514 && !pThis->pNvramStore->m->fSsmSaved)
1515 {
1516 int vrc = pThis->pNvramStore->i_saveStore();
1517 AssertRC(vrc); /** @todo Disk full error? */
1518 }
1519 }
1520}
1521
1522
1523/**
1524 * Construct a NVRAM store driver instance.
1525 *
1526 * @copydoc FNPDMDRVCONSTRUCT
1527 */
1528DECLCALLBACK(int) NvramStore::i_drvConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
1529{
1530 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1531 RT_NOREF(fFlags, pCfg);
1532 PDRVMAINNVRAMSTORE pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINNVRAMSTORE);
1533 LogFlow(("NvramStore::drvConstruct: iInstance=%d\n", pDrvIns->iInstance));
1534
1535 /*
1536 * Validate configuration.
1537 */
1538 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns, "", "");
1539 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
1540 ("Configuration error: Not possible to attach anything to this driver!\n"),
1541 VERR_PDM_DRVINS_NO_ATTACH);
1542
1543 /*
1544 * IBase.
1545 */
1546 pDrvIns->IBase.pfnQueryInterface = NvramStore::i_drvQueryInterface;
1547
1548 pThis->IVfs.pfnQuerySize = NvramStore::i_nvramStoreQuerySize;
1549 pThis->IVfs.pfnReadAll = NvramStore::i_nvramStoreReadAll;
1550 pThis->IVfs.pfnWriteAll = NvramStore::i_nvramStoreWriteAll;
1551 pThis->IVfs.pfnDelete = NvramStore::i_nvramStoreDelete;
1552
1553 /*
1554 * Get the NVRAM store object pointer.
1555 */
1556 com::Guid uuid(COM_IIDOF(INvramStore));
1557 pThis->pNvramStore = (NvramStore *)PDMDrvHlpQueryGenericUserObject(pDrvIns, uuid.raw());
1558 if (!pThis->pNvramStore)
1559 {
1560 AssertMsgFailed(("Configuration error: No/bad NVRAM store object!\n"));
1561 return VERR_NOT_FOUND;
1562 }
1563
1564 /*
1565 * Only the first instance will register the SSM handlers and will do the work on behalf
1566 * of all other NVRAM store driver instances when it comes to SSM.
1567 */
1568 if (pDrvIns->iInstance == 0)
1569 {
1570 int vrc = PDMDrvHlpSSMRegister(pDrvIns, NVRAM_STORE_SAVED_STATE_VERSION, 0 /*cbGuess*/,
1571 NvramStore::i_SsmSaveExec, NvramStore::i_SsmLoadExec);
1572 if (RT_FAILURE(vrc))
1573 return PDMDrvHlpVMSetError(pDrvIns, vrc, RT_SRC_POS,
1574 N_("Failed to register the saved state unit for the NVRAM store"));
1575 }
1576
1577 uint32_t cRefs = ASMAtomicIncU32(&pThis->pNvramStore->m->cRefs);
1578 if (cRefs == 1)
1579 {
1580 int vrc = pThis->pNvramStore->i_loadStore(pThis->pNvramStore->m->bd->strNvramPath.c_str());
1581 if (RT_FAILURE(vrc))
1582 {
1583 ASMAtomicDecU32(&pThis->pNvramStore->m->cRefs);
1584 return PDMDrvHlpVMSetError(pDrvIns, vrc, RT_SRC_POS,
1585 N_("Failed to load the NVRAM store from the file"));
1586 }
1587 }
1588
1589 return VINF_SUCCESS;
1590}
1591
1592
1593/**
1594 * NVRAM store driver registration record.
1595 */
1596const PDMDRVREG NvramStore::DrvReg =
1597{
1598 /* u32Version */
1599 PDM_DRVREG_VERSION,
1600 /* szName */
1601 "NvramStore",
1602 /* szRCMod */
1603 "",
1604 /* szR0Mod */
1605 "",
1606 /* pszDescription */
1607 "Main NVRAM store driver (Main as in the API).",
1608 /* fFlags */
1609 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1610 /* fClass. */
1611 PDM_DRVREG_CLASS_STATUS,
1612 /* cMaxInstances */
1613 ~0U,
1614 /* cbInstance */
1615 sizeof(DRVMAINNVRAMSTORE),
1616 /* pfnConstruct */
1617 NvramStore::i_drvConstruct,
1618 /* pfnDestruct */
1619 NvramStore::i_drvDestruct,
1620 /* pfnRelocate */
1621 NULL,
1622 /* pfnIOCtl */
1623 NULL,
1624 /* pfnPowerOn */
1625 NULL,
1626 /* pfnReset */
1627 NULL,
1628 /* pfnSuspend */
1629 NULL,
1630 /* pfnResume */
1631 NULL,
1632 /* pfnAttach */
1633 NULL,
1634 /* pfnDetach */
1635 NULL,
1636 /* pfnPowerOff */
1637 NULL,
1638 /* pfnSoftReset */
1639 NULL,
1640 /* u32EndVersion */
1641 PDM_DRVREG_VERSION
1642};
1643#endif /* !VBOX_COM_INPROC */
1644
1645/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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