VirtualBox

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

Last change on this file since 56103 was 55906, checked in by vboxsync, 10 years ago

FE/VBoxManage: Fix reading the partition table on Windows, ReadFile expects sector aligned reads for physical drives

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