VirtualBox

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

Last change on this file since 36067 was 36067, checked in by vboxsync, 14 years ago

VBoxManage: added internal command gueststats

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

© 2024 Oracle
ContactPrivacy/Do Not Sell My InfoTerms of Use