VirtualBox

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

Last change on this file since 46524 was 45596, checked in by vboxsync, 12 years ago

VBoxManage: Use VD_OPEN_FLAGS_INFO when opening the image to change the UUID, opening diff images causes an error because the base image is missing in the chain

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 86.6 KB
Line 
1/* $Id: VBoxInternalManage.cpp 45596 2013-04-17 18:59:52Z 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 PARTITIONING_TYPE 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 PARTITIONING_TYPE 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
764 if (RT_FAILURE(rc))
765 return rc;
766
767 if (aBuffer[450] == 0xEE)/* check the sign of the GPT disk*/
768 {
769 partitioningType = GPT;
770 pPart->uPartitioningType = GPT;//partitioningType;
771
772 if (aBuffer[510] != 0x55 || aBuffer[511] != 0xaa)
773 return VERR_INVALID_PARAMETER;
774
775 rc = RTFileReadAt(File, sector_size, &partitionTableHeader, sector_size, NULL);
776 if (RT_SUCCESS(rc))
777 {
778 const char* l_ppth = (char*)partitionTableHeader;
779 rc = strncmp(l_ppth, "EFI PART", 8);
780 if (RT_FAILURE(rc))
781 return VERR_INVALID_PARAMETER;
782
783 /** @todo check GPT Version */
784
785 uint64_t firstUsableLBA = RT_MAKE_U64_FROM_U8(partitionTableHeader[40],
786 partitionTableHeader[41],
787 partitionTableHeader[42],
788 partitionTableHeader[43],
789 partitionTableHeader[44],
790 partitionTableHeader[45],
791 partitionTableHeader[46],
792 partitionTableHeader[47]
793 );
794 lastUsableLBA = RT_MAKE_U64_FROM_U8( partitionTableHeader[48],
795 partitionTableHeader[49],
796 partitionTableHeader[50],
797 partitionTableHeader[51],
798 partitionTableHeader[52],
799 partitionTableHeader[53],
800 partitionTableHeader[54],
801 partitionTableHeader[55]
802 );
803 uint32_t partitionsNumber = RT_MAKE_U32_FROM_U8( partitionTableHeader[80],
804 partitionTableHeader[81],
805 partitionTableHeader[82],
806 partitionTableHeader[83]
807 );
808 uint32_t partitionEntrySize = RT_MAKE_U32_FROM_U8( partitionTableHeader[84],
809 partitionTableHeader[85],
810 partitionTableHeader[86],
811 partitionTableHeader[87]
812 );
813
814 uint32_t currentEntry = 0;
815 while(currentEntry<partitionsNumber)
816 {
817 uint8_t partitionEntry[128];
818
819 /*partition entries begin from LBA2*/
820 rc = RTFileReadAt(File, 1024 + currentEntry*partitionEntrySize, &partitionEntry, partitionEntrySize, NULL);
821
822 uint64_t start = RT_MAKE_U64_FROM_U8( partitionEntry[32],
823 partitionEntry[33],
824 partitionEntry[34],
825 partitionEntry[35],
826 partitionEntry[36],
827 partitionEntry[37],
828 partitionEntry[38],
829 partitionEntry[39]
830 );
831 uint64_t end = RT_MAKE_U64_FROM_U8( partitionEntry[40],
832 partitionEntry[41],
833 partitionEntry[42],
834 partitionEntry[43],
835 partitionEntry[44],
836 partitionEntry[45],
837 partitionEntry[46],
838 partitionEntry[47]
839 );
840
841 PHOSTPARTITION pCP = &pPart->aPartitions[pPart->cPartitions++];
842 pCP->uIndex = currentEntry + 1;
843 pCP->uType = 0;
844 pCP->uStartCylinder = 0;
845 pCP->uStartHead = 0;
846 pCP->uStartSector = 0;
847 pCP->uEndCylinder = 0;
848 pCP->uEndHead = 0;
849 pCP->uEndSector = 0;
850 pCP->uPartDataStart = 0; /* will be filled out later properly. */
851 pCP->cPartDataSectors = 0;
852 if (start==0 || end==0)
853 {
854 pCP->uIndex = 0;
855 --pPart->cPartitions;
856 break;
857 }
858 else
859 {
860 pCP->uStart = start;
861 pCP->uSize = (end +1) - start;/*+1 LBA because the last address is included*/
862 }
863
864 ++currentEntry;
865 }
866 }
867 }
868 else
869 {
870 partitioningType = MBR;
871 pPart->uPartitioningType = MBR;//partitioningType;
872
873 if (aBuffer[510] != 0x55 || aBuffer[511] != 0xaa)
874 return VERR_INVALID_PARAMETER;
875
876 unsigned uExtended = (unsigned)-1;
877
878 for (unsigned i = 0; i < 4; i++)
879 {
880 uint8_t *p = &aBuffer[0x1be + i * 16];
881 if (p[4] == 0)
882 continue;
883 PHOSTPARTITION pCP = &pPart->aPartitions[pPart->cPartitions++];
884 pCP->uIndex = i + 1;
885 pCP->uType = p[4];
886 pCP->uStartCylinder = (uint32_t)p[3] + ((uint32_t)(p[2] & 0xc0) << 2);
887 pCP->uStartHead = p[1];
888 pCP->uStartSector = p[2] & 0x3f;
889 pCP->uEndCylinder = (uint32_t)p[7] + ((uint32_t)(p[6] & 0xc0) << 2);
890 pCP->uEndHead = p[5];
891 pCP->uEndSector = p[6] & 0x3f;
892 pCP->uStart = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
893 pCP->uSize = RT_MAKE_U32_FROM_U8(p[12], p[13], p[14], p[15]);
894 pCP->uPartDataStart = 0; /* will be filled out later properly. */
895 pCP->cPartDataSectors = 0;
896
897 if (PARTTYPE_IS_EXTENDED(p[4]))
898 {
899 if (uExtended == (unsigned)-1)
900 uExtended = (unsigned)(pCP - pPart->aPartitions);
901 else
902 {
903 RTMsgError("More than one extended partition");
904 return VERR_INVALID_PARAMETER;
905 }
906 }
907 }
908
909 if (uExtended != (unsigned)-1)
910 {
911 unsigned uIndex = 5;
912 uint64_t uStart = pPart->aPartitions[uExtended].uStart;
913 uint64_t uOffset = 0;
914 if (!uStart)
915 {
916 RTMsgError("Inconsistency for logical partition start");
917 return VERR_INVALID_PARAMETER;
918 }
919
920 do
921 {
922 rc = RTFileReadAt(File, (uStart + uOffset) * 512, &aBuffer, sizeof(aBuffer), NULL);
923 if (RT_FAILURE(rc))
924 return rc;
925
926 if (aBuffer[510] != 0x55 || aBuffer[511] != 0xaa)
927 {
928 RTMsgError("Logical partition without magic");
929 return VERR_INVALID_PARAMETER;
930 }
931 uint8_t *p = &aBuffer[0x1be];
932
933 if (p[4] == 0)
934 {
935 RTMsgError("Logical partition with type 0 encountered");
936 return VERR_INVALID_PARAMETER;
937 }
938
939 PHOSTPARTITION pCP = &pPart->aPartitions[pPart->cPartitions++];
940 pCP->uIndex = uIndex;
941 pCP->uType = p[4];
942 pCP->uStartCylinder = (uint32_t)p[3] + ((uint32_t)(p[2] & 0xc0) << 2);
943 pCP->uStartHead = p[1];
944 pCP->uStartSector = p[2] & 0x3f;
945 pCP->uEndCylinder = (uint32_t)p[7] + ((uint32_t)(p[6] & 0xc0) << 2);
946 pCP->uEndHead = p[5];
947 pCP->uEndSector = p[6] & 0x3f;
948 uint32_t uStartOffset = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
949 if (!uStartOffset)
950 {
951 RTMsgError("Invalid partition start offset");
952 return VERR_INVALID_PARAMETER;
953 }
954 pCP->uStart = uStart + uOffset + uStartOffset;
955 pCP->uSize = RT_MAKE_U32_FROM_U8(p[12], p[13], p[14], p[15]);
956 /* Fill out partitioning location info for EBR. */
957 pCP->uPartDataStart = uStart + uOffset;
958 pCP->cPartDataSectors = uStartOffset;
959 p += 16;
960 if (p[4] == 0)
961 uExtended = (unsigned)-1;
962 else if (PARTTYPE_IS_EXTENDED(p[4]))
963 {
964 uExtended = uIndex++;
965 uOffset = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
966 }
967 else
968 {
969 RTMsgError("Logical partition chain broken");
970 return VERR_INVALID_PARAMETER;
971 }
972 } while (uExtended != (unsigned)-1);
973 }
974 }
975
976
977 /* Sort partitions in ascending order of start sector, plus a trivial
978 * bit of consistency checking. */
979 for (unsigned i = 0; i < pPart->cPartitions-1; i++)
980 {
981 unsigned uMinIdx = i;
982 uint64_t uMinVal = pPart->aPartitions[i].uStart;
983 for (unsigned j = i + 1; j < pPart->cPartitions; j++)
984 {
985 if (pPart->aPartitions[j].uStart < uMinVal)
986 {
987 uMinIdx = j;
988 uMinVal = pPart->aPartitions[j].uStart;
989 }
990 else if (pPart->aPartitions[j].uStart == uMinVal)
991 {
992 RTMsgError("Two partitions start at the same place");
993 return VERR_INVALID_PARAMETER;
994 }
995 else if (pPart->aPartitions[j].uStart == 0)
996 {
997 RTMsgError("Partition starts at sector 0");
998 return VERR_INVALID_PARAMETER;
999 }
1000 }
1001 if (uMinIdx != i)
1002 {
1003 /* Swap entries at index i and uMinIdx. */
1004 memcpy(&pPart->aPartitions[pPart->cPartitions],
1005 &pPart->aPartitions[i], sizeof(HOSTPARTITION));
1006 memcpy(&pPart->aPartitions[i],
1007 &pPart->aPartitions[uMinIdx], sizeof(HOSTPARTITION));
1008 memcpy(&pPart->aPartitions[uMinIdx],
1009 &pPart->aPartitions[pPart->cPartitions], sizeof(HOSTPARTITION));
1010 }
1011 }
1012
1013 /* Fill out partitioning location info for MBR or GPT. */
1014 pPart->aPartitions[0].uPartDataStart = 0;
1015 pPart->aPartitions[0].cPartDataSectors = pPart->aPartitions[0].uStart;
1016
1017 /* Fill out partitioning location info for backup GPT. */
1018 if (partitioningType == GPT)
1019 {
1020 pPart->aPartitions[pPart->cPartitions-1].uPartDataStart = lastUsableLBA+1;
1021 pPart->aPartitions[pPart->cPartitions-1].cPartDataSectors = 33;
1022
1023 /* Now do a some partition table consistency checking, to reject the most
1024 * obvious garbage which can lead to trouble later. */
1025 uint64_t uPrevEnd = 0;
1026 for (unsigned i = 0; i < pPart->cPartitions; i++)
1027 {
1028 if (pPart->aPartitions[i].cPartDataSectors)
1029 uPrevEnd = pPart->aPartitions[i].uPartDataStart + pPart->aPartitions[i].cPartDataSectors;
1030 if (pPart->aPartitions[i].uStart < uPrevEnd &&
1031 pPart->cPartitions-1 != i)
1032 {
1033 RTMsgError("Overlapping GPT partitions");
1034 return VERR_INVALID_PARAMETER;
1035 }
1036 }
1037 }
1038 else
1039 {
1040 /* Now do a some partition table consistency checking, to reject the most
1041 * obvious garbage which can lead to trouble later. */
1042 uint64_t uPrevEnd = 0;
1043 for (unsigned i = 0; i < pPart->cPartitions; i++)
1044 {
1045 if (pPart->aPartitions[i].cPartDataSectors)
1046 uPrevEnd = pPart->aPartitions[i].uPartDataStart + pPart->aPartitions[i].cPartDataSectors;
1047 if (pPart->aPartitions[i].uStart < uPrevEnd)
1048 {
1049 RTMsgError("Overlapping MBR partitions");
1050 return VERR_INVALID_PARAMETER;
1051 }
1052 if (!PARTTYPE_IS_EXTENDED(pPart->aPartitions[i].uType))
1053 uPrevEnd = pPart->aPartitions[i].uStart + pPart->aPartitions[i].uSize;
1054 }
1055 }
1056
1057 return VINF_SUCCESS;
1058}
1059
1060static int CmdListPartitions(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1061{
1062 Utf8Str rawdisk;
1063
1064 /* let's have a closer look at the arguments */
1065 for (int i = 0; i < argc; i++)
1066 {
1067 if (strcmp(argv[i], "-rawdisk") == 0)
1068 {
1069 if (argc <= i + 1)
1070 {
1071 return errorArgument("Missing argument to '%s'", argv[i]);
1072 }
1073 i++;
1074 rawdisk = argv[i];
1075 }
1076 else
1077 {
1078 return errorSyntax(USAGE_LISTPARTITIONS, "Invalid parameter '%s'", argv[i]);
1079 }
1080 }
1081
1082 if (rawdisk.isEmpty())
1083 return errorSyntax(USAGE_LISTPARTITIONS, "Mandatory parameter -rawdisk missing");
1084
1085 RTFILE hRawFile;
1086 int vrc = RTFileOpen(&hRawFile, rawdisk.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1087 if (RT_FAILURE(vrc))
1088 {
1089 RTMsgError("Cannot open the raw disk: %Rrc", vrc);
1090 return vrc;
1091 }
1092
1093 HOSTPARTITIONS partitions;
1094 vrc = partRead(hRawFile, &partitions);
1095 /* Don't bail out on errors, print the table and return the result code. */
1096
1097 RTPrintf("Number Type StartCHS EndCHS Size (MiB) Start (Sect)\n");
1098 for (unsigned i = 0; i < partitions.cPartitions; i++)
1099 {
1100 /* Don't show the extended partition, otherwise users might think they
1101 * can add it to the list of partitions for raw partition access. */
1102 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1103 continue;
1104
1105 RTPrintf("%-7u %#04x %-4u/%-3u/%-2u %-4u/%-3u/%-2u %10llu %10llu\n",
1106 partitions.aPartitions[i].uIndex,
1107 partitions.aPartitions[i].uType,
1108 partitions.aPartitions[i].uStartCylinder,
1109 partitions.aPartitions[i].uStartHead,
1110 partitions.aPartitions[i].uStartSector,
1111 partitions.aPartitions[i].uEndCylinder,
1112 partitions.aPartitions[i].uEndHead,
1113 partitions.aPartitions[i].uEndSector,
1114 partitions.aPartitions[i].uSize / 2048,
1115 partitions.aPartitions[i].uStart);
1116 }
1117
1118 return vrc;
1119}
1120
1121static PVBOXHDDRAWPARTDESC appendPartDesc(uint32_t *pcPartDescs, PVBOXHDDRAWPARTDESC *ppPartDescs)
1122{
1123 (*pcPartDescs)++;
1124 PVBOXHDDRAWPARTDESC p;
1125 p = (PVBOXHDDRAWPARTDESC)RTMemRealloc(*ppPartDescs,
1126 *pcPartDescs * sizeof(VBOXHDDRAWPARTDESC));
1127 *ppPartDescs = p;
1128 if (p)
1129 {
1130 p = p + *pcPartDescs - 1;
1131 memset(p, '\0', sizeof(VBOXHDDRAWPARTDESC));
1132 }
1133
1134 return p;
1135}
1136
1137static int CmdCreateRawVMDK(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1138{
1139 HRESULT rc = S_OK;
1140 Utf8Str filename;
1141 const char *pszMBRFilename = NULL;
1142 Utf8Str rawdisk;
1143 const char *pszPartitions = NULL;
1144 bool fRelative = false;
1145
1146 uint64_t cbSize = 0;
1147 PVBOXHDD pDisk = NULL;
1148 VBOXHDDRAW RawDescriptor;
1149 PVDINTERFACE pVDIfs = NULL;
1150
1151 /* let's have a closer look at the arguments */
1152 for (int i = 0; i < argc; i++)
1153 {
1154 if (strcmp(argv[i], "-filename") == 0)
1155 {
1156 if (argc <= i + 1)
1157 {
1158 return errorArgument("Missing argument to '%s'", argv[i]);
1159 }
1160 i++;
1161 filename = argv[i];
1162 }
1163 else if (strcmp(argv[i], "-mbr") == 0)
1164 {
1165 if (argc <= i + 1)
1166 {
1167 return errorArgument("Missing argument to '%s'", argv[i]);
1168 }
1169 i++;
1170 pszMBRFilename = argv[i];
1171 }
1172 else if (strcmp(argv[i], "-rawdisk") == 0)
1173 {
1174 if (argc <= i + 1)
1175 {
1176 return errorArgument("Missing argument to '%s'", argv[i]);
1177 }
1178 i++;
1179 rawdisk = argv[i];
1180 }
1181 else if (strcmp(argv[i], "-partitions") == 0)
1182 {
1183 if (argc <= i + 1)
1184 {
1185 return errorArgument("Missing argument to '%s'", argv[i]);
1186 }
1187 i++;
1188 pszPartitions = argv[i];
1189 }
1190#if defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
1191 else if (strcmp(argv[i], "-relative") == 0)
1192 {
1193 fRelative = true;
1194 }
1195#endif /* RT_OS_LINUX || RT_OS_FREEBSD */
1196 else
1197 return errorSyntax(USAGE_CREATERAWVMDK, "Invalid parameter '%s'", argv[i]);
1198 }
1199
1200 if (filename.isEmpty())
1201 return errorSyntax(USAGE_CREATERAWVMDK, "Mandatory parameter -filename missing");
1202 if (rawdisk.isEmpty())
1203 return errorSyntax(USAGE_CREATERAWVMDK, "Mandatory parameter -rawdisk missing");
1204 if (!pszPartitions && pszMBRFilename)
1205 return errorSyntax(USAGE_CREATERAWVMDK, "The parameter -mbr is only valid when the parameter -partitions is also present");
1206
1207#ifdef RT_OS_DARWIN
1208 fRelative = true;
1209#endif /* RT_OS_DARWIN */
1210 RTFILE hRawFile;
1211 int vrc = RTFileOpen(&hRawFile, rawdisk.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1212 if (RT_FAILURE(vrc))
1213 {
1214 RTMsgError("Cannot open the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1215 goto out;
1216 }
1217
1218#ifdef RT_OS_WINDOWS
1219 /* Windows NT has no IOCTL_DISK_GET_LENGTH_INFORMATION ioctl. This was
1220 * added to Windows XP, so we have to use the available info from DriveGeo.
1221 * Note that we cannot simply use IOCTL_DISK_GET_DRIVE_GEOMETRY as it
1222 * yields a slightly different result than IOCTL_DISK_GET_LENGTH_INFO.
1223 * We call IOCTL_DISK_GET_DRIVE_GEOMETRY first as we need to check the media
1224 * type anyway, and if IOCTL_DISK_GET_LENGTH_INFORMATION is supported
1225 * we will later override cbSize.
1226 */
1227 DISK_GEOMETRY DriveGeo;
1228 DWORD cbDriveGeo;
1229 if (DeviceIoControl((HANDLE)RTFileToNative(hRawFile),
1230 IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,
1231 &DriveGeo, sizeof(DriveGeo), &cbDriveGeo, NULL))
1232 {
1233 if ( DriveGeo.MediaType == FixedMedia
1234 || DriveGeo.MediaType == RemovableMedia)
1235 {
1236 cbSize = DriveGeo.Cylinders.QuadPart
1237 * DriveGeo.TracksPerCylinder
1238 * DriveGeo.SectorsPerTrack
1239 * DriveGeo.BytesPerSector;
1240 }
1241 else
1242 {
1243 RTMsgError("File '%s' is no fixed/removable medium device", rawdisk.c_str());
1244 vrc = VERR_INVALID_PARAMETER;
1245 goto out;
1246 }
1247
1248 GET_LENGTH_INFORMATION DiskLenInfo;
1249 DWORD junk;
1250 if (DeviceIoControl((HANDLE)RTFileToNative(hRawFile),
1251 IOCTL_DISK_GET_LENGTH_INFO, NULL, 0,
1252 &DiskLenInfo, sizeof(DiskLenInfo), &junk, (LPOVERLAPPED)NULL))
1253 {
1254 /* IOCTL_DISK_GET_LENGTH_INFO is supported -- override cbSize. */
1255 cbSize = DiskLenInfo.Length.QuadPart;
1256 }
1257 }
1258 else
1259 {
1260 /*
1261 * Could be raw image, remember error code and try to get the size first
1262 * before failing.
1263 */
1264 vrc = RTErrConvertFromWin32(GetLastError());
1265 if (RT_FAILURE(RTFileGetSize(hRawFile, &cbSize)))
1266 {
1267 RTMsgError("Cannot get the geometry of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1268 goto out;
1269 }
1270 else
1271 vrc = VINF_SUCCESS;
1272 }
1273#elif defined(RT_OS_LINUX)
1274 struct stat DevStat;
1275 if(!fstat(RTFileToNative(hRawFile), &DevStat))
1276 {
1277 if (S_ISBLK(DevStat.st_mode))
1278 {
1279#ifdef BLKGETSIZE64
1280 /* BLKGETSIZE64 is broken up to 2.4.17 and in many 2.5.x. In 2.6.0
1281 * it works without problems. */
1282 struct utsname utsname;
1283 if ( uname(&utsname) == 0
1284 && ( (strncmp(utsname.release, "2.5.", 4) == 0 && atoi(&utsname.release[4]) >= 18)
1285 || (strncmp(utsname.release, "2.", 2) == 0 && atoi(&utsname.release[2]) >= 6)))
1286 {
1287 uint64_t cbBlk;
1288 if (!ioctl(RTFileToNative(hRawFile), BLKGETSIZE64, &cbBlk))
1289 cbSize = cbBlk;
1290 }
1291#endif /* BLKGETSIZE64 */
1292 if (!cbSize)
1293 {
1294 long cBlocks;
1295 if (!ioctl(RTFileToNative(hRawFile), BLKGETSIZE, &cBlocks))
1296 cbSize = (uint64_t)cBlocks << 9;
1297 else
1298 {
1299 vrc = RTErrConvertFromErrno(errno);
1300 RTMsgError("Cannot get the size of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1301 goto out;
1302 }
1303 }
1304 }
1305 else if (S_ISREG(DevStat.st_mode))
1306 {
1307 vrc = RTFileGetSize(hRawFile, &cbSize);
1308 if (RT_FAILURE(vrc))
1309 {
1310 RTMsgError("Failed to get size of file '%s': %Rrc", rawdisk.c_str(), vrc);
1311 goto out;
1312 }
1313 else if (fRelative)
1314 {
1315 RTMsgError("The -relative parameter is invalid for raw images");
1316 vrc = VERR_INVALID_PARAMETER;
1317 goto out;
1318 }
1319 }
1320 else
1321 {
1322 RTMsgError("File '%s' is no block device", rawdisk.c_str());
1323 vrc = VERR_INVALID_PARAMETER;
1324 goto out;
1325 }
1326 }
1327 else
1328 {
1329 vrc = RTErrConvertFromErrno(errno);
1330 RTMsgError("Failed to get file informtation for raw disk '%s': %Rrc",
1331 rawdisk.c_str(), vrc);
1332 }
1333#elif defined(RT_OS_DARWIN)
1334 struct stat DevStat;
1335 if (!fstat(RTFileToNative(hRawFile), &DevStat))
1336 {
1337 if (S_ISBLK(DevStat.st_mode))
1338 {
1339 uint64_t cBlocks;
1340 uint32_t cbBlock;
1341 if (!ioctl(RTFileToNative(hRawFile), DKIOCGETBLOCKCOUNT, &cBlocks))
1342 {
1343 if (!ioctl(RTFileToNative(hRawFile), DKIOCGETBLOCKSIZE, &cbBlock))
1344 cbSize = cBlocks * cbBlock;
1345 else
1346 {
1347 RTMsgError("Cannot get the block size for file '%s': %Rrc", rawdisk.c_str(), vrc);
1348 vrc = RTErrConvertFromErrno(errno);
1349 goto out;
1350 }
1351 }
1352 else
1353 {
1354 vrc = RTErrConvertFromErrno(errno);
1355 RTMsgError("Cannot get the block count for file '%s': %Rrc", rawdisk.c_str(), vrc);
1356 goto out;
1357 }
1358 }
1359 else if (S_ISREG(DevStat.st_mode))
1360 {
1361 fRelative = false; /* Must be false for raw image files. */
1362 vrc = RTFileGetSize(hRawFile, &cbSize);
1363 if (RT_FAILURE(vrc))
1364 {
1365 RTMsgError("Failed to get size of file '%s': %Rrc", rawdisk.c_str(), vrc);
1366 goto out;
1367 }
1368 }
1369 else
1370 {
1371 RTMsgError("File '%s' is neither block device nor regular file", rawdisk.c_str());
1372 vrc = VERR_INVALID_PARAMETER;
1373 goto out;
1374 }
1375 }
1376 else
1377 {
1378 vrc = RTErrConvertFromErrno(errno);
1379 RTMsgError("Failed to get file informtation for raw disk '%s': %Rrc",
1380 rawdisk.c_str(), vrc);
1381 }
1382#elif defined(RT_OS_SOLARIS)
1383 struct stat DevStat;
1384 if (!fstat(RTFileToNative(hRawFile), &DevStat))
1385 {
1386 if (S_ISBLK(DevStat.st_mode) || S_ISCHR(DevStat.st_mode))
1387 {
1388 struct dk_minfo mediainfo;
1389 if (!ioctl(RTFileToNative(hRawFile), DKIOCGMEDIAINFO, &mediainfo))
1390 cbSize = mediainfo.dki_capacity * mediainfo.dki_lbsize;
1391 else
1392 {
1393 vrc = RTErrConvertFromErrno(errno);
1394 RTMsgError("Cannot get the size of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1395 goto out;
1396 }
1397 }
1398 else if (S_ISREG(DevStat.st_mode))
1399 {
1400 vrc = RTFileGetSize(hRawFile, &cbSize);
1401 if (RT_FAILURE(vrc))
1402 {
1403 RTMsgError("Failed to get size of file '%s': %Rrc", rawdisk.c_str(), vrc);
1404 goto out;
1405 }
1406 }
1407 else
1408 {
1409 RTMsgError("File '%s' is no block or char device", rawdisk.c_str());
1410 vrc = VERR_INVALID_PARAMETER;
1411 goto out;
1412 }
1413 }
1414 else
1415 {
1416 vrc = RTErrConvertFromErrno(errno);
1417 RTMsgError("Failed to get file informtation for raw disk '%s': %Rrc",
1418 rawdisk.c_str(), vrc);
1419 }
1420#elif defined(RT_OS_FREEBSD)
1421 struct stat DevStat;
1422 if (!fstat(RTFileToNative(hRawFile), &DevStat))
1423 {
1424 if (S_ISCHR(DevStat.st_mode))
1425 {
1426 off_t cbMedia = 0;
1427 if (!ioctl(RTFileToNative(hRawFile), DIOCGMEDIASIZE, &cbMedia))
1428 cbSize = cbMedia;
1429 else
1430 {
1431 vrc = RTErrConvertFromErrno(errno);
1432 RTMsgError("Cannot get the block count for file '%s': %Rrc", rawdisk.c_str(), vrc);
1433 goto out;
1434 }
1435 }
1436 else if (S_ISREG(DevStat.st_mode))
1437 {
1438 if (fRelative)
1439 {
1440 RTMsgError("The -relative parameter is invalid for raw images");
1441 vrc = VERR_INVALID_PARAMETER;
1442 goto out;
1443 }
1444 cbSize = DevStat.st_size;
1445 }
1446 else
1447 {
1448 RTMsgError("File '%s' is neither character device nor regular file", rawdisk.c_str());
1449 vrc = VERR_INVALID_PARAMETER;
1450 goto out;
1451 }
1452 }
1453 else
1454 {
1455 vrc = RTErrConvertFromErrno(errno);
1456 RTMsgError("Failed to get file informtation for raw disk '%s': %Rrc",
1457 rawdisk.c_str(), vrc);
1458 }
1459#else /* all unrecognized OSes */
1460 /* Hopefully this works on all other hosts. If it doesn't, it'll just fail
1461 * creating the VMDK, so no real harm done. */
1462 vrc = RTFileGetSize(hRawFile, &cbSize);
1463 if (RT_FAILURE(vrc))
1464 {
1465 RTMsgError("Cannot get the size of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1466 goto out;
1467 }
1468#endif
1469
1470 /* Check whether cbSize is actually sensible. */
1471 if (!cbSize || cbSize % 512)
1472 {
1473 RTMsgError("Detected size of raw disk '%s' is %s, an invalid value", rawdisk.c_str(), cbSize);
1474 vrc = VERR_INVALID_PARAMETER;
1475 goto out;
1476 }
1477
1478 RawDescriptor.szSignature[0] = 'R';
1479 RawDescriptor.szSignature[1] = 'A';
1480 RawDescriptor.szSignature[2] = 'W';
1481 RawDescriptor.szSignature[3] = '\0';
1482 if (!pszPartitions)
1483 {
1484 RawDescriptor.fRawDisk = true;
1485 RawDescriptor.pszRawDisk = rawdisk.c_str();
1486 }
1487 else
1488 {
1489 RawDescriptor.fRawDisk = false;
1490 RawDescriptor.pszRawDisk = NULL;
1491 RawDescriptor.cPartDescs = 0;
1492 RawDescriptor.pPartDescs = NULL;
1493
1494 uint32_t uPartitions = 0;
1495
1496 const char *p = pszPartitions;
1497 char *pszNext;
1498 uint32_t u32;
1499 while (*p != '\0')
1500 {
1501 vrc = RTStrToUInt32Ex(p, &pszNext, 0, &u32);
1502 if (RT_FAILURE(vrc))
1503 {
1504 RTMsgError("Incorrect value in partitions parameter");
1505 goto out;
1506 }
1507 uPartitions |= RT_BIT(u32);
1508 p = pszNext;
1509 if (*p == ',')
1510 p++;
1511 else if (*p != '\0')
1512 {
1513 RTMsgError("Incorrect separator in partitions parameter");
1514 vrc = VERR_INVALID_PARAMETER;
1515 goto out;
1516 }
1517 }
1518
1519 HOSTPARTITIONS partitions;
1520 vrc = partRead(hRawFile, &partitions);
1521 if (RT_FAILURE(vrc))
1522 {
1523 RTMsgError("Cannot read the partition information from '%s'", rawdisk.c_str());
1524 goto out;
1525 }
1526
1527 RawDescriptor.uPartitioningType = partitions.uPartitioningType;
1528
1529 for (unsigned i = 0; i < partitions.cPartitions; i++)
1530 {
1531 if ( uPartitions & RT_BIT(partitions.aPartitions[i].uIndex)
1532 && PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1533 {
1534 /* Some ignorant user specified an extended partition.
1535 * Bad idea, as this would trigger an overlapping
1536 * partitions error later during VMDK creation. So warn
1537 * here and ignore what the user requested. */
1538 RTMsgWarning("It is not possible (and necessary) to explicitly give access to the "
1539 "extended partition %u. If required, enable access to all logical "
1540 "partitions inside this extended partition.",
1541 partitions.aPartitions[i].uIndex);
1542 uPartitions &= ~RT_BIT(partitions.aPartitions[i].uIndex);
1543 }
1544 }
1545
1546 for (unsigned i = 0; i < partitions.cPartitions; i++)
1547 {
1548 PVBOXHDDRAWPARTDESC pPartDesc = NULL;
1549
1550 /* first dump the MBR/EPT data area */
1551 if (partitions.aPartitions[i].cPartDataSectors)
1552 {
1553 pPartDesc = appendPartDesc(&RawDescriptor.cPartDescs,
1554 &RawDescriptor.pPartDescs);
1555 if (!pPartDesc)
1556 {
1557 RTMsgError("Out of memory allocating the partition list for '%s'", rawdisk.c_str());
1558 vrc = VERR_NO_MEMORY;
1559 goto out;
1560 }
1561
1562 /** @todo the clipping below isn't 100% accurate, as it should
1563 * actually clip to the track size. However, that's easier said
1564 * than done as figuring out the track size is heuristics. In
1565 * any case the clipping is adjusted later after sorting, to
1566 * prevent overlapping data areas on the resulting image. */
1567 pPartDesc->cbData = RT_MIN(partitions.aPartitions[i].cPartDataSectors, 63) * 512;
1568 pPartDesc->uStart = partitions.aPartitions[i].uPartDataStart * 512;
1569 Assert(pPartDesc->cbData - (size_t)pPartDesc->cbData == 0);
1570 void *pPartData = RTMemAlloc((size_t)pPartDesc->cbData);
1571 if (!pPartData)
1572 {
1573 RTMsgError("Out of memory allocating the partition descriptor for '%s'", rawdisk.c_str());
1574 vrc = VERR_NO_MEMORY;
1575 goto out;
1576 }
1577 vrc = RTFileReadAt(hRawFile, partitions.aPartitions[i].uPartDataStart * 512,
1578 pPartData, (size_t)pPartDesc->cbData, NULL);
1579 if (RT_FAILURE(vrc))
1580 {
1581 RTMsgError("Cannot read partition data from raw device '%s': %Rrc", rawdisk.c_str(), vrc);
1582 goto out;
1583 }
1584 /* Splice in the replacement MBR code if specified. */
1585 if ( partitions.aPartitions[i].uPartDataStart == 0
1586 && pszMBRFilename)
1587 {
1588 RTFILE MBRFile;
1589 vrc = RTFileOpen(&MBRFile, pszMBRFilename, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1590 if (RT_FAILURE(vrc))
1591 {
1592 RTMsgError("Cannot open replacement MBR file '%s' specified with -mbr: %Rrc", pszMBRFilename, vrc);
1593 goto out;
1594 }
1595 vrc = RTFileReadAt(MBRFile, 0, pPartData, 0x1be, NULL);
1596 RTFileClose(MBRFile);
1597 if (RT_FAILURE(vrc))
1598 {
1599 RTMsgError("Cannot read replacement MBR file '%s': %Rrc", pszMBRFilename, vrc);
1600 goto out;
1601 }
1602 }
1603 pPartDesc->pvPartitionData = pPartData;
1604 }
1605
1606 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1607 {
1608 /* Suppress exporting the actual extended partition. Only
1609 * logical partitions should be processed. However completely
1610 * ignoring it leads to leaving out the EBR data. */
1611 continue;
1612 }
1613
1614 /* set up values for non-relative device names */
1615 const char *pszRawName = rawdisk.c_str();
1616 uint64_t uStartOffset = partitions.aPartitions[i].uStart * 512;
1617
1618 pPartDesc = appendPartDesc(&RawDescriptor.cPartDescs,
1619 &RawDescriptor.pPartDescs);
1620 if (!pPartDesc)
1621 {
1622 RTMsgError("Out of memory allocating the partition list for '%s'", rawdisk.c_str());
1623 vrc = VERR_NO_MEMORY;
1624 goto out;
1625 }
1626
1627 if (uPartitions & RT_BIT(partitions.aPartitions[i].uIndex))
1628 {
1629 if (fRelative)
1630 {
1631#if defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
1632 /* Refer to the correct partition and use offset 0. */
1633 char *psz;
1634 RTStrAPrintf(&psz,
1635#if defined(RT_OS_LINUX)
1636 "%s%u",
1637#elif defined(RT_OS_FREEBSD)
1638 "%ss%u",
1639#endif
1640 rawdisk.c_str(),
1641 partitions.aPartitions[i].uIndex);
1642 if (!psz)
1643 {
1644 vrc = VERR_NO_STR_MEMORY;
1645 RTMsgError("Cannot create reference to individual partition %u, rc=%Rrc",
1646 partitions.aPartitions[i].uIndex, vrc);
1647 goto out;
1648 }
1649 pszRawName = psz;
1650 uStartOffset = 0;
1651#elif defined(RT_OS_DARWIN)
1652 /* Refer to the correct partition and use offset 0. */
1653 char *psz;
1654 RTStrAPrintf(&psz, "%ss%u", rawdisk.c_str(),
1655 partitions.aPartitions[i].uIndex);
1656 if (!psz)
1657 {
1658 vrc = VERR_NO_STR_MEMORY;
1659 RTMsgError("Cannot create reference to individual partition %u, rc=%Rrc",
1660 partitions.aPartitions[i].uIndex, vrc);
1661 goto out;
1662 }
1663 pszRawName = psz;
1664 uStartOffset = 0;
1665#else
1666 /** @todo not implemented for other hosts. Treat just like
1667 * not specified (this code is actually never reached). */
1668#endif
1669 }
1670
1671 pPartDesc->pszRawDevice = pszRawName;
1672 pPartDesc->uStartOffset = uStartOffset;
1673 }
1674 else
1675 {
1676 pPartDesc->pszRawDevice = NULL;
1677 pPartDesc->uStartOffset = 0;
1678 }
1679
1680 pPartDesc->uStart = partitions.aPartitions[i].uStart * 512;
1681 pPartDesc->cbData = partitions.aPartitions[i].uSize * 512;
1682 }
1683
1684 /* Sort data areas in ascending order of start. */
1685 for (unsigned i = 0; i < RawDescriptor.cPartDescs-1; i++)
1686 {
1687 unsigned uMinIdx = i;
1688 uint64_t uMinVal = RawDescriptor.pPartDescs[i].uStart;
1689 for (unsigned j = i + 1; j < RawDescriptor.cPartDescs; j++)
1690 {
1691 if (RawDescriptor.pPartDescs[j].uStart < uMinVal)
1692 {
1693 uMinIdx = j;
1694 uMinVal = RawDescriptor.pPartDescs[j].uStart;
1695 }
1696 }
1697 if (uMinIdx != i)
1698 {
1699 /* Swap entries at index i and uMinIdx. */
1700 VBOXHDDRAWPARTDESC tmp;
1701 memcpy(&tmp, &RawDescriptor.pPartDescs[i], sizeof(tmp));
1702 memcpy(&RawDescriptor.pPartDescs[i], &RawDescriptor.pPartDescs[uMinIdx], sizeof(tmp));
1703 memcpy(&RawDescriptor.pPartDescs[uMinIdx], &tmp, sizeof(tmp));
1704 }
1705 }
1706
1707 /* Have a second go at MBR/EPT, GPT area clipping. Now that the data areas
1708 * are sorted this is much easier to get 100% right. */
1709 //for (unsigned i = 0; i < RawDescriptor.cPartDescs-1; i++)
1710 for (unsigned i = 0; i < RawDescriptor.cPartDescs; i++)
1711 {
1712 if (RawDescriptor.pPartDescs[i].pvPartitionData)
1713 {
1714 RawDescriptor.pPartDescs[i].cbData = RT_MIN(RawDescriptor.pPartDescs[i+1].uStart - RawDescriptor.pPartDescs[i].uStart, RawDescriptor.pPartDescs[i].cbData);
1715 if (!RawDescriptor.pPartDescs[i].cbData)
1716 {
1717 if(RawDescriptor.uPartitioningType == MBR)
1718 {
1719 RTMsgError("MBR/EPT overlaps with data area");
1720 vrc = VERR_INVALID_PARAMETER;
1721 goto out;
1722 }
1723 else
1724 {
1725 if(RawDescriptor.cPartDescs != i+1)
1726 {
1727 RTMsgError("GPT overlaps with data area");
1728 vrc = VERR_INVALID_PARAMETER;
1729 goto out;
1730 }
1731 }
1732 }
1733 }
1734 }
1735 }
1736
1737 RTFileClose(hRawFile);
1738
1739#ifdef DEBUG_klaus
1740 if (!RawDescriptor.fRawDisk)
1741 {
1742 RTPrintf("# start length startoffset partdataptr device\n");
1743 for (unsigned i = 0; i < RawDescriptor.cPartDescs; i++)
1744 {
1745 RTPrintf("%2u %14RU64 %14RU64 %14RU64 %#18p %s\n", i,
1746 RawDescriptor.pPartDescs[i].uStart,
1747 RawDescriptor.pPartDescs[i].cbData,
1748 RawDescriptor.pPartDescs[i].uStartOffset,
1749 RawDescriptor.pPartDescs[i].pvPartitionData,
1750 RawDescriptor.pPartDescs[i].pszRawDevice);
1751 }
1752 }
1753#endif
1754
1755 VDINTERFACEERROR vdInterfaceError;
1756 vdInterfaceError.pfnError = handleVDError;
1757 vdInterfaceError.pfnMessage = handleVDMessage;
1758
1759 rc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1760 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1761 AssertRC(vrc);
1762
1763 vrc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk); /* Raw VMDK's are harddisk only. */
1764 if (RT_FAILURE(vrc))
1765 {
1766 RTMsgError("Cannot create the virtual disk container: %Rrc", vrc);
1767 goto out;
1768 }
1769
1770 Assert(RT_MIN(cbSize / 512 / 16 / 63, 16383) -
1771 (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383) == 0);
1772 VDGEOMETRY PCHS, LCHS;
1773 PCHS.cCylinders = (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383);
1774 PCHS.cHeads = 16;
1775 PCHS.cSectors = 63;
1776 LCHS.cCylinders = 0;
1777 LCHS.cHeads = 0;
1778 LCHS.cSectors = 0;
1779 vrc = VDCreateBase(pDisk, "VMDK", filename.c_str(), cbSize,
1780 VD_IMAGE_FLAGS_FIXED | VD_VMDK_IMAGE_FLAGS_RAWDISK,
1781 (char *)&RawDescriptor, &PCHS, &LCHS, NULL,
1782 VD_OPEN_FLAGS_NORMAL, NULL, NULL);
1783 if (RT_FAILURE(vrc))
1784 {
1785 RTMsgError("Cannot create the raw disk VMDK: %Rrc", vrc);
1786 goto out;
1787 }
1788 RTPrintf("RAW host disk access VMDK file %s created successfully.\n", filename.c_str());
1789
1790 VDCloseAll(pDisk);
1791
1792 /* Clean up allocated memory etc. */
1793 if (pszPartitions)
1794 {
1795 for (unsigned i = 0; i < RawDescriptor.cPartDescs; i++)
1796 {
1797 /* Free memory allocated for relative device name. */
1798 if (fRelative && RawDescriptor.pPartDescs[i].pszRawDevice)
1799 RTStrFree((char *)(void *)RawDescriptor.pPartDescs[i].pszRawDevice);
1800 if (RawDescriptor.pPartDescs[i].pvPartitionData)
1801 RTMemFree((void *)RawDescriptor.pPartDescs[i].pvPartitionData);
1802 }
1803 if (RawDescriptor.pPartDescs)
1804 RTMemFree(RawDescriptor.pPartDescs);
1805 }
1806
1807 return SUCCEEDED(rc) ? 0 : 1;
1808
1809out:
1810 RTMsgError("The raw disk vmdk file was not created");
1811 return RT_SUCCESS(vrc) ? 0 : 1;
1812}
1813
1814static int CmdRenameVMDK(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1815{
1816 Utf8Str src;
1817 Utf8Str dst;
1818 /* Parse the arguments. */
1819 for (int i = 0; i < argc; i++)
1820 {
1821 if (strcmp(argv[i], "-from") == 0)
1822 {
1823 if (argc <= i + 1)
1824 {
1825 return errorArgument("Missing argument to '%s'", argv[i]);
1826 }
1827 i++;
1828 src = argv[i];
1829 }
1830 else if (strcmp(argv[i], "-to") == 0)
1831 {
1832 if (argc <= i + 1)
1833 {
1834 return errorArgument("Missing argument to '%s'", argv[i]);
1835 }
1836 i++;
1837 dst = argv[i];
1838 }
1839 else
1840 {
1841 return errorSyntax(USAGE_RENAMEVMDK, "Invalid parameter '%s'", argv[i]);
1842 }
1843 }
1844
1845 if (src.isEmpty())
1846 return errorSyntax(USAGE_RENAMEVMDK, "Mandatory parameter -from missing");
1847 if (dst.isEmpty())
1848 return errorSyntax(USAGE_RENAMEVMDK, "Mandatory parameter -to missing");
1849
1850 PVBOXHDD pDisk = NULL;
1851
1852 PVDINTERFACE pVDIfs = NULL;
1853 VDINTERFACEERROR vdInterfaceError;
1854 vdInterfaceError.pfnError = handleVDError;
1855 vdInterfaceError.pfnMessage = handleVDMessage;
1856
1857 int vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1858 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1859 AssertRC(vrc);
1860
1861 vrc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk);
1862 if (RT_FAILURE(vrc))
1863 {
1864 RTMsgError("Cannot create the virtual disk container: %Rrc", vrc);
1865 return vrc;
1866 }
1867 else
1868 {
1869 vrc = VDOpen(pDisk, "VMDK", src.c_str(), VD_OPEN_FLAGS_NORMAL, NULL);
1870 if (RT_FAILURE(vrc))
1871 {
1872 RTMsgError("Cannot create the source image: %Rrc", vrc);
1873 }
1874 else
1875 {
1876 vrc = VDCopy(pDisk, 0, pDisk, "VMDK", dst.c_str(), true, 0,
1877 VD_IMAGE_FLAGS_NONE, NULL, VD_OPEN_FLAGS_NORMAL,
1878 NULL, NULL, NULL);
1879 if (RT_FAILURE(vrc))
1880 {
1881 RTMsgError("Cannot rename the image: %Rrc", vrc);
1882 }
1883 }
1884 }
1885 VDCloseAll(pDisk);
1886 return vrc;
1887}
1888
1889static int CmdConvertToRaw(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1890{
1891 Utf8Str srcformat;
1892 Utf8Str src;
1893 Utf8Str dst;
1894 bool fWriteToStdOut = false;
1895
1896 /* Parse the arguments. */
1897 for (int i = 0; i < argc; i++)
1898 {
1899 if (strcmp(argv[i], "-format") == 0)
1900 {
1901 if (argc <= i + 1)
1902 {
1903 return errorArgument("Missing argument to '%s'", argv[i]);
1904 }
1905 i++;
1906 srcformat = argv[i];
1907 }
1908 else if (src.isEmpty())
1909 {
1910 src = argv[i];
1911 }
1912 else if (dst.isEmpty())
1913 {
1914 dst = argv[i];
1915#ifdef ENABLE_CONVERT_RAW_TO_STDOUT
1916 if (!strcmp(argv[i], "stdout"))
1917 fWriteToStdOut = true;
1918#endif /* ENABLE_CONVERT_RAW_TO_STDOUT */
1919 }
1920 else
1921 {
1922 return errorSyntax(USAGE_CONVERTTORAW, "Invalid parameter '%s'", argv[i]);
1923 }
1924 }
1925
1926 if (src.isEmpty())
1927 return errorSyntax(USAGE_CONVERTTORAW, "Mandatory filename parameter missing");
1928 if (dst.isEmpty())
1929 return errorSyntax(USAGE_CONVERTTORAW, "Mandatory outputfile parameter missing");
1930
1931 PVBOXHDD pDisk = NULL;
1932
1933 PVDINTERFACE pVDIfs = NULL;
1934 VDINTERFACEERROR vdInterfaceError;
1935 vdInterfaceError.pfnError = handleVDError;
1936 vdInterfaceError.pfnMessage = handleVDMessage;
1937
1938 int vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1939 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1940 AssertRC(vrc);
1941
1942 /** @todo: Support convert to raw for floppy and DVD images too. */
1943 vrc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk);
1944 if (RT_FAILURE(vrc))
1945 {
1946 RTMsgError("Cannot create the virtual disk container: %Rrc", vrc);
1947 return 1;
1948 }
1949
1950 /* Open raw output file. */
1951 RTFILE outFile;
1952 vrc = VINF_SUCCESS;
1953 if (fWriteToStdOut)
1954 vrc = RTFileFromNative(&outFile, 1);
1955 else
1956 vrc = RTFileOpen(&outFile, dst.c_str(), RTFILE_O_WRITE | RTFILE_O_CREATE | RTFILE_O_DENY_ALL);
1957 if (RT_FAILURE(vrc))
1958 {
1959 VDCloseAll(pDisk);
1960 RTMsgError("Cannot create destination file \"%s\": %Rrc", dst.c_str(), vrc);
1961 return 1;
1962 }
1963
1964 if (srcformat.isEmpty())
1965 {
1966 char *pszFormat = NULL;
1967 VDTYPE enmType = VDTYPE_INVALID;
1968 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
1969 src.c_str(), &pszFormat, &enmType);
1970 if (RT_FAILURE(vrc) || enmType != VDTYPE_HDD)
1971 {
1972 VDCloseAll(pDisk);
1973 if (!fWriteToStdOut)
1974 {
1975 RTFileClose(outFile);
1976 RTFileDelete(dst.c_str());
1977 }
1978 if (RT_FAILURE(vrc))
1979 RTMsgError("No file format specified and autodetect failed - please specify format: %Rrc", vrc);
1980 else
1981 RTMsgError("Only converting harddisk images is supported");
1982 return 1;
1983 }
1984 srcformat = pszFormat;
1985 RTStrFree(pszFormat);
1986 }
1987 vrc = VDOpen(pDisk, srcformat.c_str(), src.c_str(), VD_OPEN_FLAGS_READONLY, NULL);
1988 if (RT_FAILURE(vrc))
1989 {
1990 VDCloseAll(pDisk);
1991 if (!fWriteToStdOut)
1992 {
1993 RTFileClose(outFile);
1994 RTFileDelete(dst.c_str());
1995 }
1996 RTMsgError("Cannot open the source image: %Rrc", vrc);
1997 return 1;
1998 }
1999
2000 uint64_t cbSize = VDGetSize(pDisk, VD_LAST_IMAGE);
2001 uint64_t offFile = 0;
2002#define RAW_BUFFER_SIZE _128K
2003 size_t cbBuf = RAW_BUFFER_SIZE;
2004 void *pvBuf = RTMemAlloc(cbBuf);
2005 if (pvBuf)
2006 {
2007 RTStrmPrintf(g_pStdErr, "Converting image \"%s\" with size %RU64 bytes (%RU64MB) to raw...\n", src.c_str(), cbSize, (cbSize + _1M - 1) / _1M);
2008 while (offFile < cbSize)
2009 {
2010 size_t cb = (size_t)RT_MIN(cbSize - offFile, cbBuf);
2011 vrc = VDRead(pDisk, offFile, pvBuf, cb);
2012 if (RT_FAILURE(vrc))
2013 break;
2014 vrc = RTFileWrite(outFile, pvBuf, cb, NULL);
2015 if (RT_FAILURE(vrc))
2016 break;
2017 offFile += cb;
2018 }
2019 if (RT_FAILURE(vrc))
2020 {
2021 VDCloseAll(pDisk);
2022 if (!fWriteToStdOut)
2023 {
2024 RTFileClose(outFile);
2025 RTFileDelete(dst.c_str());
2026 }
2027 RTMsgError("Cannot copy image data: %Rrc", vrc);
2028 return 1;
2029 }
2030 }
2031 else
2032 {
2033 vrc = VERR_NO_MEMORY;
2034 VDCloseAll(pDisk);
2035 if (!fWriteToStdOut)
2036 {
2037 RTFileClose(outFile);
2038 RTFileDelete(dst.c_str());
2039 }
2040 RTMsgError("Out of memory allocating read buffer");
2041 return 1;
2042 }
2043
2044 if (!fWriteToStdOut)
2045 RTFileClose(outFile);
2046 VDCloseAll(pDisk);
2047 return 0;
2048}
2049
2050static int CmdConvertHardDisk(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2051{
2052 Utf8Str srcformat;
2053 Utf8Str dstformat;
2054 Utf8Str src;
2055 Utf8Str dst;
2056 int vrc;
2057 PVBOXHDD pSrcDisk = NULL;
2058 PVBOXHDD pDstDisk = NULL;
2059 VDTYPE enmSrcType = VDTYPE_INVALID;
2060
2061 /* Parse the arguments. */
2062 for (int i = 0; i < argc; i++)
2063 {
2064 if (strcmp(argv[i], "-srcformat") == 0)
2065 {
2066 if (argc <= i + 1)
2067 {
2068 return errorArgument("Missing argument to '%s'", argv[i]);
2069 }
2070 i++;
2071 srcformat = argv[i];
2072 }
2073 else if (strcmp(argv[i], "-dstformat") == 0)
2074 {
2075 if (argc <= i + 1)
2076 {
2077 return errorArgument("Missing argument to '%s'", argv[i]);
2078 }
2079 i++;
2080 dstformat = argv[i];
2081 }
2082 else if (src.isEmpty())
2083 {
2084 src = argv[i];
2085 }
2086 else if (dst.isEmpty())
2087 {
2088 dst = argv[i];
2089 }
2090 else
2091 {
2092 return errorSyntax(USAGE_CONVERTHD, "Invalid parameter '%s'", argv[i]);
2093 }
2094 }
2095
2096 if (src.isEmpty())
2097 return errorSyntax(USAGE_CONVERTHD, "Mandatory input image parameter missing");
2098 if (dst.isEmpty())
2099 return errorSyntax(USAGE_CONVERTHD, "Mandatory output image parameter missing");
2100
2101
2102 PVDINTERFACE pVDIfs = NULL;
2103 VDINTERFACEERROR vdInterfaceError;
2104 vdInterfaceError.pfnError = handleVDError;
2105 vdInterfaceError.pfnMessage = handleVDMessage;
2106
2107 vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
2108 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
2109 AssertRC(vrc);
2110
2111 do
2112 {
2113 /* Try to determine input image format */
2114 if (srcformat.isEmpty())
2115 {
2116 char *pszFormat = NULL;
2117 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
2118 src.c_str(), &pszFormat, &enmSrcType);
2119 if (RT_FAILURE(vrc))
2120 {
2121 RTMsgError("No file format specified and autodetect failed - please specify format: %Rrc", vrc);
2122 break;
2123 }
2124 srcformat = pszFormat;
2125 RTStrFree(pszFormat);
2126 }
2127
2128 vrc = VDCreate(pVDIfs, enmSrcType, &pSrcDisk);
2129 if (RT_FAILURE(vrc))
2130 {
2131 RTMsgError("Cannot create the source virtual disk container: %Rrc", vrc);
2132 break;
2133 }
2134
2135 /* Open the input image */
2136 vrc = VDOpen(pSrcDisk, srcformat.c_str(), src.c_str(), VD_OPEN_FLAGS_READONLY, NULL);
2137 if (RT_FAILURE(vrc))
2138 {
2139 RTMsgError("Cannot open the source image: %Rrc", vrc);
2140 break;
2141 }
2142
2143 /* Output format defaults to VDI */
2144 if (dstformat.isEmpty())
2145 dstformat = "VDI";
2146
2147 vrc = VDCreate(pVDIfs, enmSrcType, &pDstDisk);
2148 if (RT_FAILURE(vrc))
2149 {
2150 RTMsgError("Cannot create the destination virtual disk container: %Rrc", vrc);
2151 break;
2152 }
2153
2154 uint64_t cbSize = VDGetSize(pSrcDisk, VD_LAST_IMAGE);
2155 RTStrmPrintf(g_pStdErr, "Converting image \"%s\" with size %RU64 bytes (%RU64MB)...\n", src.c_str(), cbSize, (cbSize + _1M - 1) / _1M);
2156
2157 /* Create the output image */
2158 vrc = VDCopy(pSrcDisk, VD_LAST_IMAGE, pDstDisk, dstformat.c_str(),
2159 dst.c_str(), false, 0, VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED,
2160 NULL, VD_OPEN_FLAGS_NORMAL, NULL, NULL, NULL);
2161 if (RT_FAILURE(vrc))
2162 {
2163 RTMsgError("Cannot copy the image: %Rrc", vrc);
2164 break;
2165 }
2166 }
2167 while (0);
2168 if (pDstDisk)
2169 VDCloseAll(pDstDisk);
2170 if (pSrcDisk)
2171 VDCloseAll(pSrcDisk);
2172
2173 return RT_SUCCESS(vrc) ? 0 : 1;
2174}
2175
2176/**
2177 * Tries to repair a corrupted hard disk image.
2178 *
2179 * @returns VBox status code
2180 */
2181static int CmdRepairHardDisk(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2182{
2183 Utf8Str image;
2184 Utf8Str format;
2185 int vrc;
2186 bool fDryRun = false;
2187 PVBOXHDD pDisk = NULL;
2188
2189 /* Parse the arguments. */
2190 for (int i = 0; i < argc; i++)
2191 {
2192 if (strcmp(argv[i], "-dry-run") == 0)
2193 {
2194 fDryRun = true;
2195 }
2196 else if (strcmp(argv[i], "-format") == 0)
2197 {
2198 if (argc <= i + 1)
2199 {
2200 return errorArgument("Missing argument to '%s'", argv[i]);
2201 }
2202 i++;
2203 format = argv[i];
2204 }
2205 else if (image.isEmpty())
2206 {
2207 image = argv[i];
2208 }
2209 else
2210 {
2211 return errorSyntax(USAGE_REPAIRHD, "Invalid parameter '%s'", argv[i]);
2212 }
2213 }
2214
2215 if (image.isEmpty())
2216 return errorSyntax(USAGE_REPAIRHD, "Mandatory input image parameter missing");
2217
2218 PVDINTERFACE pVDIfs = NULL;
2219 VDINTERFACEERROR vdInterfaceError;
2220 vdInterfaceError.pfnError = handleVDError;
2221 vdInterfaceError.pfnMessage = handleVDMessage;
2222
2223 vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
2224 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
2225 AssertRC(vrc);
2226
2227 do
2228 {
2229 /* Try to determine input image format */
2230 if (format.isEmpty())
2231 {
2232 char *pszFormat = NULL;
2233 VDTYPE enmSrcType = VDTYPE_INVALID;
2234
2235 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
2236 image.c_str(), &pszFormat, &enmSrcType);
2237 if (RT_FAILURE(vrc) && (vrc != VERR_VD_IMAGE_CORRUPTED))
2238 {
2239 RTMsgError("No file format specified and autodetect failed - please specify format: %Rrc", vrc);
2240 break;
2241 }
2242 format = pszFormat;
2243 RTStrFree(pszFormat);
2244 }
2245
2246 uint32_t fFlags = 0;
2247 if (fDryRun)
2248 fFlags |= VD_REPAIR_DRY_RUN;
2249
2250 vrc = VDRepair(pVDIfs, NULL, image.c_str(), format.c_str(), fFlags);
2251 }
2252 while (0);
2253
2254 return RT_SUCCESS(vrc) ? 0 : 1;
2255}
2256
2257/**
2258 * Unloads the necessary driver.
2259 *
2260 * @returns VBox status code
2261 */
2262int CmdModUninstall(void)
2263{
2264 int rc;
2265
2266 rc = SUPR3Uninstall();
2267 if (RT_SUCCESS(rc))
2268 return 0;
2269 if (rc == VERR_NOT_IMPLEMENTED)
2270 return 0;
2271 return E_FAIL;
2272}
2273
2274/**
2275 * Loads the necessary driver.
2276 *
2277 * @returns VBox status code
2278 */
2279int CmdModInstall(void)
2280{
2281 int rc;
2282
2283 rc = SUPR3Install();
2284 if (RT_SUCCESS(rc))
2285 return 0;
2286 if (rc == VERR_NOT_IMPLEMENTED)
2287 return 0;
2288 return E_FAIL;
2289}
2290
2291int CmdDebugLog(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2292{
2293 /*
2294 * The first parameter is the name or UUID of a VM with a direct session
2295 * that we wish to open.
2296 */
2297 if (argc < 1)
2298 return errorSyntax(USAGE_DEBUGLOG, "Missing VM name/UUID");
2299
2300 ComPtr<IMachine> ptrMachine;
2301 HRESULT rc;
2302 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
2303 ptrMachine.asOutParam()), 1);
2304
2305 CHECK_ERROR_RET(ptrMachine, LockMachine(aSession, LockType_Shared), 1);
2306
2307 /*
2308 * Get the debugger interface.
2309 */
2310 ComPtr<IConsole> ptrConsole;
2311 CHECK_ERROR_RET(aSession, COMGETTER(Console)(ptrConsole.asOutParam()), 1);
2312
2313 ComPtr<IMachineDebugger> ptrDebugger;
2314 CHECK_ERROR_RET(ptrConsole, COMGETTER(Debugger)(ptrDebugger.asOutParam()), 1);
2315
2316 /*
2317 * Parse the command.
2318 */
2319 bool fEnablePresent = false;
2320 bool fEnable = false;
2321 bool fFlagsPresent = false;
2322 RTCString strFlags;
2323 bool fGroupsPresent = false;
2324 RTCString strGroups;
2325 bool fDestsPresent = false;
2326 RTCString strDests;
2327
2328 static const RTGETOPTDEF s_aOptions[] =
2329 {
2330 { "--disable", 'E', RTGETOPT_REQ_NOTHING },
2331 { "--enable", 'e', RTGETOPT_REQ_NOTHING },
2332 { "--flags", 'f', RTGETOPT_REQ_STRING },
2333 { "--groups", 'g', RTGETOPT_REQ_STRING },
2334 { "--destinations", 'd', RTGETOPT_REQ_STRING }
2335 };
2336
2337 int ch;
2338 RTGETOPTUNION ValueUnion;
2339 RTGETOPTSTATE GetState;
2340 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
2341 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
2342 {
2343 switch (ch)
2344 {
2345 case 'e':
2346 fEnablePresent = true;
2347 fEnable = true;
2348 break;
2349
2350 case 'E':
2351 fEnablePresent = true;
2352 fEnable = false;
2353 break;
2354
2355 case 'f':
2356 fFlagsPresent = true;
2357 if (*ValueUnion.psz)
2358 {
2359 if (strFlags.isNotEmpty())
2360 strFlags.append(' ');
2361 strFlags.append(ValueUnion.psz);
2362 }
2363 break;
2364
2365 case 'g':
2366 fGroupsPresent = true;
2367 if (*ValueUnion.psz)
2368 {
2369 if (strGroups.isNotEmpty())
2370 strGroups.append(' ');
2371 strGroups.append(ValueUnion.psz);
2372 }
2373 break;
2374
2375 case 'd':
2376 fDestsPresent = true;
2377 if (*ValueUnion.psz)
2378 {
2379 if (strDests.isNotEmpty())
2380 strDests.append(' ');
2381 strDests.append(ValueUnion.psz);
2382 }
2383 break;
2384
2385 default:
2386 return errorGetOpt(USAGE_DEBUGLOG , ch, &ValueUnion);
2387 }
2388 }
2389
2390 /*
2391 * Do the job.
2392 */
2393 if (fEnablePresent && !fEnable)
2394 CHECK_ERROR_RET(ptrDebugger, COMSETTER(LogEnabled)(FALSE), 1);
2395
2396 /** @todo flags, groups destination. */
2397 if (fFlagsPresent || fGroupsPresent || fDestsPresent)
2398 RTMsgWarning("One or more of the requested features are not implemented! Feel free to do this.");
2399
2400 if (fEnablePresent && fEnable)
2401 CHECK_ERROR_RET(ptrDebugger, COMSETTER(LogEnabled)(TRUE), 1);
2402 return 0;
2403}
2404
2405/**
2406 * Generate a SHA-256 password hash
2407 */
2408int CmdGeneratePasswordHash(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2409{
2410 /* one parameter, the password to hash */
2411 if (argc != 1)
2412 return errorSyntax(USAGE_PASSWORDHASH, "password to hash required");
2413
2414 uint8_t abDigest[RTSHA256_HASH_SIZE];
2415 RTSha256(argv[0], strlen(argv[0]), abDigest);
2416 char pszDigest[RTSHA256_DIGEST_LEN + 1];
2417 RTSha256ToString(abDigest, pszDigest, sizeof(pszDigest));
2418 RTPrintf("Password hash: %s\n", pszDigest);
2419
2420 return 0;
2421}
2422
2423/**
2424 * Print internal guest statistics or
2425 * set internal guest statistics update interval if specified
2426 */
2427int CmdGuestStats(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2428{
2429 /* one parameter, guest name */
2430 if (argc < 1)
2431 return errorSyntax(USAGE_GUESTSTATS, "Missing VM name/UUID");
2432
2433 /*
2434 * Parse the command.
2435 */
2436 ULONG aUpdateInterval = 0;
2437
2438 static const RTGETOPTDEF s_aOptions[] =
2439 {
2440 { "--interval", 'i', RTGETOPT_REQ_UINT32 }
2441 };
2442
2443 int ch;
2444 RTGETOPTUNION ValueUnion;
2445 RTGETOPTSTATE GetState;
2446 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
2447 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
2448 {
2449 switch (ch)
2450 {
2451 case 'i':
2452 aUpdateInterval = ValueUnion.u32;
2453 break;
2454
2455 default:
2456 return errorGetOpt(USAGE_GUESTSTATS , ch, &ValueUnion);
2457 }
2458 }
2459
2460 if (argc > 1 && aUpdateInterval == 0)
2461 return errorSyntax(USAGE_GUESTSTATS, "Invalid update interval specified");
2462
2463 RTPrintf("argc=%d interval=%u\n", argc, aUpdateInterval);
2464
2465 ComPtr<IMachine> ptrMachine;
2466 HRESULT rc;
2467 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
2468 ptrMachine.asOutParam()), 1);
2469
2470 CHECK_ERROR_RET(ptrMachine, LockMachine(aSession, LockType_Shared), 1);
2471
2472 /*
2473 * Get the guest interface.
2474 */
2475 ComPtr<IConsole> ptrConsole;
2476 CHECK_ERROR_RET(aSession, COMGETTER(Console)(ptrConsole.asOutParam()), 1);
2477
2478 ComPtr<IGuest> ptrGuest;
2479 CHECK_ERROR_RET(ptrConsole, COMGETTER(Guest)(ptrGuest.asOutParam()), 1);
2480
2481 if (aUpdateInterval)
2482 CHECK_ERROR_RET(ptrGuest, COMSETTER(StatisticsUpdateInterval)(aUpdateInterval), 1);
2483 else
2484 {
2485 ULONG mCpuUser, mCpuKernel, mCpuIdle;
2486 ULONG mMemTotal, mMemFree, mMemBalloon, mMemShared, mMemCache, mPageTotal;
2487 ULONG ulMemAllocTotal, ulMemFreeTotal, ulMemBalloonTotal, ulMemSharedTotal;
2488
2489 CHECK_ERROR_RET(ptrGuest, InternalGetStatistics(&mCpuUser, &mCpuKernel, &mCpuIdle,
2490 &mMemTotal, &mMemFree, &mMemBalloon, &mMemShared, &mMemCache,
2491 &mPageTotal, &ulMemAllocTotal, &ulMemFreeTotal, &ulMemBalloonTotal, &ulMemSharedTotal), 1);
2492 RTPrintf("mCpuUser=%u mCpuKernel=%u mCpuIdle=%u\n"
2493 "mMemTotal=%u mMemFree=%u mMemBalloon=%u mMemShared=%u mMemCache=%u\n"
2494 "mPageTotal=%u ulMemAllocTotal=%u ulMemFreeTotal=%u ulMemBalloonTotal=%u ulMemSharedTotal=%u\n",
2495 mCpuUser, mCpuKernel, mCpuIdle,
2496 mMemTotal, mMemFree, mMemBalloon, mMemShared, mMemCache,
2497 mPageTotal, ulMemAllocTotal, ulMemFreeTotal, ulMemBalloonTotal, ulMemSharedTotal);
2498
2499 }
2500
2501 return 0;
2502}
2503
2504
2505/**
2506 * Wrapper for handling internal commands
2507 */
2508int handleInternalCommands(HandlerArg *a)
2509{
2510 g_fInternalMode = true;
2511
2512 /* at least a command is required */
2513 if (a->argc < 1)
2514 return errorSyntax(USAGE_ALL, "Command missing");
2515
2516 /*
2517 * The 'string switch' on command name.
2518 */
2519 const char *pszCmd = a->argv[0];
2520 if (!strcmp(pszCmd, "loadmap"))
2521 return CmdLoadMap(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2522 if (!strcmp(pszCmd, "loadsyms"))
2523 return CmdLoadSyms(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2524 //if (!strcmp(pszCmd, "unloadsyms"))
2525 // return CmdUnloadSyms(argc - 1 , &a->argv[1]);
2526 if (!strcmp(pszCmd, "sethduuid") || !strcmp(pszCmd, "sethdparentuuid"))
2527 return CmdSetHDUUID(a->argc, &a->argv[0], a->virtualBox, a->session);
2528 if (!strcmp(pszCmd, "dumphdinfo"))
2529 return CmdDumpHDInfo(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2530 if (!strcmp(pszCmd, "listpartitions"))
2531 return CmdListPartitions(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2532 if (!strcmp(pszCmd, "createrawvmdk"))
2533 return CmdCreateRawVMDK(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2534 if (!strcmp(pszCmd, "renamevmdk"))
2535 return CmdRenameVMDK(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2536 if (!strcmp(pszCmd, "converttoraw"))
2537 return CmdConvertToRaw(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2538 if (!strcmp(pszCmd, "converthd"))
2539 return CmdConvertHardDisk(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2540 if (!strcmp(pszCmd, "modinstall"))
2541 return CmdModInstall();
2542 if (!strcmp(pszCmd, "moduninstall"))
2543 return CmdModUninstall();
2544 if (!strcmp(pszCmd, "debuglog"))
2545 return CmdDebugLog(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2546 if (!strcmp(pszCmd, "passwordhash"))
2547 return CmdGeneratePasswordHash(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2548 if (!strcmp(pszCmd, "gueststats"))
2549 return CmdGuestStats(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2550 if (!strcmp(pszCmd, "repairhd"))
2551 return CmdRepairHardDisk(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2552
2553 /* default: */
2554 return errorSyntax(USAGE_ALL, "Invalid command '%s'", a->argv[0]);
2555}
2556
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