VirtualBox

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

Last change on this file since 37763 was 37596, checked in by vboxsync, 13 years ago

*: RTFILE becomes a pointer, RTFileOpen++ expands it's flags paramter from uint32_t to uint64_t.

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