VirtualBox

source: vbox/trunk/src/VBox/Frontends/VBoxManage/VBoxInternalManage.cpp@ 94234

Last change on this file since 94234 was 93115, checked in by vboxsync, 3 years ago

scm --update-copyright-year

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 94.8 KB
Line 
1/* $Id: VBoxInternalManage.cpp 93115 2022-01-01 11:31:46Z vboxsync $ */
2/** @file
3 * VBoxManage - The 'internalcommands' command.
4 *
5 * VBoxInternalManage used to be a second CLI for doing special tricks,
6 * not intended for general usage, only for assisting VBox developers.
7 * It is now integrated into VBoxManage.
8 */
9
10/*
11 * Copyright (C) 2006-2022 Oracle Corporation
12 *
13 * This file is part of VirtualBox Open Source Edition (OSE), as
14 * available from http://www.virtualbox.org. This file is free software;
15 * you can redistribute it and/or modify it under the terms of the GNU
16 * General Public License (GPL) as published by the Free Software
17 * Foundation, in version 2 as it comes in the "COPYING" file of the
18 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
19 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
20 */
21
22
23
24/*********************************************************************************************************************************
25* Header Files *
26*********************************************************************************************************************************/
27#include <VBox/com/com.h>
28#include <VBox/com/string.h>
29#include <VBox/com/Guid.h>
30#include <VBox/com/ErrorInfo.h>
31#include <VBox/com/errorprint.h>
32
33#include <VBox/com/VirtualBox.h>
34
35#include <VBox/vd.h>
36#include <VBox/sup.h>
37#include <VBox/log.h>
38
39#include <iprt/ctype.h>
40#include <iprt/file.h>
41#include <iprt/getopt.h>
42#include <iprt/stream.h>
43#include <iprt/string.h>
44#include <iprt/uuid.h>
45#include <iprt/sha.h>
46
47#include "VBoxManage.h"
48
49/* Includes for the raw disk stuff. */
50#ifdef RT_OS_WINDOWS
51# include <iprt/win/windows.h>
52# include <winioctl.h>
53#elif defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) \
54 || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
55# include <errno.h>
56# include <sys/ioctl.h>
57# include <sys/types.h>
58# include <sys/stat.h>
59# include <fcntl.h>
60# include <unistd.h>
61#endif
62#ifdef RT_OS_LINUX
63# include <sys/utsname.h>
64# include <linux/hdreg.h>
65# include <linux/fs.h>
66# include <stdlib.h> /* atoi() */
67#endif /* RT_OS_LINUX */
68#ifdef RT_OS_DARWIN
69# include <sys/disk.h>
70#endif /* RT_OS_DARWIN */
71#ifdef RT_OS_SOLARIS
72# include <stropts.h>
73# include <sys/dkio.h>
74# include <sys/vtoc.h>
75#endif /* RT_OS_SOLARIS */
76#ifdef RT_OS_FREEBSD
77# include <sys/disk.h>
78#endif /* RT_OS_FREEBSD */
79
80using namespace com;
81
82
83/** Macro for checking whether a partition is of extended type or not. */
84#define PARTTYPE_IS_EXTENDED(x) ((x) == 0x05 || (x) == 0x0f || (x) == 0x85)
85
86/** Maximum number of partitions we can deal with.
87 * Ridiculously large number, but the memory consumption is rather low so who
88 * cares about never using most entries. */
89#define HOSTPARTITION_MAX 100
90
91DECLARE_TRANSLATION_CONTEXT(Internal);
92
93
94typedef struct HOSTPARTITION
95{
96 /** partition number */
97 unsigned uIndex;
98 /** partition number (internal only, windows specific numbering) */
99 unsigned uIndexWin;
100 /** partition type */
101 unsigned uType;
102 /** CHS/cylinder of the first sector */
103 unsigned uStartCylinder;
104 /** CHS/head of the first sector */
105 unsigned uStartHead;
106 /** CHS/head of the first sector */
107 unsigned uStartSector;
108 /** CHS/cylinder of the last sector */
109 unsigned uEndCylinder;
110 /** CHS/head of the last sector */
111 unsigned uEndHead;
112 /** CHS/sector of the last sector */
113 unsigned uEndSector;
114 /** start sector of this partition relative to the beginning of the hard
115 * disk or relative to the beginning of the extended partition table */
116 uint64_t uStart;
117 /** numer of sectors of the partition */
118 uint64_t uSize;
119 /** start sector of this partition _table_ */
120 uint64_t uPartDataStart;
121 /** numer of sectors of this partition _table_ */
122 uint64_t cPartDataSectors;
123} HOSTPARTITION, *PHOSTPARTITION;
124
125typedef struct HOSTPARTITIONS
126{
127 /** partitioning type - MBR or GPT */
128 VDISKPARTTYPE uPartitioningType;
129 unsigned cPartitions;
130 HOSTPARTITION aPartitions[HOSTPARTITION_MAX];
131} HOSTPARTITIONS, *PHOSTPARTITIONS;
132
133/** flag whether we're in internal mode */
134bool g_fInternalMode;
135
136/**
137 * Print the usage info.
138 */
139void printUsageInternal(USAGECATEGORY enmCommand, PRTSTREAM pStrm)
140{
141 Assert(enmCommand != USAGE_INVALID);
142 Assert(enmCommand != USAGE_S_NEWCMD);
143 Assert(enmCommand != USAGE_S_DUMPOPTS);
144 RTStrmPrintf(pStrm,
145 Internal::tr(
146 "Usage: VBoxManage internalcommands <command> [command arguments]\n"
147 "\n"
148 "Commands:\n"
149 "\n"
150 "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s"
151 "WARNING: This is a development tool and shall only be used to analyse\n"
152 " problems. It is completely unsupported and will change in\n"
153 " incompatible ways without warning.\n"),
154
155 (enmCommand == USAGE_I_LOADMAP || enmCommand == USAGE_S_ALL)
156 ? Internal::tr(
157 " loadmap <vmname|uuid> <symfile> <address> [module] [subtrahend] [segment]\n"
158 " This will instruct DBGF to load the given map file\n"
159 " during initialization. (See also loadmap in the debugger.)\n"
160 "\n")
161 : "",
162 (enmCommand == USAGE_I_LOADSYMS || enmCommand == USAGE_S_ALL)
163 ? Internal::tr(
164 " loadsyms <vmname|uuid> <symfile> [delta] [module] [module address]\n"
165 " This will instruct DBGF to load the given symbol file\n"
166 " during initialization.\n"
167 "\n")
168 : "",
169 (enmCommand == USAGE_I_SETHDUUID || enmCommand == USAGE_S_ALL)
170 ? Internal::tr(
171 " sethduuid <filepath> [<uuid>]\n"
172 " Assigns a new UUID to the given image file. This way, multiple copies\n"
173 " of a container can be registered.\n"
174 "\n")
175 : "",
176 (enmCommand == USAGE_I_SETHDPARENTUUID || enmCommand == USAGE_S_ALL)
177 ? Internal::tr(
178 " sethdparentuuid <filepath> <uuid>\n"
179 " Assigns a new parent UUID to the given image file.\n"
180 "\n")
181 : "",
182 (enmCommand == USAGE_I_DUMPHDINFO || enmCommand == USAGE_S_ALL)
183 ? Internal::tr(
184 " dumphdinfo <filepath>\n"
185 " Prints information about the image at the given location.\n"
186 "\n")
187 : "",
188 (enmCommand == USAGE_I_LISTPARTITIONS || enmCommand == USAGE_S_ALL)
189 ? Internal::tr(
190 " listpartitions -rawdisk <diskname>\n"
191 " Lists all partitions on <diskname>.\n"
192 "\n")
193 : "",
194 (enmCommand == USAGE_I_CREATERAWVMDK || enmCommand == USAGE_S_ALL)
195 ? Internal::tr(
196 " createrawvmdk -filename <filename> -rawdisk <diskname>\n"
197 " [-partitions <list of partition numbers> [-mbr <filename>] ]\n"
198 " [-relative]\n"
199 " Creates a new VMDK image which gives access to an entire host disk (if\n"
200 " the parameter -partitions is not specified) or some partitions of a\n"
201 " host disk. If access to individual partitions is granted, then the\n"
202 " parameter -mbr can be used to specify an alternative MBR to be used\n"
203 " (the partitioning information in the MBR file is ignored).\n"
204 " The diskname is on Linux e.g. /dev/sda, and on Windows e.g.\n"
205 " \\\\.\\PhysicalDrive0).\n"
206 " On Linux or FreeBSD host the parameter -relative causes a VMDK file to\n"
207 " be created which refers to individual partitions instead to the entire\n"
208 " disk.\n"
209 " The necessary partition numbers can be queried with\n"
210 " VBoxManage internalcommands listpartitions\n"
211 "\n")
212 : "",
213 (enmCommand == USAGE_I_RENAMEVMDK || enmCommand == USAGE_S_ALL)
214 ? Internal::tr(
215 " renamevmdk -from <filename> -to <filename>\n"
216 " Renames an existing VMDK image, including the base file and all its extents.\n"
217 "\n")
218 : "",
219 (enmCommand == USAGE_I_CONVERTTORAW || enmCommand == USAGE_S_ALL)
220#ifdef ENABLE_CONVERT_RAW_TO_STDOUT
221 ? Internal::tr(
222 " converttoraw [-format <fileformat>] <filename> <outputfile>|stdout"
223 "\n"
224 " Convert image to raw, writing to file or stdout.\n"
225 "\n")
226#else
227 ? Internal::tr(
228 " converttoraw [-format <fileformat>] <filename> <outputfile>"
229 "\n"
230 " Convert image to raw, writing to file.\n"
231 "\n")
232#endif
233 : "",
234 (enmCommand == USAGE_I_CONVERTHD || enmCommand == USAGE_S_ALL)
235 ? Internal::tr(
236 " converthd [-srcformat VDI|VMDK|VHD|RAW]\n"
237 " [-dstformat VDI|VMDK|VHD|RAW]\n"
238 " <inputfile> <outputfile>\n"
239 " converts hard disk images between formats\n"
240 "\n")
241 : "",
242 (enmCommand == USAGE_I_REPAIRHD || enmCommand == USAGE_S_ALL)
243 ? Internal::tr(
244 " repairhd [-dry-run]\n"
245 " [-format VDI|VMDK|VHD|...]\n"
246 " <filename>\n"
247 " Tries to repair corrupted disk images\n"
248 "\n")
249 : "",
250#ifdef RT_OS_WINDOWS
251 (enmCommand == USAGE_I_MODINSTALL || enmCommand == USAGE_S_ALL)
252 ? Internal::tr(
253 " modinstall\n"
254 " Installs the necessary driver for the host OS\n"
255 "\n")
256 : "",
257 (enmCommand == USAGE_I_MODUNINSTALL || enmCommand == USAGE_S_ALL)
258 ? Internal::tr(
259 " moduninstall\n"
260 " Deinstalls the driver\n"
261 "\n")
262 : "",
263#else
264 "",
265 "",
266#endif
267 (enmCommand == USAGE_I_DEBUGLOG || enmCommand == USAGE_S_ALL)
268 ? Internal::tr(
269 " debuglog <vmname|uuid> [--enable|--disable] [--flags todo]\n"
270 " [--groups todo] [--destinations todo]\n"
271 " Controls debug logging.\n"
272 "\n")
273 : "",
274 (enmCommand == USAGE_I_PASSWORDHASH || enmCommand == USAGE_S_ALL)
275 ? Internal::tr(
276 " passwordhash <password>\n"
277 " Generates a password hash.\n"
278 "\n")
279 : "",
280 (enmCommand == USAGE_I_GUESTSTATS || enmCommand == USAGE_S_ALL)
281 ? Internal::tr(
282 " gueststats <vmname|uuid> [--interval <seconds>]\n"
283 " Obtains and prints internal guest statistics.\n"
284 " Sets the update interval if specified.\n"
285 "\n")
286 : ""
287 );
288}
289
290/** @todo this is no longer necessary, we can enumerate extra data */
291/**
292 * Finds a new unique key name.
293 *
294 * I don't think this is 100% race condition proof, but we assumes
295 * the user is not trying to push this point.
296 *
297 * @returns Result from the insert.
298 * @param pMachine The Machine object.
299 * @param pszKeyBase The base key.
300 * @param rKey Reference to the string object in which we will return the key.
301 */
302static HRESULT NewUniqueKey(ComPtr<IMachine> pMachine, const char *pszKeyBase, Utf8Str &rKey)
303{
304 Bstr KeyBase(pszKeyBase);
305 Bstr Keys;
306 HRESULT hrc = pMachine->GetExtraData(KeyBase.raw(), Keys.asOutParam());
307 if (FAILED(hrc))
308 return hrc;
309
310 /* if there are no keys, it's simple. */
311 if (Keys.isEmpty())
312 {
313 rKey = "1";
314 return pMachine->SetExtraData(KeyBase.raw(), Bstr(rKey).raw());
315 }
316
317 /* find a unique number - brute force rulez. */
318 Utf8Str KeysUtf8(Keys);
319 const char *pszKeys = RTStrStripL(KeysUtf8.c_str());
320 for (unsigned i = 1; i < 1000000; i++)
321 {
322 char szKey[32];
323 size_t cchKey = RTStrPrintf(szKey, sizeof(szKey), "%#x", i);
324 const char *psz = strstr(pszKeys, szKey);
325 while (psz)
326 {
327 if ( ( psz == pszKeys
328 || psz[-1] == ' ')
329 && ( psz[cchKey] == ' '
330 || !psz[cchKey])
331 )
332 break;
333 psz = strstr(psz + cchKey, szKey);
334 }
335 if (!psz)
336 {
337 rKey = szKey;
338 Utf8StrFmt NewKeysUtf8("%s %s", pszKeys, szKey);
339 return pMachine->SetExtraData(KeyBase.raw(),
340 Bstr(NewKeysUtf8).raw());
341 }
342 }
343 RTMsgError(Internal::tr("Cannot find unique key for '%s'!"), pszKeyBase);
344 return E_FAIL;
345}
346
347
348#if 0
349/**
350 * Remove a key.
351 *
352 * I don't think this isn't 100% race condition proof, but we assumes
353 * the user is not trying to push this point.
354 *
355 * @returns Result from the insert.
356 * @param pMachine The machine object.
357 * @param pszKeyBase The base key.
358 * @param pszKey The key to remove.
359 */
360static HRESULT RemoveKey(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey)
361{
362 Bstr Keys;
363 HRESULT hrc = pMachine->GetExtraData(Bstr(pszKeyBase), Keys.asOutParam());
364 if (FAILED(hrc))
365 return hrc;
366
367 /* if there are no keys, it's simple. */
368 if (Keys.isEmpty())
369 return S_OK;
370
371 char *pszKeys;
372 int rc = RTUtf16ToUtf8(Keys.raw(), &pszKeys);
373 if (RT_SUCCESS(rc))
374 {
375 /* locate it */
376 size_t cchKey = strlen(pszKey);
377 char *psz = strstr(pszKeys, pszKey);
378 while (psz)
379 {
380 if ( ( psz == pszKeys
381 || psz[-1] == ' ')
382 && ( psz[cchKey] == ' '
383 || !psz[cchKey])
384 )
385 break;
386 psz = strstr(psz + cchKey, pszKey);
387 }
388 if (psz)
389 {
390 /* remove it */
391 char *pszNext = RTStrStripL(psz + cchKey);
392 if (*pszNext)
393 memmove(psz, pszNext, strlen(pszNext) + 1);
394 else
395 *psz = '\0';
396 psz = RTStrStrip(pszKeys);
397
398 /* update */
399 hrc = pMachine->SetExtraData(Bstr(pszKeyBase), Bstr(psz));
400 }
401
402 RTStrFree(pszKeys);
403 return hrc;
404 }
405 else
406 RTMsgError(Internal::tr("Failed to delete key '%s' from '%s', string conversion error %Rrc!"),
407 pszKey, pszKeyBase, rc);
408
409 return E_FAIL;
410}
411#endif
412
413
414/**
415 * Sets a key value, does necessary error bitching.
416 *
417 * @returns COM status code.
418 * @param pMachine The Machine object.
419 * @param pszKeyBase The key base.
420 * @param pszKey The key.
421 * @param pszAttribute The attribute name.
422 * @param pszValue The string value.
423 */
424static HRESULT SetString(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey, const char *pszAttribute, const char *pszValue)
425{
426 HRESULT hrc = pMachine->SetExtraData(BstrFmt("%s/%s/%s", pszKeyBase,
427 pszKey, pszAttribute).raw(),
428 Bstr(pszValue).raw());
429 if (FAILED(hrc))
430 RTMsgError(Internal::tr("Failed to set '%s/%s/%s' to '%s'! hrc=%#x"),
431 pszKeyBase, pszKey, pszAttribute, pszValue, hrc);
432 return hrc;
433}
434
435
436/**
437 * Sets a key value, does necessary error bitching.
438 *
439 * @returns COM status code.
440 * @param pMachine The Machine object.
441 * @param pszKeyBase The key base.
442 * @param pszKey The key.
443 * @param pszAttribute The attribute name.
444 * @param u64Value The value.
445 */
446static HRESULT SetUInt64(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey, const char *pszAttribute, uint64_t u64Value)
447{
448 char szValue[64];
449 RTStrPrintf(szValue, sizeof(szValue), "%#RX64", u64Value);
450 return SetString(pMachine, pszKeyBase, pszKey, pszAttribute, szValue);
451}
452
453
454/**
455 * Sets a key value, does necessary error bitching.
456 *
457 * @returns COM status code.
458 * @param pMachine The Machine object.
459 * @param pszKeyBase The key base.
460 * @param pszKey The key.
461 * @param pszAttribute The attribute name.
462 * @param i64Value The value.
463 */
464static HRESULT SetInt64(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey, const char *pszAttribute, int64_t i64Value)
465{
466 char szValue[64];
467 RTStrPrintf(szValue, sizeof(szValue), "%RI64", i64Value);
468 return SetString(pMachine, pszKeyBase, pszKey, pszAttribute, szValue);
469}
470
471
472/**
473 * Identical to the 'loadsyms' command.
474 */
475static RTEXITCODE CmdLoadSyms(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
476{
477 RT_NOREF(aSession);
478 HRESULT rc;
479
480 /*
481 * Get the VM
482 */
483 ComPtr<IMachine> machine;
484 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
485 machine.asOutParam()), RTEXITCODE_FAILURE);
486
487 /*
488 * Parse the command.
489 */
490 const char *pszFilename;
491 int64_t offDelta = 0;
492 const char *pszModule = NULL;
493 uint64_t ModuleAddress = UINT64_MAX;
494 uint64_t ModuleSize = 0;
495
496 /* filename */
497 if (argc < 2)
498 return errorArgument(Internal::tr("Missing the filename argument!\n"));
499 pszFilename = argv[1];
500
501 /* offDelta */
502 if (argc >= 3)
503 {
504 int irc = RTStrToInt64Ex(argv[2], NULL, 0, &offDelta);
505 if (RT_FAILURE(irc))
506 return errorArgument(argv[0], Internal::tr("Failed to read delta '%s', rc=%Rrc\n"), argv[2], rc);
507 }
508
509 /* pszModule */
510 if (argc >= 4)
511 pszModule = argv[3];
512
513 /* ModuleAddress */
514 if (argc >= 5)
515 {
516 int irc = RTStrToUInt64Ex(argv[4], NULL, 0, &ModuleAddress);
517 if (RT_FAILURE(irc))
518 return errorArgument(argv[0], Internal::tr("Failed to read module address '%s', rc=%Rrc\n"), argv[4], rc);
519 }
520
521 /* ModuleSize */
522 if (argc >= 6)
523 {
524 int irc = RTStrToUInt64Ex(argv[5], NULL, 0, &ModuleSize);
525 if (RT_FAILURE(irc))
526 return errorArgument(argv[0], Internal::tr("Failed to read module size '%s', rc=%Rrc\n"), argv[5], rc);
527 }
528
529 /*
530 * Add extra data.
531 */
532 Utf8Str KeyStr;
533 HRESULT hrc = NewUniqueKey(machine, "VBoxInternal/DBGF/loadsyms", KeyStr);
534 if (SUCCEEDED(hrc))
535 hrc = SetString(machine, "VBoxInternal/DBGF/loadsyms", KeyStr.c_str(), "Filename", pszFilename);
536 if (SUCCEEDED(hrc) && argc >= 3)
537 hrc = SetInt64(machine, "VBoxInternal/DBGF/loadsyms", KeyStr.c_str(), "Delta", offDelta);
538 if (SUCCEEDED(hrc) && argc >= 4)
539 hrc = SetString(machine, "VBoxInternal/DBGF/loadsyms", KeyStr.c_str(), "Module", pszModule);
540 if (SUCCEEDED(hrc) && argc >= 5)
541 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadsyms", KeyStr.c_str(), "ModuleAddress", ModuleAddress);
542 if (SUCCEEDED(hrc) && argc >= 6)
543 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadsyms", KeyStr.c_str(), "ModuleSize", ModuleSize);
544
545 return SUCCEEDED(hrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
546}
547
548
549/**
550 * Identical to the 'loadmap' command.
551 */
552static RTEXITCODE CmdLoadMap(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
553{
554 RT_NOREF(aSession);
555 HRESULT rc;
556
557 /*
558 * Get the VM
559 */
560 ComPtr<IMachine> machine;
561 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
562 machine.asOutParam()), RTEXITCODE_FAILURE);
563
564 /*
565 * Parse the command.
566 */
567 const char *pszFilename;
568 uint64_t ModuleAddress = UINT64_MAX;
569 const char *pszModule = NULL;
570 uint64_t offSubtrahend = 0;
571 uint32_t iSeg = UINT32_MAX;
572
573 /* filename */
574 if (argc < 2)
575 return errorArgument(Internal::tr("Missing the filename argument!\n"));
576 pszFilename = argv[1];
577
578 /* address */
579 if (argc < 3)
580 return errorArgument(Internal::tr("Missing the module address argument!\n"));
581 int irc = RTStrToUInt64Ex(argv[2], NULL, 0, &ModuleAddress);
582 if (RT_FAILURE(irc))
583 return errorArgument(argv[0], Internal::tr("Failed to read module address '%s', rc=%Rrc\n"), argv[2], rc);
584
585 /* name (optional) */
586 if (argc > 3)
587 pszModule = argv[3];
588
589 /* subtrahend (optional) */
590 if (argc > 4)
591 {
592 irc = RTStrToUInt64Ex(argv[4], NULL, 0, &offSubtrahend);
593 if (RT_FAILURE(irc))
594 return errorArgument(argv[0], Internal::tr("Failed to read subtrahend '%s', rc=%Rrc\n"), argv[4], rc);
595 }
596
597 /* segment (optional) */
598 if (argc > 5)
599 {
600 irc = RTStrToUInt32Ex(argv[5], NULL, 0, &iSeg);
601 if (RT_FAILURE(irc))
602 return errorArgument(argv[0], Internal::tr("Failed to read segment number '%s', rc=%Rrc\n"), argv[5], rc);
603 }
604
605 /*
606 * Add extra data.
607 */
608 Utf8Str KeyStr;
609 HRESULT hrc = NewUniqueKey(machine, "VBoxInternal/DBGF/loadmap", KeyStr);
610 if (SUCCEEDED(hrc))
611 hrc = SetString(machine, "VBoxInternal/DBGF/loadmap", KeyStr.c_str(), "Filename", pszFilename);
612 if (SUCCEEDED(hrc))
613 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadmap", KeyStr.c_str(), "Address", ModuleAddress);
614 if (SUCCEEDED(hrc) && pszModule != NULL)
615 hrc = SetString(machine, "VBoxInternal/DBGF/loadmap", KeyStr.c_str(), "Name", pszModule);
616 if (SUCCEEDED(hrc) && offSubtrahend != 0)
617 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadmap", KeyStr.c_str(), "Subtrahend", offSubtrahend);
618 if (SUCCEEDED(hrc) && iSeg != UINT32_MAX)
619 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadmap", KeyStr.c_str(), "Segment", iSeg);
620
621 return SUCCEEDED(hrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
622}
623
624
625static DECLCALLBACK(void) handleVDError(void *pvUser, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list va)
626{
627 RT_NOREF(pvUser);
628 RTMsgErrorV(pszFormat, va);
629 RTMsgError(Internal::tr("Error code %Rrc at %s(%u) in function %s"), rc, RT_SRC_POS_ARGS);
630}
631
632static DECLCALLBACK(int) handleVDMessage(void *pvUser, const char *pszFormat, va_list va)
633{
634 NOREF(pvUser);
635 return RTPrintfV(pszFormat, va);
636}
637
638static RTEXITCODE CmdSetHDUUID(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
639{
640 RT_NOREF(aVirtualBox, aSession);
641 Guid uuid;
642 RTUUID rtuuid;
643 enum eUuidType {
644 HDUUID,
645 HDPARENTUUID
646 } uuidType;
647
648 if (!strcmp(argv[0], "sethduuid"))
649 {
650 uuidType = HDUUID;
651 if (argc != 3 && argc != 2)
652 return errorSyntax(USAGE_I_SETHDUUID, Internal::tr("Not enough parameters"));
653 /* if specified, take UUID, otherwise generate a new one */
654 if (argc == 3)
655 {
656 if (RT_FAILURE(RTUuidFromStr(&rtuuid, argv[2])))
657 return errorSyntax(USAGE_I_SETHDUUID, Internal::tr("Invalid UUID parameter"));
658 uuid = argv[2];
659 } else
660 uuid.create();
661 }
662 else if (!strcmp(argv[0], "sethdparentuuid"))
663 {
664 uuidType = HDPARENTUUID;
665 if (argc != 3)
666 return errorSyntax(USAGE_I_SETHDPARENTUUID, Internal::tr("Not enough parameters"));
667 if (RT_FAILURE(RTUuidFromStr(&rtuuid, argv[2])))
668 return errorSyntax(USAGE_I_SETHDPARENTUUID, Internal::tr("Invalid UUID parameter"));
669 uuid = argv[2];
670 }
671 else
672 return errorSyntax(USAGE_I_SETHDUUID, Internal::tr("Invalid invocation"));
673
674 /* just try it */
675 char *pszFormat = NULL;
676 VDTYPE enmType = VDTYPE_INVALID;
677 int rc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
678 argv[1], VDTYPE_INVALID, &pszFormat, &enmType);
679 if (RT_FAILURE(rc))
680 return RTMsgErrorExit(RTEXITCODE_FAILURE, Internal::tr("Format autodetect failed: %Rrc"), rc);
681
682 PVDISK pDisk = NULL;
683
684 PVDINTERFACE pVDIfs = NULL;
685 VDINTERFACEERROR vdInterfaceError;
686 vdInterfaceError.pfnError = handleVDError;
687 vdInterfaceError.pfnMessage = handleVDMessage;
688
689 rc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
690 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
691 AssertRC(rc);
692
693 rc = VDCreate(pVDIfs, enmType, &pDisk);
694 if (RT_FAILURE(rc))
695 return RTMsgErrorExit(RTEXITCODE_FAILURE, Internal::tr("Cannot create the virtual disk container: %Rrc"), rc);
696
697 /* Open the image */
698 rc = VDOpen(pDisk, pszFormat, argv[1], VD_OPEN_FLAGS_NORMAL | VD_OPEN_FLAGS_INFO, NULL);
699 if (RT_FAILURE(rc))
700 return RTMsgErrorExit(RTEXITCODE_FAILURE, Internal::tr("Cannot open the image: %Rrc"), rc);
701
702 if (uuidType == HDUUID)
703 rc = VDSetUuid(pDisk, VD_LAST_IMAGE, uuid.raw());
704 else
705 rc = VDSetParentUuid(pDisk, VD_LAST_IMAGE, uuid.raw());
706 if (RT_FAILURE(rc))
707 RTMsgError(Internal::tr("Cannot set a new UUID: %Rrc"), rc);
708 else
709 RTPrintf(Internal::tr("UUID changed to: %s\n"), uuid.toString().c_str());
710
711 VDCloseAll(pDisk);
712
713 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
714}
715
716
717static RTEXITCODE CmdDumpHDInfo(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
718{
719 RT_NOREF(aVirtualBox, aSession);
720
721 /* we need exactly one parameter: the image file */
722 if (argc != 1)
723 {
724 return errorSyntax(USAGE_I_DUMPHDINFO, Internal::tr("Not enough parameters"));
725 }
726
727 /* just try it */
728 char *pszFormat = NULL;
729 VDTYPE enmType = VDTYPE_INVALID;
730 int rc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
731 argv[0], VDTYPE_INVALID, &pszFormat, &enmType);
732 if (RT_FAILURE(rc))
733 return RTMsgErrorExit(RTEXITCODE_FAILURE, Internal::tr("Format autodetect failed: %Rrc"), rc);
734
735 PVDISK pDisk = NULL;
736
737 PVDINTERFACE pVDIfs = NULL;
738 VDINTERFACEERROR vdInterfaceError;
739 vdInterfaceError.pfnError = handleVDError;
740 vdInterfaceError.pfnMessage = handleVDMessage;
741
742 rc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
743 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
744 AssertRC(rc);
745
746 rc = VDCreate(pVDIfs, enmType, &pDisk);
747 if (RT_FAILURE(rc))
748 return RTMsgErrorExit(RTEXITCODE_FAILURE, Internal::tr("Cannot create the virtual disk container: %Rrc"), rc);
749
750 /* Open the image */
751 rc = VDOpen(pDisk, pszFormat, argv[0], VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO, NULL);
752 if (RT_FAILURE(rc))
753 return RTMsgErrorExit(RTEXITCODE_FAILURE, Internal::tr("Cannot open the image: %Rrc"), rc);
754
755 VDDumpImages(pDisk);
756
757 VDCloseAll(pDisk);
758
759 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
760}
761
762static int partRead(RTFILE File, PHOSTPARTITIONS pPart)
763{
764 uint8_t aBuffer[512];
765 uint8_t partitionTableHeader[512];
766 uint32_t sector_size = 512;
767 uint64_t lastUsableLBA = 0;
768 int rc;
769
770 VDISKPARTTYPE partitioningType;
771
772 pPart->cPartitions = 0;
773 memset(pPart->aPartitions, '\0', sizeof(pPart->aPartitions));
774
775 rc = RTFileReadAt(File, 0, &aBuffer, sizeof(aBuffer), NULL);
776 if (RT_FAILURE(rc))
777 return rc;
778
779 if (aBuffer[450] == 0xEE)/* check the sign of the GPT disk*/
780 {
781 partitioningType = VDISKPARTTYPE_GPT;
782 pPart->uPartitioningType = VDISKPARTTYPE_GPT;//partitioningType;
783
784 if (aBuffer[510] != 0x55 || aBuffer[511] != 0xaa)
785 return VERR_INVALID_PARAMETER;
786
787 rc = RTFileReadAt(File, sector_size, &partitionTableHeader, sector_size, NULL);
788 if (RT_SUCCESS(rc))
789 {
790 /** @todo r=bird: This is a 64-bit magic value, right... */
791 const char *l_ppth = (char *)partitionTableHeader;
792 if (strncmp(l_ppth, "EFI PART", 8))
793 return VERR_INVALID_PARAMETER;
794
795 /** @todo check GPT Version */
796
797 /** @todo r=bird: C have this handy concept called structures which
798 * greatly simplify data access... (Someone is really lazy here!) */
799#if 0 /* unused */
800 uint64_t firstUsableLBA = RT_MAKE_U64_FROM_U8(partitionTableHeader[40],
801 partitionTableHeader[41],
802 partitionTableHeader[42],
803 partitionTableHeader[43],
804 partitionTableHeader[44],
805 partitionTableHeader[45],
806 partitionTableHeader[46],
807 partitionTableHeader[47]
808 );
809#endif
810 lastUsableLBA = RT_MAKE_U64_FROM_U8(partitionTableHeader[48],
811 partitionTableHeader[49],
812 partitionTableHeader[50],
813 partitionTableHeader[51],
814 partitionTableHeader[52],
815 partitionTableHeader[53],
816 partitionTableHeader[54],
817 partitionTableHeader[55]
818 );
819 uint32_t partitionsNumber = RT_MAKE_U32_FROM_U8(partitionTableHeader[80],
820 partitionTableHeader[81],
821 partitionTableHeader[82],
822 partitionTableHeader[83]
823 );
824 uint32_t partitionEntrySize = RT_MAKE_U32_FROM_U8(partitionTableHeader[84],
825 partitionTableHeader[85],
826 partitionTableHeader[86],
827 partitionTableHeader[87]
828 );
829
830 uint32_t currentEntry = 0;
831
832 if (partitionEntrySize * partitionsNumber > 4 * _1M)
833 {
834 RTMsgError(Internal::tr("The GPT header seems corrupt because it contains too many entries"));
835 return VERR_INVALID_PARAMETER;
836 }
837
838 uint8_t *pbPartTable = (uint8_t *)RTMemAllocZ(RT_ALIGN_Z(partitionEntrySize * partitionsNumber, 512));
839 if (!pbPartTable)
840 {
841 RTMsgError(Internal::tr("Allocating memory for the GPT partitions entries failed"));
842 return VERR_NO_MEMORY;
843 }
844
845 /* partition entries begin from LBA2 */
846 /** @todo r=aeichner: Reading from LBA 2 is not always correct, the header will contain the starting LBA. */
847 rc = RTFileReadAt(File, 1024, pbPartTable, RT_ALIGN_Z(partitionEntrySize * partitionsNumber, 512), NULL);
848 if (RT_FAILURE(rc))
849 {
850 RTMsgError(Internal::tr("Reading the partition table failed"));
851 RTMemFree(pbPartTable);
852 return rc;
853 }
854
855 while (currentEntry < partitionsNumber)
856 {
857 uint8_t *partitionEntry = pbPartTable + currentEntry * partitionEntrySize;
858
859 uint64_t start = RT_MAKE_U64_FROM_U8(partitionEntry[32], partitionEntry[33], partitionEntry[34], partitionEntry[35],
860 partitionEntry[36], partitionEntry[37], partitionEntry[38], partitionEntry[39]);
861 uint64_t end = RT_MAKE_U64_FROM_U8(partitionEntry[40], partitionEntry[41], partitionEntry[42], partitionEntry[43],
862 partitionEntry[44], partitionEntry[45], partitionEntry[46], partitionEntry[47]);
863
864 PHOSTPARTITION pCP = &pPart->aPartitions[pPart->cPartitions++];
865 pCP->uIndex = currentEntry + 1;
866 pCP->uIndexWin = currentEntry + 1;
867 pCP->uType = 0;
868 pCP->uStartCylinder = 0;
869 pCP->uStartHead = 0;
870 pCP->uStartSector = 0;
871 pCP->uEndCylinder = 0;
872 pCP->uEndHead = 0;
873 pCP->uEndSector = 0;
874 pCP->uPartDataStart = 0; /* will be filled out later properly. */
875 pCP->cPartDataSectors = 0;
876 if (start==0 || end==0)
877 {
878 pCP->uIndex = 0;
879 pCP->uIndexWin = 0;
880 --pPart->cPartitions;
881 break;
882 }
883 else
884 {
885 pCP->uStart = start;
886 pCP->uSize = (end +1) - start;/*+1 LBA because the last address is included*/
887 }
888
889 ++currentEntry;
890 }
891
892 RTMemFree(pbPartTable);
893 }
894 }
895 else
896 {
897 partitioningType = VDISKPARTTYPE_MBR;
898 pPart->uPartitioningType = VDISKPARTTYPE_MBR;//partitioningType;
899
900 if (aBuffer[510] != 0x55 || aBuffer[511] != 0xaa)
901 return VERR_INVALID_PARAMETER;
902
903 unsigned uExtended = (unsigned)-1;
904 unsigned uIndexWin = 1;
905
906 for (unsigned i = 0; i < 4; i++)
907 {
908 uint8_t *p = &aBuffer[0x1be + i * 16];
909 if (p[4] == 0)
910 continue;
911 PHOSTPARTITION pCP = &pPart->aPartitions[pPart->cPartitions++];
912 pCP->uIndex = i + 1;
913 pCP->uType = p[4];
914 pCP->uStartCylinder = (uint32_t)p[3] + ((uint32_t)(p[2] & 0xc0) << 2);
915 pCP->uStartHead = p[1];
916 pCP->uStartSector = p[2] & 0x3f;
917 pCP->uEndCylinder = (uint32_t)p[7] + ((uint32_t)(p[6] & 0xc0) << 2);
918 pCP->uEndHead = p[5];
919 pCP->uEndSector = p[6] & 0x3f;
920 pCP->uStart = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
921 pCP->uSize = RT_MAKE_U32_FROM_U8(p[12], p[13], p[14], p[15]);
922 pCP->uPartDataStart = 0; /* will be filled out later properly. */
923 pCP->cPartDataSectors = 0;
924
925 if (PARTTYPE_IS_EXTENDED(p[4]))
926 {
927 if (uExtended == (unsigned)-1)
928 {
929 uExtended = (unsigned)(pCP - pPart->aPartitions);
930 pCP->uIndexWin = 0;
931 }
932 else
933 {
934 RTMsgError(Internal::tr("More than one extended partition"));
935 return VERR_INVALID_PARAMETER;
936 }
937 }
938 else
939 {
940 pCP->uIndexWin = uIndexWin;
941 uIndexWin++;
942 }
943 }
944
945 if (uExtended != (unsigned)-1)
946 {
947 unsigned uIndex = 5;
948 uint64_t uStart = pPart->aPartitions[uExtended].uStart;
949 uint64_t uOffset = 0;
950 if (!uStart)
951 {
952 RTMsgError(Internal::tr("Inconsistency for logical partition start"));
953 return VERR_INVALID_PARAMETER;
954 }
955
956 do
957 {
958 rc = RTFileReadAt(File, (uStart + uOffset) * 512, &aBuffer, sizeof(aBuffer), NULL);
959 if (RT_FAILURE(rc))
960 return rc;
961
962 if (aBuffer[510] != 0x55 || aBuffer[511] != 0xaa)
963 {
964 RTMsgError(Internal::tr("Logical partition without magic"));
965 return VERR_INVALID_PARAMETER;
966 }
967 uint8_t *p = &aBuffer[0x1be];
968
969 if (p[4] == 0)
970 {
971 RTMsgError(Internal::tr("Logical partition with type 0 encountered"));
972 return VERR_INVALID_PARAMETER;
973 }
974
975 PHOSTPARTITION pCP = &pPart->aPartitions[pPart->cPartitions++];
976 pCP->uIndex = uIndex;
977 pCP->uIndexWin = uIndexWin;
978 pCP->uType = p[4];
979 pCP->uStartCylinder = (uint32_t)p[3] + ((uint32_t)(p[2] & 0xc0) << 2);
980 pCP->uStartHead = p[1];
981 pCP->uStartSector = p[2] & 0x3f;
982 pCP->uEndCylinder = (uint32_t)p[7] + ((uint32_t)(p[6] & 0xc0) << 2);
983 pCP->uEndHead = p[5];
984 pCP->uEndSector = p[6] & 0x3f;
985 uint32_t uStartOffset = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
986 if (!uStartOffset)
987 {
988 RTMsgError(Internal::tr("Invalid partition start offset"));
989 return VERR_INVALID_PARAMETER;
990 }
991 pCP->uStart = uStart + uOffset + uStartOffset;
992 pCP->uSize = RT_MAKE_U32_FROM_U8(p[12], p[13], p[14], p[15]);
993 /* Fill out partitioning location info for EBR. */
994 pCP->uPartDataStart = uStart + uOffset;
995 pCP->cPartDataSectors = uStartOffset;
996 p += 16;
997 if (p[4] == 0)
998 uExtended = (unsigned)-1;
999 else if (PARTTYPE_IS_EXTENDED(p[4]))
1000 {
1001 uExtended = uIndex;
1002 uIndex++;
1003 uIndexWin++;
1004 uOffset = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
1005 }
1006 else
1007 {
1008 RTMsgError(Internal::tr("Logical partition chain broken"));
1009 return VERR_INVALID_PARAMETER;
1010 }
1011 } while (uExtended != (unsigned)-1);
1012 }
1013 }
1014
1015
1016 /* Sort partitions in ascending order of start sector, plus a trivial
1017 * bit of consistency checking. */
1018 for (unsigned i = 0; i < pPart->cPartitions-1; i++)
1019 {
1020 unsigned uMinIdx = i;
1021 uint64_t uMinVal = pPart->aPartitions[i].uStart;
1022 for (unsigned j = i + 1; j < pPart->cPartitions; j++)
1023 {
1024 if (pPart->aPartitions[j].uStart < uMinVal)
1025 {
1026 uMinIdx = j;
1027 uMinVal = pPart->aPartitions[j].uStart;
1028 }
1029 else if (pPart->aPartitions[j].uStart == uMinVal)
1030 {
1031 RTMsgError(Internal::tr("Two partitions start at the same place"));
1032 return VERR_INVALID_PARAMETER;
1033 }
1034 else if (pPart->aPartitions[j].uStart == 0)
1035 {
1036 RTMsgError(Internal::tr("Partition starts at sector 0"));
1037 return VERR_INVALID_PARAMETER;
1038 }
1039 }
1040 if (uMinIdx != i)
1041 {
1042 /* Swap entries at index i and uMinIdx. */
1043 memcpy(&pPart->aPartitions[pPart->cPartitions],
1044 &pPart->aPartitions[i], sizeof(HOSTPARTITION));
1045 memcpy(&pPart->aPartitions[i],
1046 &pPart->aPartitions[uMinIdx], sizeof(HOSTPARTITION));
1047 memcpy(&pPart->aPartitions[uMinIdx],
1048 &pPart->aPartitions[pPart->cPartitions], sizeof(HOSTPARTITION));
1049 }
1050 }
1051
1052 /* Fill out partitioning location info for MBR or GPT. */
1053 pPart->aPartitions[0].uPartDataStart = 0;
1054 pPart->aPartitions[0].cPartDataSectors = pPart->aPartitions[0].uStart;
1055
1056 /* Fill out partitioning location info for backup GPT. */
1057 if (partitioningType == VDISKPARTTYPE_GPT)
1058 {
1059 pPart->aPartitions[pPart->cPartitions-1].uPartDataStart = lastUsableLBA+1;
1060 pPart->aPartitions[pPart->cPartitions-1].cPartDataSectors = 33;
1061
1062 /* Now do a some partition table consistency checking, to reject the most
1063 * obvious garbage which can lead to trouble later. */
1064 uint64_t uPrevEnd = 0;
1065 for (unsigned i = 0; i < pPart->cPartitions; i++)
1066 {
1067 if (pPart->aPartitions[i].cPartDataSectors)
1068 uPrevEnd = pPart->aPartitions[i].uPartDataStart + pPart->aPartitions[i].cPartDataSectors;
1069 if (pPart->aPartitions[i].uStart < uPrevEnd &&
1070 pPart->cPartitions-1 != i)
1071 {
1072 RTMsgError(Internal::tr("Overlapping GPT partitions"));
1073 return VERR_INVALID_PARAMETER;
1074 }
1075 }
1076 }
1077 else
1078 {
1079 /* Now do a some partition table consistency checking, to reject the most
1080 * obvious garbage which can lead to trouble later. */
1081 uint64_t uPrevEnd = 0;
1082 for (unsigned i = 0; i < pPart->cPartitions; i++)
1083 {
1084 if (pPart->aPartitions[i].cPartDataSectors)
1085 uPrevEnd = pPart->aPartitions[i].uPartDataStart + pPart->aPartitions[i].cPartDataSectors;
1086 if (pPart->aPartitions[i].uStart < uPrevEnd)
1087 {
1088 RTMsgError(Internal::tr("Overlapping MBR partitions"));
1089 return VERR_INVALID_PARAMETER;
1090 }
1091 if (!PARTTYPE_IS_EXTENDED(pPart->aPartitions[i].uType))
1092 uPrevEnd = pPart->aPartitions[i].uStart + pPart->aPartitions[i].uSize;
1093 }
1094 }
1095
1096 return VINF_SUCCESS;
1097}
1098
1099static RTEXITCODE CmdListPartitions(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1100{
1101 RT_NOREF(aVirtualBox, aSession);
1102 Utf8Str rawdisk;
1103
1104 /* let's have a closer look at the arguments */
1105 for (int i = 0; i < argc; i++)
1106 {
1107 if (strcmp(argv[i], "-rawdisk") == 0)
1108 {
1109 if (argc <= i + 1)
1110 {
1111 return errorArgument(Internal::tr("Missing argument to '%s'"), argv[i]);
1112 }
1113 i++;
1114 rawdisk = argv[i];
1115 }
1116 else
1117 {
1118 return errorSyntax(USAGE_I_LISTPARTITIONS, Internal::tr("Invalid parameter '%s'"), argv[i]);
1119 }
1120 }
1121
1122 if (rawdisk.isEmpty())
1123 return errorSyntax(USAGE_I_LISTPARTITIONS, Internal::tr("Mandatory parameter -rawdisk missing"));
1124
1125 RTFILE hRawFile;
1126 int vrc = RTFileOpen(&hRawFile, rawdisk.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1127 if (RT_FAILURE(vrc))
1128 return RTMsgErrorExit(RTEXITCODE_FAILURE, Internal::tr("Cannot open the raw disk: %Rrc"), vrc);
1129
1130 HOSTPARTITIONS partitions;
1131 vrc = partRead(hRawFile, &partitions);
1132 /* Don't bail out on errors, print the table and return the result code. */
1133
1134 RTPrintf(Internal::tr("Number Type StartCHS EndCHS Size (MiB) Start (Sect)\n"));
1135 for (unsigned i = 0; i < partitions.cPartitions; i++)
1136 {
1137 /* Don't show the extended partition, otherwise users might think they
1138 * can add it to the list of partitions for raw partition access. */
1139 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1140 continue;
1141
1142 RTPrintf("%-7u %#04x %-4u/%-3u/%-2u %-4u/%-3u/%-2u %10llu %10llu\n",
1143 partitions.aPartitions[i].uIndex,
1144 partitions.aPartitions[i].uType,
1145 partitions.aPartitions[i].uStartCylinder,
1146 partitions.aPartitions[i].uStartHead,
1147 partitions.aPartitions[i].uStartSector,
1148 partitions.aPartitions[i].uEndCylinder,
1149 partitions.aPartitions[i].uEndHead,
1150 partitions.aPartitions[i].uEndSector,
1151 partitions.aPartitions[i].uSize / 2048,
1152 partitions.aPartitions[i].uStart);
1153 }
1154
1155 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1156}
1157
1158static PVDISKRAWPARTDESC appendPartDesc(uint32_t *pcPartDescs, PVDISKRAWPARTDESC *ppPartDescs)
1159{
1160 (*pcPartDescs)++;
1161 PVDISKRAWPARTDESC p;
1162 p = (PVDISKRAWPARTDESC)RTMemRealloc(*ppPartDescs,
1163 *pcPartDescs * sizeof(VDISKRAWPARTDESC));
1164 *ppPartDescs = p;
1165 if (p)
1166 {
1167 p = p + *pcPartDescs - 1;
1168 memset(p, '\0', sizeof(VDISKRAWPARTDESC));
1169 }
1170
1171 return p;
1172}
1173
1174static RTEXITCODE CmdCreateRawVMDK(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1175{
1176 RT_NOREF(aVirtualBox, aSession);
1177 HRESULT rc = S_OK;
1178 Utf8Str filename;
1179 const char *pszMBRFilename = NULL;
1180 Utf8Str rawdisk;
1181 const char *pszPartitions = NULL;
1182 bool fRelative = false;
1183
1184 uint64_t cbSize = 0;
1185 PVDISK pDisk = NULL;
1186 VDISKRAW RawDescriptor;
1187 PVDINTERFACE pVDIfs = NULL;
1188
1189 /* let's have a closer look at the arguments */
1190 for (int i = 0; i < argc; i++)
1191 {
1192 if (strcmp(argv[i], "-filename") == 0)
1193 {
1194 if (argc <= i + 1)
1195 {
1196 return errorArgument(Internal::tr("Missing argument to '%s'"), argv[i]);
1197 }
1198 i++;
1199 filename = argv[i];
1200 }
1201 else if (strcmp(argv[i], "-mbr") == 0)
1202 {
1203 if (argc <= i + 1)
1204 {
1205 return errorArgument(Internal::tr("Missing argument to '%s'"), argv[i]);
1206 }
1207 i++;
1208 pszMBRFilename = argv[i];
1209 }
1210 else if (strcmp(argv[i], "-rawdisk") == 0)
1211 {
1212 if (argc <= i + 1)
1213 {
1214 return errorArgument(Internal::tr("Missing argument to '%s'"), argv[i]);
1215 }
1216 i++;
1217 rawdisk = argv[i];
1218 }
1219 else if (strcmp(argv[i], "-partitions") == 0)
1220 {
1221 if (argc <= i + 1)
1222 {
1223 return errorArgument(Internal::tr("Missing argument to '%s'"), argv[i]);
1224 }
1225 i++;
1226 pszPartitions = argv[i];
1227 }
1228#if defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD) || defined(RT_OS_WINDOWS)
1229 else if (strcmp(argv[i], "-relative") == 0)
1230 {
1231 fRelative = true;
1232 }
1233#endif /* RT_OS_LINUX || RT_OS_FREEBSD */
1234 else
1235 return errorSyntax(USAGE_I_CREATERAWVMDK, Internal::tr("Invalid parameter '%s'"), argv[i]);
1236 }
1237
1238 if (filename.isEmpty())
1239 return errorSyntax(USAGE_I_CREATERAWVMDK, Internal::tr("Mandatory parameter -filename missing"));
1240 if (rawdisk.isEmpty())
1241 return errorSyntax(USAGE_I_CREATERAWVMDK, Internal::tr("Mandatory parameter -rawdisk missing"));
1242 if (!pszPartitions && pszMBRFilename)
1243 return errorSyntax(USAGE_I_CREATERAWVMDK,
1244 Internal::tr("The parameter -mbr is only valid when the parameter -partitions is also present"));
1245
1246#ifdef RT_OS_DARWIN
1247 fRelative = true;
1248#endif /* RT_OS_DARWIN */
1249 RTFILE hRawFile;
1250 int vrc = RTFileOpen(&hRawFile, rawdisk.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1251 if (RT_FAILURE(vrc))
1252 {
1253 RTMsgError(Internal::tr("Cannot open the raw disk '%s': %Rrc"), rawdisk.c_str(), vrc);
1254 goto out;
1255 }
1256
1257#ifdef RT_OS_WINDOWS
1258 /* Windows NT has no IOCTL_DISK_GET_LENGTH_INFORMATION ioctl. This was
1259 * added to Windows XP, so we have to use the available info from DriveGeo.
1260 * Note that we cannot simply use IOCTL_DISK_GET_DRIVE_GEOMETRY as it
1261 * yields a slightly different result than IOCTL_DISK_GET_LENGTH_INFO.
1262 * We call IOCTL_DISK_GET_DRIVE_GEOMETRY first as we need to check the media
1263 * type anyway, and if IOCTL_DISK_GET_LENGTH_INFORMATION is supported
1264 * we will later override cbSize.
1265 */
1266 DISK_GEOMETRY DriveGeo;
1267 DWORD cbDriveGeo;
1268 if (DeviceIoControl((HANDLE)RTFileToNative(hRawFile),
1269 IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,
1270 &DriveGeo, sizeof(DriveGeo), &cbDriveGeo, NULL))
1271 {
1272 if ( DriveGeo.MediaType == FixedMedia
1273 || DriveGeo.MediaType == RemovableMedia)
1274 {
1275 cbSize = DriveGeo.Cylinders.QuadPart
1276 * DriveGeo.TracksPerCylinder
1277 * DriveGeo.SectorsPerTrack
1278 * DriveGeo.BytesPerSector;
1279 }
1280 else
1281 {
1282 RTMsgError(Internal::tr("File '%s' is no fixed/removable medium device"), rawdisk.c_str());
1283 vrc = VERR_INVALID_PARAMETER;
1284 goto out;
1285 }
1286
1287 GET_LENGTH_INFORMATION DiskLenInfo;
1288 DWORD junk;
1289 if (DeviceIoControl((HANDLE)RTFileToNative(hRawFile),
1290 IOCTL_DISK_GET_LENGTH_INFO, NULL, 0,
1291 &DiskLenInfo, sizeof(DiskLenInfo), &junk, (LPOVERLAPPED)NULL))
1292 {
1293 /* IOCTL_DISK_GET_LENGTH_INFO is supported -- override cbSize. */
1294 cbSize = DiskLenInfo.Length.QuadPart;
1295 }
1296 if ( fRelative
1297 && !rawdisk.startsWith("\\\\.\\PhysicalDrive", Utf8Str::CaseInsensitive))
1298 {
1299 RTMsgError(Internal::tr("The -relative parameter is invalid for raw disk %s"), rawdisk.c_str());
1300 vrc = VERR_INVALID_PARAMETER;
1301 goto out;
1302 }
1303 }
1304 else
1305 {
1306 /*
1307 * Could be raw image, remember error code and try to get the size first
1308 * before failing.
1309 */
1310 vrc = RTErrConvertFromWin32(GetLastError());
1311 if (RT_FAILURE(RTFileQuerySize(hRawFile, &cbSize)))
1312 {
1313 RTMsgError(Internal::tr("Cannot get the geometry of the raw disk '%s': %Rrc"), rawdisk.c_str(), vrc);
1314 goto out;
1315 }
1316 else
1317 {
1318 if (fRelative)
1319 {
1320 RTMsgError(Internal::tr("The -relative parameter is invalid for raw images"));
1321 vrc = VERR_INVALID_PARAMETER;
1322 goto out;
1323 }
1324 vrc = VINF_SUCCESS;
1325 }
1326 }
1327#elif defined(RT_OS_LINUX)
1328 struct stat DevStat;
1329 if (!fstat(RTFileToNative(hRawFile), &DevStat))
1330 {
1331 if (S_ISBLK(DevStat.st_mode))
1332 {
1333#ifdef BLKGETSIZE64
1334 /* BLKGETSIZE64 is broken up to 2.4.17 and in many 2.5.x. In 2.6.0
1335 * it works without problems. */
1336 struct utsname utsname;
1337 if ( uname(&utsname) == 0
1338 && ( (strncmp(utsname.release, "2.5.", 4) == 0 && atoi(&utsname.release[4]) >= 18)
1339 || (strncmp(utsname.release, "2.", 2) == 0 && atoi(&utsname.release[2]) >= 6)))
1340 {
1341 uint64_t cbBlk;
1342 if (!ioctl(RTFileToNative(hRawFile), BLKGETSIZE64, &cbBlk))
1343 cbSize = cbBlk;
1344 }
1345#endif /* BLKGETSIZE64 */
1346 if (!cbSize)
1347 {
1348 long cBlocks;
1349 if (!ioctl(RTFileToNative(hRawFile), BLKGETSIZE, &cBlocks))
1350 cbSize = (uint64_t)cBlocks << 9;
1351 else
1352 {
1353 vrc = RTErrConvertFromErrno(errno);
1354 RTMsgError(Internal::tr("Cannot get the size of the raw disk '%s': %Rrc"), rawdisk.c_str(), vrc);
1355 goto out;
1356 }
1357 }
1358 }
1359 else if (S_ISREG(DevStat.st_mode))
1360 {
1361 vrc = RTFileQuerySize(hRawFile, &cbSize);
1362 if (RT_FAILURE(vrc))
1363 {
1364 RTMsgError(Internal::tr("Failed to get size of file '%s': %Rrc"), rawdisk.c_str(), vrc);
1365 goto out;
1366 }
1367 else if (fRelative)
1368 {
1369 RTMsgError(Internal::tr("The -relative parameter is invalid for raw images"));
1370 vrc = VERR_INVALID_PARAMETER;
1371 goto out;
1372 }
1373 }
1374 else
1375 {
1376 RTMsgError(Internal::tr("File '%s' is no block device"), rawdisk.c_str());
1377 vrc = VERR_INVALID_PARAMETER;
1378 goto out;
1379 }
1380 }
1381 else
1382 {
1383 vrc = RTErrConvertFromErrno(errno);
1384 RTMsgError(Internal::tr("Failed to get file informtation for raw disk '%s': %Rrc"),
1385 rawdisk.c_str(), vrc);
1386 }
1387#elif defined(RT_OS_DARWIN)
1388 struct stat DevStat;
1389 if (!fstat(RTFileToNative(hRawFile), &DevStat))
1390 {
1391 if (S_ISBLK(DevStat.st_mode))
1392 {
1393 uint64_t cBlocks;
1394 uint32_t cbBlock;
1395 if (!ioctl(RTFileToNative(hRawFile), DKIOCGETBLOCKCOUNT, &cBlocks))
1396 {
1397 if (!ioctl(RTFileToNative(hRawFile), DKIOCGETBLOCKSIZE, &cbBlock))
1398 cbSize = cBlocks * cbBlock;
1399 else
1400 {
1401 RTMsgError(Internal::tr("Cannot get the block size for file '%s': %Rrc", rawdisk.c_str()), vrc);
1402 vrc = RTErrConvertFromErrno(errno);
1403 goto out;
1404 }
1405 }
1406 else
1407 {
1408 vrc = RTErrConvertFromErrno(errno);
1409 RTMsgError(Internal::tr("Cannot get the block count for file '%s': %Rrc"), rawdisk.c_str(), vrc);
1410 goto out;
1411 }
1412 }
1413 else if (S_ISREG(DevStat.st_mode))
1414 {
1415 fRelative = false; /* Must be false for raw image files. */
1416 vrc = RTFileQuerySize(hRawFile, &cbSize);
1417 if (RT_FAILURE(vrc))
1418 {
1419 RTMsgError(Internal::tr("Failed to get size of file '%s': %Rrc"), rawdisk.c_str(), vrc);
1420 goto out;
1421 }
1422 }
1423 else
1424 {
1425 RTMsgError(Internal::tr("File '%s' is neither block device nor regular file"), rawdisk.c_str());
1426 vrc = VERR_INVALID_PARAMETER;
1427 goto out;
1428 }
1429 }
1430 else
1431 {
1432 vrc = RTErrConvertFromErrno(errno);
1433 RTMsgError(Internal::tr("Failed to get file informtation for raw disk '%s': %Rrc"),
1434 rawdisk.c_str(), vrc);
1435 }
1436#elif defined(RT_OS_SOLARIS)
1437 struct stat DevStat;
1438 if (!fstat(RTFileToNative(hRawFile), &DevStat))
1439 {
1440 if (S_ISBLK(DevStat.st_mode) || S_ISCHR(DevStat.st_mode))
1441 {
1442 struct dk_minfo mediainfo;
1443 if (!ioctl(RTFileToNative(hRawFile), DKIOCGMEDIAINFO, &mediainfo))
1444 cbSize = mediainfo.dki_capacity * mediainfo.dki_lbsize;
1445 else
1446 {
1447 vrc = RTErrConvertFromErrno(errno);
1448 RTMsgError(Internal::tr("Cannot get the size of the raw disk '%s': %Rrc"), rawdisk.c_str(), vrc);
1449 goto out;
1450 }
1451 }
1452 else if (S_ISREG(DevStat.st_mode))
1453 {
1454 vrc = RTFileQuerySize(hRawFile, &cbSize);
1455 if (RT_FAILURE(vrc))
1456 {
1457 RTMsgError(Internal::tr("Failed to get size of file '%s': %Rrc"), rawdisk.c_str(), vrc);
1458 goto out;
1459 }
1460 }
1461 else
1462 {
1463 RTMsgError(Internal::tr("File '%s' is no block or char device"), rawdisk.c_str());
1464 vrc = VERR_INVALID_PARAMETER;
1465 goto out;
1466 }
1467 }
1468 else
1469 {
1470 vrc = RTErrConvertFromErrno(errno);
1471 RTMsgError(Internal::tr("Failed to get file informtation for raw disk '%s': %Rrc"),
1472 rawdisk.c_str(), vrc);
1473 }
1474#elif defined(RT_OS_FREEBSD)
1475 struct stat DevStat;
1476 if (!fstat(RTFileToNative(hRawFile), &DevStat))
1477 {
1478 if (S_ISCHR(DevStat.st_mode))
1479 {
1480 off_t cbMedia = 0;
1481 if (!ioctl(RTFileToNative(hRawFile), DIOCGMEDIASIZE, &cbMedia))
1482 cbSize = cbMedia;
1483 else
1484 {
1485 vrc = RTErrConvertFromErrno(errno);
1486 RTMsgError(Internal::tr("Cannot get the block count for file '%s': %Rrc"), rawdisk.c_str(), vrc);
1487 goto out;
1488 }
1489 }
1490 else if (S_ISREG(DevStat.st_mode))
1491 {
1492 if (fRelative)
1493 {
1494 RTMsgError(Internal::tr("The -relative parameter is invalid for raw images"));
1495 vrc = VERR_INVALID_PARAMETER;
1496 goto out;
1497 }
1498 cbSize = DevStat.st_size;
1499 }
1500 else
1501 {
1502 RTMsgError(Internal::tr("File '%s' is neither character device nor regular file"), rawdisk.c_str());
1503 vrc = VERR_INVALID_PARAMETER;
1504 goto out;
1505 }
1506 }
1507 else
1508 {
1509 vrc = RTErrConvertFromErrno(errno);
1510 RTMsgError(Internal::tr("Failed to get file informtation for raw disk '%s': %Rrc"),
1511 rawdisk.c_str(), vrc);
1512 }
1513#else /* all unrecognized OSes */
1514 /* Hopefully this works on all other hosts. If it doesn't, it'll just fail
1515 * creating the VMDK, so no real harm done. */
1516 vrc = RTFileQuerySize(hRawFile, &cbSize);
1517 if (RT_FAILURE(vrc))
1518 {
1519 RTMsgError(Internal::tr("Cannot get the size of the raw disk '%s': %Rrc"), rawdisk.c_str(), vrc);
1520 goto out;
1521 }
1522#endif
1523
1524 /* Check whether cbSize is actually sensible. */
1525 if (!cbSize || cbSize % 512)
1526 {
1527 RTMsgError(Internal::tr("Detected size of raw disk '%s' is %RU64, an invalid value"), rawdisk.c_str(), cbSize);
1528 vrc = VERR_INVALID_PARAMETER;
1529 goto out;
1530 }
1531
1532 RawDescriptor.szSignature[0] = 'R';
1533 RawDescriptor.szSignature[1] = 'A';
1534 RawDescriptor.szSignature[2] = 'W';
1535 RawDescriptor.szSignature[3] = '\0';
1536 if (!pszPartitions)
1537 {
1538 RawDescriptor.uFlags = VDISKRAW_DISK;
1539 RawDescriptor.pszRawDisk = (char *)rawdisk.c_str();
1540 }
1541 else
1542 {
1543 RawDescriptor.uFlags = VDISKRAW_NORMAL;
1544 RawDescriptor.pszRawDisk = NULL;
1545 RawDescriptor.cPartDescs = 0;
1546 RawDescriptor.pPartDescs = NULL;
1547
1548 uint32_t uPartitions = 0;
1549 uint32_t uPartitionsRO = 0;
1550
1551 const char *p = pszPartitions;
1552 char *pszNext;
1553 uint32_t u32;
1554 while (*p != '\0')
1555 {
1556 vrc = RTStrToUInt32Ex(p, &pszNext, 0, &u32);
1557 if (RT_FAILURE(vrc))
1558 {
1559 RTMsgError(Internal::tr("Incorrect value in partitions parameter"));
1560 goto out;
1561 }
1562 uPartitions |= RT_BIT(u32);
1563 p = pszNext;
1564 if (*p == 'r')
1565 {
1566 uPartitionsRO |= RT_BIT(u32);
1567 p++;
1568 }
1569 if (*p == ',')
1570 p++;
1571 else if (*p != '\0')
1572 {
1573 RTMsgError(Internal::tr("Incorrect separator in partitions parameter"));
1574 vrc = VERR_INVALID_PARAMETER;
1575 goto out;
1576 }
1577 }
1578
1579 HOSTPARTITIONS partitions;
1580 vrc = partRead(hRawFile, &partitions);
1581 if (RT_FAILURE(vrc))
1582 {
1583 RTMsgError(Internal::tr("Cannot read the partition information from '%s'"), rawdisk.c_str());
1584 goto out;
1585 }
1586
1587 RawDescriptor.enmPartitioningType = partitions.uPartitioningType;
1588
1589 for (unsigned i = 0; i < partitions.cPartitions; i++)
1590 {
1591 if ( uPartitions & RT_BIT(partitions.aPartitions[i].uIndex)
1592 && PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1593 {
1594 /* Some ignorant user specified an extended partition.
1595 * Bad idea, as this would trigger an overlapping
1596 * partitions error later during VMDK creation. So warn
1597 * here and ignore what the user requested. */
1598 RTMsgWarning(Internal::tr(
1599 "It is not possible (and necessary) to explicitly give access to the "
1600 "extended partition %u. If required, enable access to all logical "
1601 "partitions inside this extended partition."),
1602 partitions.aPartitions[i].uIndex);
1603 uPartitions &= ~RT_BIT(partitions.aPartitions[i].uIndex);
1604 }
1605 }
1606
1607 for (unsigned i = 0; i < partitions.cPartitions; i++)
1608 {
1609 PVDISKRAWPARTDESC pPartDesc = NULL;
1610
1611 /* first dump the MBR/EPT data area */
1612 if (partitions.aPartitions[i].cPartDataSectors)
1613 {
1614 pPartDesc = appendPartDesc(&RawDescriptor.cPartDescs,
1615 &RawDescriptor.pPartDescs);
1616 if (!pPartDesc)
1617 {
1618 RTMsgError(Internal::tr("Out of memory allocating the partition list for '%s'"), rawdisk.c_str());
1619 vrc = VERR_NO_MEMORY;
1620 goto out;
1621 }
1622
1623 /** @todo the clipping below isn't 100% accurate, as it should
1624 * actually clip to the track size. However, that's easier said
1625 * than done as figuring out the track size is heuristics. In
1626 * any case the clipping is adjusted later after sorting, to
1627 * prevent overlapping data areas on the resulting image. */
1628 pPartDesc->cbData = RT_MIN(partitions.aPartitions[i].cPartDataSectors, 63) * 512;
1629 pPartDesc->offStartInVDisk = partitions.aPartitions[i].uPartDataStart * 512;
1630 Assert(pPartDesc->cbData - (size_t)pPartDesc->cbData == 0);
1631 void *pPartData = RTMemAlloc((size_t)pPartDesc->cbData);
1632 if (!pPartData)
1633 {
1634 RTMsgError(Internal::tr("Out of memory allocating the partition descriptor for '%s'"),
1635 rawdisk.c_str());
1636 vrc = VERR_NO_MEMORY;
1637 goto out;
1638 }
1639 vrc = RTFileReadAt(hRawFile, partitions.aPartitions[i].uPartDataStart * 512,
1640 pPartData, (size_t)pPartDesc->cbData, NULL);
1641 if (RT_FAILURE(vrc))
1642 {
1643 RTMsgError(Internal::tr("Cannot read partition data from raw device '%s': %Rrc"),
1644 rawdisk.c_str(), vrc);
1645 goto out;
1646 }
1647 /* Splice in the replacement MBR code if specified. */
1648 if ( partitions.aPartitions[i].uPartDataStart == 0
1649 && pszMBRFilename)
1650 {
1651 RTFILE MBRFile;
1652 vrc = RTFileOpen(&MBRFile, pszMBRFilename, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1653 if (RT_FAILURE(vrc))
1654 {
1655 RTMsgError(Internal::tr("Cannot open replacement MBR file '%s' specified with -mbr: %Rrc"),
1656 pszMBRFilename, vrc);
1657 goto out;
1658 }
1659 vrc = RTFileReadAt(MBRFile, 0, pPartData, 0x1be, NULL);
1660 RTFileClose(MBRFile);
1661 if (RT_FAILURE(vrc))
1662 {
1663 RTMsgError(Internal::tr("Cannot read replacement MBR file '%s': %Rrc"), pszMBRFilename, vrc);
1664 goto out;
1665 }
1666 }
1667 pPartDesc->pvPartitionData = pPartData;
1668 }
1669
1670 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1671 {
1672 /* Suppress exporting the actual extended partition. Only
1673 * logical partitions should be processed. However completely
1674 * ignoring it leads to leaving out the EBR data. */
1675 continue;
1676 }
1677
1678 /* set up values for non-relative device names */
1679 const char *pszRawName = rawdisk.c_str();
1680 uint64_t uStartOffset = partitions.aPartitions[i].uStart * 512;
1681
1682 pPartDesc = appendPartDesc(&RawDescriptor.cPartDescs,
1683 &RawDescriptor.pPartDescs);
1684 if (!pPartDesc)
1685 {
1686 RTMsgError(Internal::tr("Out of memory allocating the partition list for '%s'"), rawdisk.c_str());
1687 vrc = VERR_NO_MEMORY;
1688 goto out;
1689 }
1690
1691 if (uPartitions & RT_BIT(partitions.aPartitions[i].uIndex))
1692 {
1693 if (uPartitionsRO & RT_BIT(partitions.aPartitions[i].uIndex))
1694 pPartDesc->uFlags |= VDISKRAW_READONLY;
1695
1696 if (fRelative)
1697 {
1698#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD)
1699 /* Refer to the correct partition and use offset 0. */
1700 char *psz;
1701#if defined(RT_OS_LINUX)
1702 /*
1703 * Check whether raw disk ends with a digit. In that case
1704 * insert a p before adding the partition number.
1705 * This is used for nvme devices only currently which look like
1706 * /dev/nvme0n1p1 but might be extended to other devices in the
1707 * future.
1708 */
1709 size_t cchRawDisk = rawdisk.length();
1710 if (RT_C_IS_DIGIT(pszRawName[cchRawDisk - 1]))
1711 RTStrAPrintf(&psz,
1712 "%sp%u",
1713 rawdisk.c_str(),
1714 partitions.aPartitions[i].uIndex);
1715 else
1716 RTStrAPrintf(&psz,
1717 "%s%u",
1718 rawdisk.c_str(),
1719 partitions.aPartitions[i].uIndex);
1720#elif defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD)
1721 RTStrAPrintf(&psz,
1722 "%ss%u",
1723 rawdisk.c_str(),
1724 partitions.aPartitions[i].uIndex);
1725#endif
1726 if (!psz)
1727 {
1728 vrc = VERR_NO_STR_MEMORY;
1729 RTMsgError(Internal::tr("Cannot create reference to individual partition %u, rc=%Rrc"),
1730 partitions.aPartitions[i].uIndex, vrc);
1731 goto out;
1732 }
1733 pszRawName = psz;
1734 uStartOffset = 0;
1735#elif defined(RT_OS_WINDOWS)
1736 /* Refer to the correct partition and use offset 0. */
1737 char *psz;
1738 RTStrAPrintf(&psz, "\\\\.\\Harddisk%sPartition%u",
1739 rawdisk.c_str() + 17,
1740 partitions.aPartitions[i].uIndexWin);
1741 if (!psz)
1742 {
1743 vrc = VERR_NO_STR_MEMORY;
1744 RTMsgError(Internal::tr("Cannot create reference to individual partition %u (numbered %u), rc=%Rrc"),
1745 partitions.aPartitions[i].uIndex, partitions.aPartitions[i].uIndexWin, vrc);
1746 goto out;
1747 }
1748 pszRawName = psz;
1749 uStartOffset = 0;
1750#else
1751 /** @todo not implemented for other hosts. Treat just like
1752 * not specified (this code is actually never reached). */
1753#endif
1754 }
1755
1756 pPartDesc->pszRawDevice = (char *)pszRawName;
1757 pPartDesc->offStartInDevice = uStartOffset;
1758 }
1759 else
1760 {
1761 pPartDesc->pszRawDevice = NULL;
1762 pPartDesc->offStartInDevice = 0;
1763 }
1764
1765 pPartDesc->offStartInVDisk = partitions.aPartitions[i].uStart * 512;
1766 pPartDesc->cbData = partitions.aPartitions[i].uSize * 512;
1767 }
1768
1769 /* Sort data areas in ascending order of start. */
1770 for (unsigned i = 0; i < RawDescriptor.cPartDescs-1; i++)
1771 {
1772 unsigned uMinIdx = i;
1773 uint64_t uMinVal = RawDescriptor.pPartDescs[i].offStartInVDisk;
1774 for (unsigned j = i + 1; j < RawDescriptor.cPartDescs; j++)
1775 {
1776 if (RawDescriptor.pPartDescs[j].offStartInVDisk < uMinVal)
1777 {
1778 uMinIdx = j;
1779 uMinVal = RawDescriptor.pPartDescs[j].offStartInVDisk;
1780 }
1781 }
1782 if (uMinIdx != i)
1783 {
1784 /* Swap entries at index i and uMinIdx. */
1785 VDISKRAWPARTDESC tmp;
1786 memcpy(&tmp, &RawDescriptor.pPartDescs[i], sizeof(tmp));
1787 memcpy(&RawDescriptor.pPartDescs[i], &RawDescriptor.pPartDescs[uMinIdx], sizeof(tmp));
1788 memcpy(&RawDescriptor.pPartDescs[uMinIdx], &tmp, sizeof(tmp));
1789 }
1790 }
1791
1792 /* Have a second go at MBR/EPT, GPT area clipping. Now that the data areas
1793 * are sorted this is much easier to get 100% right. */
1794 //for (unsigned i = 0; i < RawDescriptor.cPartDescs-1; i++)
1795 for (unsigned i = 0; i < RawDescriptor.cPartDescs; i++)
1796 {
1797 if (RawDescriptor.pPartDescs[i].pvPartitionData)
1798 {
1799 RawDescriptor.pPartDescs[i].cbData = RT_MIN( RawDescriptor.pPartDescs[i+1].offStartInVDisk
1800 - RawDescriptor.pPartDescs[i].offStartInVDisk,
1801 RawDescriptor.pPartDescs[i].cbData);
1802 if (!RawDescriptor.pPartDescs[i].cbData)
1803 {
1804 if (RawDescriptor.enmPartitioningType == VDISKPARTTYPE_MBR)
1805 {
1806 RTMsgError(Internal::tr("MBR/EPT overlaps with data area"));
1807 vrc = VERR_INVALID_PARAMETER;
1808 goto out;
1809 }
1810 if (RawDescriptor.cPartDescs != i+1)
1811 {
1812 RTMsgError(Internal::tr("GPT overlaps with data area"));
1813 vrc = VERR_INVALID_PARAMETER;
1814 goto out;
1815 }
1816 }
1817 }
1818 }
1819 }
1820
1821 RTFileClose(hRawFile);
1822
1823#ifdef DEBUG_klaus
1824 if (!(RawDescriptor.uFlags & VDISKRAW_DISK))
1825 {
1826 RTPrintf("# start length startoffset partdataptr device\n");
1827 for (unsigned i = 0; i < RawDescriptor.cPartDescs; i++)
1828 {
1829 RTPrintf("%2u %14RU64 %14RU64 %14RU64 %#18p %s\n", i,
1830 RawDescriptor.pPartDescs[i].offStartInVDisk,
1831 RawDescriptor.pPartDescs[i].cbData,
1832 RawDescriptor.pPartDescs[i].offStartInDevice,
1833 RawDescriptor.pPartDescs[i].pvPartitionData,
1834 RawDescriptor.pPartDescs[i].pszRawDevice);
1835 }
1836 }
1837#endif
1838
1839 VDINTERFACEERROR vdInterfaceError;
1840 vdInterfaceError.pfnError = handleVDError;
1841 vdInterfaceError.pfnMessage = handleVDMessage;
1842
1843 rc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1844 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1845 AssertRC(vrc);
1846
1847 vrc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk); /* Raw VMDK's are harddisk only. */
1848 if (RT_FAILURE(vrc))
1849 {
1850 RTMsgError(Internal::tr("Cannot create the virtual disk container: %Rrc"), vrc);
1851 goto out;
1852 }
1853
1854 Assert(RT_MIN(cbSize / 512 / 16 / 63, 16383) -
1855 (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383) == 0);
1856 VDGEOMETRY PCHS, LCHS;
1857 PCHS.cCylinders = (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383);
1858 PCHS.cHeads = 16;
1859 PCHS.cSectors = 63;
1860 LCHS.cCylinders = 0;
1861 LCHS.cHeads = 0;
1862 LCHS.cSectors = 0;
1863 vrc = VDCreateBase(pDisk, "VMDK", filename.c_str(), cbSize,
1864 VD_IMAGE_FLAGS_FIXED | VD_VMDK_IMAGE_FLAGS_RAWDISK,
1865 (char *)&RawDescriptor, &PCHS, &LCHS, NULL,
1866 VD_OPEN_FLAGS_NORMAL, NULL, NULL);
1867 if (RT_FAILURE(vrc))
1868 {
1869 RTMsgError(Internal::tr("Cannot create the raw disk VMDK: %Rrc"), vrc);
1870 goto out;
1871 }
1872 RTPrintf(Internal::tr("RAW host disk access VMDK file %s created successfully.\n"), filename.c_str());
1873
1874 VDCloseAll(pDisk);
1875
1876 /* Clean up allocated memory etc. */
1877 if (pszPartitions)
1878 {
1879 for (unsigned i = 0; i < RawDescriptor.cPartDescs; i++)
1880 {
1881 /* Free memory allocated for relative device name. */
1882 if (fRelative && RawDescriptor.pPartDescs[i].pszRawDevice)
1883 RTStrFree((char *)(void *)RawDescriptor.pPartDescs[i].pszRawDevice);
1884 if (RawDescriptor.pPartDescs[i].pvPartitionData)
1885 RTMemFree((void *)RawDescriptor.pPartDescs[i].pvPartitionData);
1886 }
1887 if (RawDescriptor.pPartDescs)
1888 RTMemFree(RawDescriptor.pPartDescs);
1889 }
1890
1891 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1892
1893out:
1894 RTMsgError(Internal::tr("The raw disk vmdk file was not created"));
1895 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1896}
1897
1898static RTEXITCODE CmdRenameVMDK(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1899{
1900 RT_NOREF(aVirtualBox, aSession);
1901 Utf8Str src;
1902 Utf8Str dst;
1903 /* Parse the arguments. */
1904 for (int i = 0; i < argc; i++)
1905 {
1906 if (strcmp(argv[i], "-from") == 0)
1907 {
1908 if (argc <= i + 1)
1909 {
1910 return errorArgument(Internal::tr("Missing argument to '%s'"), argv[i]);
1911 }
1912 i++;
1913 src = argv[i];
1914 }
1915 else if (strcmp(argv[i], "-to") == 0)
1916 {
1917 if (argc <= i + 1)
1918 {
1919 return errorArgument(Internal::tr("Missing argument to '%s'"), argv[i]);
1920 }
1921 i++;
1922 dst = argv[i];
1923 }
1924 else
1925 {
1926 return errorSyntax(USAGE_I_RENAMEVMDK, Internal::tr("Invalid parameter '%s'"), argv[i]);
1927 }
1928 }
1929
1930 if (src.isEmpty())
1931 return errorSyntax(USAGE_I_RENAMEVMDK, Internal::tr("Mandatory parameter -from missing"));
1932 if (dst.isEmpty())
1933 return errorSyntax(USAGE_I_RENAMEVMDK, Internal::tr("Mandatory parameter -to missing"));
1934
1935 PVDISK pDisk = NULL;
1936
1937 PVDINTERFACE pVDIfs = NULL;
1938 VDINTERFACEERROR vdInterfaceError;
1939 vdInterfaceError.pfnError = handleVDError;
1940 vdInterfaceError.pfnMessage = handleVDMessage;
1941
1942 int vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1943 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1944 AssertRC(vrc);
1945
1946 vrc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk);
1947 if (RT_FAILURE(vrc))
1948 return RTMsgErrorExit(RTEXITCODE_FAILURE, Internal::tr("Cannot create the virtual disk container: %Rrc"), vrc);
1949
1950 vrc = VDOpen(pDisk, "VMDK", src.c_str(), VD_OPEN_FLAGS_NORMAL, NULL);
1951 if (RT_SUCCESS(vrc))
1952 {
1953 vrc = VDCopy(pDisk, 0, pDisk, "VMDK", dst.c_str(), true, 0,
1954 VD_IMAGE_FLAGS_NONE, NULL, VD_OPEN_FLAGS_NORMAL,
1955 NULL, NULL, NULL);
1956 if (RT_FAILURE(vrc))
1957 RTMsgError(Internal::tr("Cannot rename the image: %Rrc"), vrc);
1958 }
1959 else
1960 RTMsgError(Internal::tr("Cannot create the source image: %Rrc"), vrc);
1961 VDCloseAll(pDisk);
1962 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1963}
1964
1965static RTEXITCODE CmdConvertToRaw(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1966{
1967 RT_NOREF(aVirtualBox, aSession);
1968 Utf8Str srcformat;
1969 Utf8Str src;
1970 Utf8Str dst;
1971 bool fWriteToStdOut = false;
1972
1973 /* Parse the arguments. */
1974 for (int i = 0; i < argc; i++)
1975 {
1976 if (strcmp(argv[i], "-format") == 0)
1977 {
1978 if (argc <= i + 1)
1979 {
1980 return errorArgument(Internal::tr("Missing argument to '%s'"), argv[i]);
1981 }
1982 i++;
1983 srcformat = argv[i];
1984 }
1985 else if (src.isEmpty())
1986 {
1987 src = argv[i];
1988 }
1989 else if (dst.isEmpty())
1990 {
1991 dst = argv[i];
1992#ifdef ENABLE_CONVERT_RAW_TO_STDOUT
1993 if (!strcmp(argv[i], "stdout"))
1994 fWriteToStdOut = true;
1995#endif /* ENABLE_CONVERT_RAW_TO_STDOUT */
1996 }
1997 else
1998 {
1999 return errorSyntax(USAGE_I_CONVERTTORAW, Internal::tr("Invalid parameter '%s'"), argv[i]);
2000 }
2001 }
2002
2003 if (src.isEmpty())
2004 return errorSyntax(USAGE_I_CONVERTTORAW, Internal::tr("Mandatory filename parameter missing"));
2005 if (dst.isEmpty())
2006 return errorSyntax(USAGE_I_CONVERTTORAW, Internal::tr("Mandatory outputfile parameter missing"));
2007
2008 PVDISK pDisk = NULL;
2009
2010 PVDINTERFACE pVDIfs = NULL;
2011 VDINTERFACEERROR vdInterfaceError;
2012 vdInterfaceError.pfnError = handleVDError;
2013 vdInterfaceError.pfnMessage = handleVDMessage;
2014
2015 int vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
2016 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
2017 AssertRC(vrc);
2018
2019 /** @todo Support convert to raw for floppy and DVD images too. */
2020 vrc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk);
2021 if (RT_FAILURE(vrc))
2022 return RTMsgErrorExit(RTEXITCODE_FAILURE, Internal::tr("Cannot create the virtual disk container: %Rrc"), vrc);
2023
2024 /* Open raw output file. */
2025 RTFILE outFile;
2026 vrc = VINF_SUCCESS;
2027 if (fWriteToStdOut)
2028 vrc = RTFileFromNative(&outFile, 1);
2029 else
2030 vrc = RTFileOpen(&outFile, dst.c_str(), RTFILE_O_WRITE | RTFILE_O_CREATE | RTFILE_O_DENY_ALL);
2031 if (RT_FAILURE(vrc))
2032 {
2033 VDCloseAll(pDisk);
2034 return RTMsgErrorExit(RTEXITCODE_FAILURE, Internal::tr("Cannot create destination file \"%s\": %Rrc"),
2035 dst.c_str(), vrc);
2036 }
2037
2038 if (srcformat.isEmpty())
2039 {
2040 char *pszFormat = NULL;
2041 VDTYPE enmType = VDTYPE_INVALID;
2042 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
2043 src.c_str(), VDTYPE_INVALID, &pszFormat, &enmType);
2044 if (RT_FAILURE(vrc) || enmType != VDTYPE_HDD)
2045 {
2046 VDCloseAll(pDisk);
2047 if (!fWriteToStdOut)
2048 {
2049 RTFileClose(outFile);
2050 RTFileDelete(dst.c_str());
2051 }
2052 if (RT_FAILURE(vrc))
2053 RTMsgError(Internal::tr("No file format specified and autodetect failed - please specify format: %Rrc"),
2054 vrc);
2055 else
2056 RTMsgError(Internal::tr("Only converting harddisk images is supported"));
2057 return RTEXITCODE_FAILURE;
2058 }
2059 srcformat = pszFormat;
2060 RTStrFree(pszFormat);
2061 }
2062 vrc = VDOpen(pDisk, srcformat.c_str(), src.c_str(), VD_OPEN_FLAGS_READONLY, NULL);
2063 if (RT_FAILURE(vrc))
2064 {
2065 VDCloseAll(pDisk);
2066 if (!fWriteToStdOut)
2067 {
2068 RTFileClose(outFile);
2069 RTFileDelete(dst.c_str());
2070 }
2071 return RTMsgErrorExit(RTEXITCODE_FAILURE, Internal::tr("Cannot open the source image: %Rrc"), vrc);
2072 }
2073
2074 uint64_t cbSize = VDGetSize(pDisk, VD_LAST_IMAGE);
2075 uint64_t offFile = 0;
2076#define RAW_BUFFER_SIZE _128K
2077 size_t cbBuf = RAW_BUFFER_SIZE;
2078 void *pvBuf = RTMemAlloc(cbBuf);
2079 if (pvBuf)
2080 {
2081 RTStrmPrintf(g_pStdErr, Internal::tr("Converting image \"%s\" with size %RU64 bytes (%RU64MB) to raw...\n", "", cbSize),
2082 src.c_str(), cbSize, (cbSize + _1M - 1) / _1M);
2083 while (offFile < cbSize)
2084 {
2085 size_t cb = (size_t)RT_MIN(cbSize - offFile, cbBuf);
2086 vrc = VDRead(pDisk, offFile, pvBuf, cb);
2087 if (RT_FAILURE(vrc))
2088 break;
2089 vrc = RTFileWrite(outFile, pvBuf, cb, NULL);
2090 if (RT_FAILURE(vrc))
2091 break;
2092 offFile += cb;
2093 }
2094 RTMemFree(pvBuf);
2095 if (RT_FAILURE(vrc))
2096 {
2097 VDCloseAll(pDisk);
2098 if (!fWriteToStdOut)
2099 {
2100 RTFileClose(outFile);
2101 RTFileDelete(dst.c_str());
2102 }
2103 return RTMsgErrorExit(RTEXITCODE_FAILURE, Internal::tr("Cannot copy image data: %Rrc"), vrc);
2104 }
2105 }
2106 else
2107 {
2108 vrc = VERR_NO_MEMORY;
2109 VDCloseAll(pDisk);
2110 if (!fWriteToStdOut)
2111 {
2112 RTFileClose(outFile);
2113 RTFileDelete(dst.c_str());
2114 }
2115 return RTMsgErrorExit(RTEXITCODE_FAILURE, Internal::tr("Out of memory allocating read buffer"));
2116 }
2117
2118 if (!fWriteToStdOut)
2119 RTFileClose(outFile);
2120 VDCloseAll(pDisk);
2121 return RTEXITCODE_SUCCESS;
2122}
2123
2124static RTEXITCODE CmdConvertHardDisk(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2125{
2126 RT_NOREF(aVirtualBox, aSession);
2127 Utf8Str srcformat;
2128 Utf8Str dstformat;
2129 Utf8Str src;
2130 Utf8Str dst;
2131 int vrc;
2132 PVDISK pSrcDisk = NULL;
2133 PVDISK pDstDisk = NULL;
2134 VDTYPE enmSrcType = VDTYPE_INVALID;
2135
2136 /* Parse the arguments. */
2137 for (int i = 0; i < argc; i++)
2138 {
2139 if (strcmp(argv[i], "-srcformat") == 0)
2140 {
2141 if (argc <= i + 1)
2142 {
2143 return errorArgument(Internal::tr("Missing argument to '%s'"), argv[i]);
2144 }
2145 i++;
2146 srcformat = argv[i];
2147 }
2148 else if (strcmp(argv[i], "-dstformat") == 0)
2149 {
2150 if (argc <= i + 1)
2151 {
2152 return errorArgument(Internal::tr("Missing argument to '%s'"), argv[i]);
2153 }
2154 i++;
2155 dstformat = argv[i];
2156 }
2157 else if (src.isEmpty())
2158 {
2159 src = argv[i];
2160 }
2161 else if (dst.isEmpty())
2162 {
2163 dst = argv[i];
2164 }
2165 else
2166 {
2167 return errorSyntax(USAGE_I_CONVERTHD, Internal::tr("Invalid parameter '%s'"), argv[i]);
2168 }
2169 }
2170
2171 if (src.isEmpty())
2172 return errorSyntax(USAGE_I_CONVERTHD, Internal::tr("Mandatory input image parameter missing"));
2173 if (dst.isEmpty())
2174 return errorSyntax(USAGE_I_CONVERTHD, Internal::tr("Mandatory output image parameter missing"));
2175
2176
2177 PVDINTERFACE pVDIfs = NULL;
2178 VDINTERFACEERROR vdInterfaceError;
2179 vdInterfaceError.pfnError = handleVDError;
2180 vdInterfaceError.pfnMessage = handleVDMessage;
2181
2182 vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
2183 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
2184 AssertRC(vrc);
2185
2186 do
2187 {
2188 /* Try to determine input image format */
2189 if (srcformat.isEmpty())
2190 {
2191 char *pszFormat = NULL;
2192 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
2193 src.c_str(), VDTYPE_HDD, &pszFormat, &enmSrcType);
2194 if (RT_FAILURE(vrc))
2195 {
2196 RTMsgError(Internal::tr("No file format specified and autodetect failed - please specify format: %Rrc"),
2197 vrc);
2198 break;
2199 }
2200 srcformat = pszFormat;
2201 RTStrFree(pszFormat);
2202 }
2203
2204 vrc = VDCreate(pVDIfs, enmSrcType, &pSrcDisk);
2205 if (RT_FAILURE(vrc))
2206 {
2207 RTMsgError(Internal::tr("Cannot create the source virtual disk container: %Rrc"), vrc);
2208 break;
2209 }
2210
2211 /* Open the input image */
2212 vrc = VDOpen(pSrcDisk, srcformat.c_str(), src.c_str(), VD_OPEN_FLAGS_READONLY, NULL);
2213 if (RT_FAILURE(vrc))
2214 {
2215 RTMsgError(Internal::tr("Cannot open the source image: %Rrc"), vrc);
2216 break;
2217 }
2218
2219 /* Output format defaults to VDI */
2220 if (dstformat.isEmpty())
2221 dstformat = "VDI";
2222
2223 vrc = VDCreate(pVDIfs, enmSrcType, &pDstDisk);
2224 if (RT_FAILURE(vrc))
2225 {
2226 RTMsgError(Internal::tr("Cannot create the destination virtual disk container: %Rrc"), vrc);
2227 break;
2228 }
2229
2230 uint64_t cbSize = VDGetSize(pSrcDisk, VD_LAST_IMAGE);
2231 RTStrmPrintf(g_pStdErr, Internal::tr("Converting image \"%s\" with size %RU64 bytes (%RU64MB)...\n", "", cbSize),
2232 src.c_str(), cbSize, (cbSize + _1M - 1) / _1M);
2233
2234 /* Create the output image */
2235 vrc = VDCopy(pSrcDisk, VD_LAST_IMAGE, pDstDisk, dstformat.c_str(),
2236 dst.c_str(), false, 0, VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED,
2237 NULL, VD_OPEN_FLAGS_NORMAL, NULL, NULL, NULL);
2238 if (RT_FAILURE(vrc))
2239 {
2240 RTMsgError(Internal::tr("Cannot copy the image: %Rrc"), vrc);
2241 break;
2242 }
2243 }
2244 while (0);
2245 if (pDstDisk)
2246 VDCloseAll(pDstDisk);
2247 if (pSrcDisk)
2248 VDCloseAll(pSrcDisk);
2249
2250 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2251}
2252
2253/**
2254 * Tries to repair a corrupted hard disk image.
2255 *
2256 * @returns VBox status code
2257 */
2258static RTEXITCODE CmdRepairHardDisk(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2259{
2260 RT_NOREF(aVirtualBox, aSession);
2261 Utf8Str image;
2262 Utf8Str format;
2263 int vrc;
2264 bool fDryRun = false;
2265
2266 /* Parse the arguments. */
2267 for (int i = 0; i < argc; i++)
2268 {
2269 if (strcmp(argv[i], "-dry-run") == 0)
2270 {
2271 fDryRun = true;
2272 }
2273 else if (strcmp(argv[i], "-format") == 0)
2274 {
2275 if (argc <= i + 1)
2276 {
2277 return errorArgument(Internal::tr("Missing argument to '%s'"), argv[i]);
2278 }
2279 i++;
2280 format = argv[i];
2281 }
2282 else if (image.isEmpty())
2283 {
2284 image = argv[i];
2285 }
2286 else
2287 {
2288 return errorSyntax(USAGE_I_REPAIRHD, Internal::tr("Invalid parameter '%s'"), argv[i]);
2289 }
2290 }
2291
2292 if (image.isEmpty())
2293 return errorSyntax(USAGE_I_REPAIRHD, Internal::tr("Mandatory input image parameter missing"));
2294
2295 PVDINTERFACE pVDIfs = NULL;
2296 VDINTERFACEERROR vdInterfaceError;
2297 vdInterfaceError.pfnError = handleVDError;
2298 vdInterfaceError.pfnMessage = handleVDMessage;
2299
2300 vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
2301 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
2302 AssertRC(vrc);
2303
2304 do
2305 {
2306 /* Try to determine input image format */
2307 if (format.isEmpty())
2308 {
2309 char *pszFormat = NULL;
2310 VDTYPE enmSrcType = VDTYPE_INVALID;
2311
2312 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
2313 image.c_str(), VDTYPE_HDD, &pszFormat, &enmSrcType);
2314 if (RT_FAILURE(vrc) && (vrc != VERR_VD_IMAGE_CORRUPTED))
2315 {
2316 RTMsgError(Internal::tr("No file format specified and autodetect failed - please specify format: %Rrc"),
2317 vrc);
2318 break;
2319 }
2320 format = pszFormat;
2321 RTStrFree(pszFormat);
2322 }
2323
2324 uint32_t fFlags = 0;
2325 if (fDryRun)
2326 fFlags |= VD_REPAIR_DRY_RUN;
2327
2328 vrc = VDRepair(pVDIfs, NULL, image.c_str(), format.c_str(), fFlags);
2329 }
2330 while (0);
2331
2332 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2333}
2334
2335/**
2336 * Unloads the necessary driver.
2337 *
2338 * @returns VBox status code
2339 */
2340static RTEXITCODE CmdModUninstall(void)
2341{
2342 int rc = SUPR3Uninstall();
2343 if (RT_SUCCESS(rc) || rc == VERR_NOT_IMPLEMENTED)
2344 return RTEXITCODE_SUCCESS;
2345 return RTEXITCODE_FAILURE;
2346}
2347
2348/**
2349 * Loads the necessary driver.
2350 *
2351 * @returns VBox status code
2352 */
2353static RTEXITCODE CmdModInstall(void)
2354{
2355 int rc = SUPR3Install();
2356 if (RT_SUCCESS(rc) || rc == VERR_NOT_IMPLEMENTED)
2357 return RTEXITCODE_SUCCESS;
2358 return RTEXITCODE_FAILURE;
2359}
2360
2361static RTEXITCODE CmdDebugLog(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2362{
2363 /*
2364 * The first parameter is the name or UUID of a VM with a direct session
2365 * that we wish to open.
2366 */
2367 if (argc < 1)
2368 return errorSyntax(USAGE_I_DEBUGLOG, Internal::tr("Missing VM name/UUID"));
2369
2370 ComPtr<IMachine> ptrMachine;
2371 HRESULT rc;
2372 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
2373 ptrMachine.asOutParam()), RTEXITCODE_FAILURE);
2374
2375 CHECK_ERROR_RET(ptrMachine, LockMachine(aSession, LockType_Shared), RTEXITCODE_FAILURE);
2376
2377 /*
2378 * Get the debugger interface.
2379 */
2380 ComPtr<IConsole> ptrConsole;
2381 CHECK_ERROR_RET(aSession, COMGETTER(Console)(ptrConsole.asOutParam()), RTEXITCODE_FAILURE);
2382
2383 ComPtr<IMachineDebugger> ptrDebugger;
2384 CHECK_ERROR_RET(ptrConsole, COMGETTER(Debugger)(ptrDebugger.asOutParam()), RTEXITCODE_FAILURE);
2385
2386 /*
2387 * Parse the command.
2388 */
2389 bool fEnablePresent = false;
2390 bool fEnable = false;
2391 bool fFlagsPresent = false;
2392 RTCString strFlags;
2393 bool fGroupsPresent = false;
2394 RTCString strGroups;
2395 bool fDestsPresent = false;
2396 RTCString strDests;
2397
2398 static const RTGETOPTDEF s_aOptions[] =
2399 {
2400 { "--disable", 'E', RTGETOPT_REQ_NOTHING },
2401 { "--enable", 'e', RTGETOPT_REQ_NOTHING },
2402 { "--flags", 'f', RTGETOPT_REQ_STRING },
2403 { "--groups", 'g', RTGETOPT_REQ_STRING },
2404 { "--destinations", 'd', RTGETOPT_REQ_STRING }
2405 };
2406
2407 int ch;
2408 RTGETOPTUNION ValueUnion;
2409 RTGETOPTSTATE GetState;
2410 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
2411 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
2412 {
2413 switch (ch)
2414 {
2415 case 'e':
2416 fEnablePresent = true;
2417 fEnable = true;
2418 break;
2419
2420 case 'E':
2421 fEnablePresent = true;
2422 fEnable = false;
2423 break;
2424
2425 case 'f':
2426 fFlagsPresent = true;
2427 if (*ValueUnion.psz)
2428 {
2429 if (strFlags.isNotEmpty())
2430 strFlags.append(' ');
2431 strFlags.append(ValueUnion.psz);
2432 }
2433 break;
2434
2435 case 'g':
2436 fGroupsPresent = true;
2437 if (*ValueUnion.psz)
2438 {
2439 if (strGroups.isNotEmpty())
2440 strGroups.append(' ');
2441 strGroups.append(ValueUnion.psz);
2442 }
2443 break;
2444
2445 case 'd':
2446 fDestsPresent = true;
2447 if (*ValueUnion.psz)
2448 {
2449 if (strDests.isNotEmpty())
2450 strDests.append(' ');
2451 strDests.append(ValueUnion.psz);
2452 }
2453 break;
2454
2455 default:
2456 return errorGetOpt(USAGE_I_DEBUGLOG, ch, &ValueUnion);
2457 }
2458 }
2459
2460 /*
2461 * Do the job.
2462 */
2463 if (fEnablePresent && !fEnable)
2464 CHECK_ERROR_RET(ptrDebugger, COMSETTER(LogEnabled)(FALSE), RTEXITCODE_FAILURE);
2465
2466 /** @todo flags, groups destination. */
2467 if (fFlagsPresent || fGroupsPresent || fDestsPresent)
2468 RTMsgWarning(Internal::tr("One or more of the requested features are not implemented! Feel free to do this."));
2469
2470 if (fEnablePresent && fEnable)
2471 CHECK_ERROR_RET(ptrDebugger, COMSETTER(LogEnabled)(TRUE), RTEXITCODE_FAILURE);
2472 return RTEXITCODE_SUCCESS;
2473}
2474
2475/**
2476 * Generate a SHA-256 password hash
2477 */
2478static RTEXITCODE CmdGeneratePasswordHash(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2479{
2480 RT_NOREF(aVirtualBox, aSession);
2481
2482 /* one parameter, the password to hash */
2483 if (argc != 1)
2484 return errorSyntax(USAGE_I_PASSWORDHASH, Internal::tr("password to hash required"));
2485
2486 uint8_t abDigest[RTSHA256_HASH_SIZE];
2487 RTSha256(argv[0], strlen(argv[0]), abDigest);
2488 char pszDigest[RTSHA256_DIGEST_LEN + 1];
2489 RTSha256ToString(abDigest, pszDigest, sizeof(pszDigest));
2490 RTPrintf(Internal::tr("Password hash: %s\n"), pszDigest);
2491
2492 return RTEXITCODE_SUCCESS;
2493}
2494
2495/**
2496 * Print internal guest statistics or
2497 * set internal guest statistics update interval if specified
2498 */
2499static RTEXITCODE CmdGuestStats(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2500{
2501 /* one parameter, guest name */
2502 if (argc < 1)
2503 return errorSyntax(USAGE_I_GUESTSTATS, Internal::tr("Missing VM name/UUID"));
2504
2505 /*
2506 * Parse the command.
2507 */
2508 ULONG aUpdateInterval = 0;
2509
2510 static const RTGETOPTDEF s_aOptions[] =
2511 {
2512 { "--interval", 'i', RTGETOPT_REQ_UINT32 }
2513 };
2514
2515 int ch;
2516 RTGETOPTUNION ValueUnion;
2517 RTGETOPTSTATE GetState;
2518 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
2519 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
2520 {
2521 switch (ch)
2522 {
2523 case 'i':
2524 aUpdateInterval = ValueUnion.u32;
2525 break;
2526
2527 default:
2528 return errorGetOpt(USAGE_I_GUESTSTATS, ch, &ValueUnion);
2529 }
2530 }
2531
2532 if (argc > 1 && aUpdateInterval == 0)
2533 return errorSyntax(USAGE_I_GUESTSTATS, Internal::tr("Invalid update interval specified"));
2534
2535 RTPrintf(Internal::tr("argc=%d interval=%u\n"), argc, aUpdateInterval);
2536
2537 ComPtr<IMachine> ptrMachine;
2538 HRESULT rc;
2539 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
2540 ptrMachine.asOutParam()), RTEXITCODE_FAILURE);
2541
2542 CHECK_ERROR_RET(ptrMachine, LockMachine(aSession, LockType_Shared), RTEXITCODE_FAILURE);
2543
2544 /*
2545 * Get the guest interface.
2546 */
2547 ComPtr<IConsole> ptrConsole;
2548 CHECK_ERROR_RET(aSession, COMGETTER(Console)(ptrConsole.asOutParam()), RTEXITCODE_FAILURE);
2549
2550 ComPtr<IGuest> ptrGuest;
2551 CHECK_ERROR_RET(ptrConsole, COMGETTER(Guest)(ptrGuest.asOutParam()), RTEXITCODE_FAILURE);
2552
2553 if (aUpdateInterval)
2554 CHECK_ERROR_RET(ptrGuest, COMSETTER(StatisticsUpdateInterval)(aUpdateInterval), RTEXITCODE_FAILURE);
2555 else
2556 {
2557 ULONG mCpuUser, mCpuKernel, mCpuIdle;
2558 ULONG mMemTotal, mMemFree, mMemBalloon, mMemShared, mMemCache, mPageTotal;
2559 ULONG ulMemAllocTotal, ulMemFreeTotal, ulMemBalloonTotal, ulMemSharedTotal;
2560
2561 CHECK_ERROR_RET(ptrGuest, InternalGetStatistics(&mCpuUser, &mCpuKernel, &mCpuIdle,
2562 &mMemTotal, &mMemFree, &mMemBalloon, &mMemShared, &mMemCache,
2563 &mPageTotal, &ulMemAllocTotal, &ulMemFreeTotal,
2564 &ulMemBalloonTotal, &ulMemSharedTotal),
2565 RTEXITCODE_FAILURE);
2566 RTPrintf("mCpuUser=%u mCpuKernel=%u mCpuIdle=%u\n"
2567 "mMemTotal=%u mMemFree=%u mMemBalloon=%u mMemShared=%u mMemCache=%u\n"
2568 "mPageTotal=%u ulMemAllocTotal=%u ulMemFreeTotal=%u ulMemBalloonTotal=%u ulMemSharedTotal=%u\n",
2569 mCpuUser, mCpuKernel, mCpuIdle,
2570 mMemTotal, mMemFree, mMemBalloon, mMemShared, mMemCache,
2571 mPageTotal, ulMemAllocTotal, ulMemFreeTotal, ulMemBalloonTotal, ulMemSharedTotal);
2572
2573 }
2574
2575 return RTEXITCODE_SUCCESS;
2576}
2577
2578
2579/**
2580 * Wrapper for handling internal commands
2581 */
2582RTEXITCODE handleInternalCommands(HandlerArg *a)
2583{
2584 g_fInternalMode = true;
2585
2586 /* at least a command is required */
2587 if (a->argc < 1)
2588 return errorSyntax(USAGE_S_ALL, Internal::tr("Command missing"));
2589
2590 /*
2591 * The 'string switch' on command name.
2592 */
2593 const char *pszCmd = a->argv[0];
2594 if (!strcmp(pszCmd, "loadmap"))
2595 return CmdLoadMap(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2596 if (!strcmp(pszCmd, "loadsyms"))
2597 return CmdLoadSyms(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2598 //if (!strcmp(pszCmd, "unloadsyms"))
2599 // return CmdUnloadSyms(argc - 1, &a->argv[1]);
2600 if (!strcmp(pszCmd, "sethduuid") || !strcmp(pszCmd, "sethdparentuuid"))
2601 return CmdSetHDUUID(a->argc, &a->argv[0], a->virtualBox, a->session);
2602 if (!strcmp(pszCmd, "dumphdinfo"))
2603 return CmdDumpHDInfo(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2604 if (!strcmp(pszCmd, "listpartitions"))
2605 return CmdListPartitions(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2606 if (!strcmp(pszCmd, "createrawvmdk"))
2607 return CmdCreateRawVMDK(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2608 if (!strcmp(pszCmd, "renamevmdk"))
2609 return CmdRenameVMDK(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2610 if (!strcmp(pszCmd, "converttoraw"))
2611 return CmdConvertToRaw(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2612 if (!strcmp(pszCmd, "converthd"))
2613 return CmdConvertHardDisk(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2614 if (!strcmp(pszCmd, "modinstall"))
2615 return CmdModInstall();
2616 if (!strcmp(pszCmd, "moduninstall"))
2617 return CmdModUninstall();
2618 if (!strcmp(pszCmd, "debuglog"))
2619 return CmdDebugLog(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2620 if (!strcmp(pszCmd, "passwordhash"))
2621 return CmdGeneratePasswordHash(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2622 if (!strcmp(pszCmd, "gueststats"))
2623 return CmdGuestStats(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2624 if (!strcmp(pszCmd, "repairhd"))
2625 return CmdRepairHardDisk(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2626
2627 /* default: */
2628 return errorSyntax(USAGE_S_ALL, Internal::tr("Invalid command '%s'"), a->argv[0]);
2629}
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