VirtualBox

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

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

DIGEST_LEN, not STRING_LEN as the terminator is not included

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 68.6 KB
Line 
1/* $Id: VBoxInternalManage.cpp 33229 2010-10-19 13:23:02Z 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/VBoxHDD.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"
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 " [-register] [-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 " Optionally the created image can be immediately registered.\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 neccessary 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 ""
247 );
248}
249
250/** @todo this is no longer necessary, we can enumerate extra data */
251/**
252 * Finds a new unique key name.
253 *
254 * I don't think this is 100% race condition proof, but we assumes
255 * the user is not trying to push this point.
256 *
257 * @returns Result from the insert.
258 * @param pMachine The Machine object.
259 * @param pszKeyBase The base key.
260 * @param rKey Reference to the string object in which we will return the key.
261 */
262static HRESULT NewUniqueKey(ComPtr<IMachine> pMachine, const char *pszKeyBase, Utf8Str &rKey)
263{
264 Bstr KeyBase(pszKeyBase);
265 Bstr Keys;
266 HRESULT hrc = pMachine->GetExtraData(KeyBase.raw(), Keys.asOutParam());
267 if (FAILED(hrc))
268 return hrc;
269
270 /* if there are no keys, it's simple. */
271 if (Keys.isEmpty())
272 {
273 rKey = "1";
274 return pMachine->SetExtraData(KeyBase.raw(), Bstr(rKey).raw());
275 }
276
277 /* find a unique number - brute force rulez. */
278 Utf8Str KeysUtf8(Keys);
279 const char *pszKeys = RTStrStripL(KeysUtf8.c_str());
280 for (unsigned i = 1; i < 1000000; i++)
281 {
282 char szKey[32];
283 size_t cchKey = RTStrPrintf(szKey, sizeof(szKey), "%#x", i);
284 const char *psz = strstr(pszKeys, szKey);
285 while (psz)
286 {
287 if ( ( psz == pszKeys
288 || psz[-1] == ' ')
289 && ( psz[cchKey] == ' '
290 || !psz[cchKey])
291 )
292 break;
293 psz = strstr(psz + cchKey, szKey);
294 }
295 if (!psz)
296 {
297 rKey = szKey;
298 Utf8StrFmt NewKeysUtf8("%s %s", pszKeys, szKey);
299 return pMachine->SetExtraData(KeyBase.raw(),
300 Bstr(NewKeysUtf8).raw());
301 }
302 }
303 RTMsgError("Cannot find unique key for '%s'!", pszKeyBase);
304 return E_FAIL;
305}
306
307
308#if 0
309/**
310 * Remove a key.
311 *
312 * I don't think this isn't 100% race condition proof, but we assumes
313 * the user is not trying to push this point.
314 *
315 * @returns Result from the insert.
316 * @param pMachine The machine object.
317 * @param pszKeyBase The base key.
318 * @param pszKey The key to remove.
319 */
320static HRESULT RemoveKey(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey)
321{
322 Bstr Keys;
323 HRESULT hrc = pMachine->GetExtraData(Bstr(pszKeyBase), Keys.asOutParam());
324 if (FAILED(hrc))
325 return hrc;
326
327 /* if there are no keys, it's simple. */
328 if (Keys.isEmpty())
329 return S_OK;
330
331 char *pszKeys;
332 int rc = RTUtf16ToUtf8(Keys.raw(), &pszKeys);
333 if (RT_SUCCESS(rc))
334 {
335 /* locate it */
336 size_t cchKey = strlen(pszKey);
337 char *psz = strstr(pszKeys, pszKey);
338 while (psz)
339 {
340 if ( ( psz == pszKeys
341 || psz[-1] == ' ')
342 && ( psz[cchKey] == ' '
343 || !psz[cchKey])
344 )
345 break;
346 psz = strstr(psz + cchKey, pszKey);
347 }
348 if (psz)
349 {
350 /* remove it */
351 char *pszNext = RTStrStripL(psz + cchKey);
352 if (*pszNext)
353 memmove(psz, pszNext, strlen(pszNext) + 1);
354 else
355 *psz = '\0';
356 psz = RTStrStrip(pszKeys);
357
358 /* update */
359 hrc = pMachine->SetExtraData(Bstr(pszKeyBase), Bstr(psz));
360 }
361
362 RTStrFree(pszKeys);
363 return hrc;
364 }
365 else
366 RTMsgError("Failed to delete key '%s' from '%s', string conversion error %Rrc!",
367 pszKey, pszKeyBase, rc);
368
369 return E_FAIL;
370}
371#endif
372
373
374/**
375 * Sets a key value, does necessary error bitching.
376 *
377 * @returns COM status code.
378 * @param pMachine The Machine object.
379 * @param pszKeyBase The key base.
380 * @param pszKey The key.
381 * @param pszAttribute The attribute name.
382 * @param pszValue The string value.
383 */
384static HRESULT SetString(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey, const char *pszAttribute, const char *pszValue)
385{
386 HRESULT hrc = pMachine->SetExtraData(BstrFmt("%s/%s/%s", pszKeyBase,
387 pszKey, pszAttribute).raw(),
388 Bstr(pszValue).raw());
389 if (FAILED(hrc))
390 RTMsgError("Failed to set '%s/%s/%s' to '%s'! hrc=%#x",
391 pszKeyBase, pszKey, pszAttribute, pszValue, hrc);
392 return hrc;
393}
394
395
396/**
397 * Sets a key value, does necessary error bitching.
398 *
399 * @returns COM status code.
400 * @param pMachine The Machine object.
401 * @param pszKeyBase The key base.
402 * @param pszKey The key.
403 * @param pszAttribute The attribute name.
404 * @param u64Value The value.
405 */
406static HRESULT SetUInt64(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey, const char *pszAttribute, uint64_t u64Value)
407{
408 char szValue[64];
409 RTStrPrintf(szValue, sizeof(szValue), "%#RX64", u64Value);
410 return SetString(pMachine, pszKeyBase, pszKey, pszAttribute, szValue);
411}
412
413
414/**
415 * Sets a key value, does necessary error bitching.
416 *
417 * @returns COM status code.
418 * @param pMachine The Machine object.
419 * @param pszKeyBase The key base.
420 * @param pszKey The key.
421 * @param pszAttribute The attribute name.
422 * @param i64Value The value.
423 */
424static HRESULT SetInt64(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey, const char *pszAttribute, int64_t i64Value)
425{
426 char szValue[64];
427 RTStrPrintf(szValue, sizeof(szValue), "%RI64", i64Value);
428 return SetString(pMachine, pszKeyBase, pszKey, pszAttribute, szValue);
429}
430
431
432/**
433 * Identical to the 'loadsyms' command.
434 */
435static int CmdLoadSyms(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
436{
437 HRESULT rc;
438
439 /*
440 * Get the VM
441 */
442 ComPtr<IMachine> machine;
443 /* assume it's a UUID */
444 rc = aVirtualBox->GetMachine(Bstr(argv[0]).raw(), machine.asOutParam());
445 if (FAILED(rc) || !machine)
446 {
447 /* must be a name */
448 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
449 machine.asOutParam()), 1);
450 }
451
452 /*
453 * Parse the command.
454 */
455 const char *pszFilename;
456 int64_t offDelta = 0;
457 const char *pszModule = NULL;
458 uint64_t ModuleAddress = ~0;
459 uint64_t ModuleSize = 0;
460
461 /* filename */
462 if (argc < 2)
463 return errorArgument("Missing the filename argument!\n");
464 pszFilename = argv[1];
465
466 /* offDelta */
467 if (argc >= 3)
468 {
469 int irc = RTStrToInt64Ex(argv[2], NULL, 0, &offDelta);
470 if (RT_FAILURE(irc))
471 return errorArgument(argv[0], "Failed to read delta '%s', rc=%Rrc\n", argv[2], rc);
472 }
473
474 /* pszModule */
475 if (argc >= 4)
476 pszModule = argv[3];
477
478 /* ModuleAddress */
479 if (argc >= 5)
480 {
481 int irc = RTStrToUInt64Ex(argv[4], NULL, 0, &ModuleAddress);
482 if (RT_FAILURE(irc))
483 return errorArgument(argv[0], "Failed to read module address '%s', rc=%Rrc\n", argv[4], rc);
484 }
485
486 /* ModuleSize */
487 if (argc >= 6)
488 {
489 int irc = RTStrToUInt64Ex(argv[5], NULL, 0, &ModuleSize);
490 if (RT_FAILURE(irc))
491 return errorArgument(argv[0], "Failed to read module size '%s', rc=%Rrc\n", argv[5], rc);
492 }
493
494 /*
495 * Add extra data.
496 */
497 Utf8Str KeyStr;
498 HRESULT hrc = NewUniqueKey(machine, "VBoxInternal/DBGF/loadsyms", KeyStr);
499 if (SUCCEEDED(hrc))
500 hrc = SetString(machine, "VBoxInternal/DBGF/loadsyms", KeyStr.c_str(), "Filename", pszFilename);
501 if (SUCCEEDED(hrc) && argc >= 3)
502 hrc = SetInt64(machine, "VBoxInternal/DBGF/loadsyms", KeyStr.c_str(), "Delta", offDelta);
503 if (SUCCEEDED(hrc) && argc >= 4)
504 hrc = SetString(machine, "VBoxInternal/DBGF/loadsyms", KeyStr.c_str(), "Module", pszModule);
505 if (SUCCEEDED(hrc) && argc >= 5)
506 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadsyms", KeyStr.c_str(), "ModuleAddress", ModuleAddress);
507 if (SUCCEEDED(hrc) && argc >= 6)
508 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadsyms", KeyStr.c_str(), "ModuleSize", ModuleSize);
509
510 return FAILED(hrc);
511}
512
513
514static DECLCALLBACK(void) handleVDError(void *pvUser, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list va)
515{
516 RTMsgErrorV(pszFormat, va);
517 RTMsgError("Error code %Rrc at %s(%u) in function %s", rc, RT_SRC_POS_ARGS);
518}
519
520static int handleVDMessage(void *pvUser, const char *pszFormat, va_list va)
521{
522 NOREF(pvUser);
523 return RTPrintfV(pszFormat, va);
524}
525
526static int CmdSetHDUUID(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
527{
528 Guid uuid;
529 RTUUID rtuuid;
530 enum eUuidType {
531 HDUUID,
532 HDPARENTUUID
533 } uuidType;
534
535 if (!strcmp(argv[0], "sethduuid"))
536 {
537 uuidType = HDUUID;
538 if (argc != 3 && argc != 2)
539 return errorSyntax(USAGE_SETHDUUID, "Not enough parameters");
540 /* if specified, take UUID, otherwise generate a new one */
541 if (argc == 3)
542 {
543 if (RT_FAILURE(RTUuidFromStr(&rtuuid, argv[2])))
544 return errorSyntax(USAGE_SETHDUUID, "Invalid UUID parameter");
545 uuid = argv[2];
546 } else
547 uuid.create();
548 }
549 else if (!strcmp(argv[0], "sethdparentuuid"))
550 {
551 uuidType = HDPARENTUUID;
552 if (argc != 3)
553 return errorSyntax(USAGE_SETHDPARENTUUID, "Not enough parameters");
554 if (RT_FAILURE(RTUuidFromStr(&rtuuid, argv[2])))
555 return errorSyntax(USAGE_SETHDPARENTUUID, "Invalid UUID parameter");
556 uuid = argv[2];
557 }
558 else
559 return errorSyntax(USAGE_SETHDUUID, "Invalid invocation");
560
561 /* just try it */
562 char *pszFormat = NULL;
563 int rc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
564 argv[1], &pszFormat);
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, &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 int rc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
626 argv[0], &pszFormat);
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, &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("Cannnot 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 fRegister = false;
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 else if (strcmp(argv[i], "-register") == 0)
972 {
973 fRegister = true;
974 }
975#ifdef RT_OS_LINUX
976 else if (strcmp(argv[i], "-relative") == 0)
977 {
978 fRelative = true;
979 }
980#endif /* RT_OS_LINUX */
981 else
982 return errorSyntax(USAGE_CREATERAWVMDK, "Invalid parameter '%s'", argv[i]);
983 }
984
985 if (filename.isEmpty())
986 return errorSyntax(USAGE_CREATERAWVMDK, "Mandatory parameter -filename missing");
987 if (rawdisk.isEmpty())
988 return errorSyntax(USAGE_CREATERAWVMDK, "Mandatory parameter -rawdisk missing");
989 if (!pszPartitions && pszMBRFilename)
990 return errorSyntax(USAGE_CREATERAWVMDK, "The parameter -mbr is only valid when the parameter -partitions is also present");
991
992#ifdef RT_OS_DARWIN
993 fRelative = true;
994#endif /* RT_OS_DARWIN */
995 RTFILE RawFile;
996 int vrc = RTFileOpen(&RawFile, rawdisk.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
997 if (RT_FAILURE(vrc))
998 {
999 RTMsgError("Cannot open the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1000 goto out;
1001 }
1002
1003#ifdef RT_OS_WINDOWS
1004 /* Windows NT has no IOCTL_DISK_GET_LENGTH_INFORMATION ioctl. This was
1005 * added to Windows XP, so we have to use the available info from DriveGeo.
1006 * Note that we cannot simply use IOCTL_DISK_GET_DRIVE_GEOMETRY as it
1007 * yields a slightly different result than IOCTL_DISK_GET_LENGTH_INFO.
1008 * We call IOCTL_DISK_GET_DRIVE_GEOMETRY first as we need to check the media
1009 * type anyway, and if IOCTL_DISK_GET_LENGTH_INFORMATION is supported
1010 * we will later override cbSize.
1011 */
1012 DISK_GEOMETRY DriveGeo;
1013 DWORD cbDriveGeo;
1014 if (DeviceIoControl((HANDLE)RawFile,
1015 IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,
1016 &DriveGeo, sizeof(DriveGeo), &cbDriveGeo, NULL))
1017 {
1018 if ( DriveGeo.MediaType == FixedMedia
1019 || DriveGeo.MediaType == RemovableMedia)
1020 {
1021 cbSize = DriveGeo.Cylinders.QuadPart
1022 * DriveGeo.TracksPerCylinder
1023 * DriveGeo.SectorsPerTrack
1024 * DriveGeo.BytesPerSector;
1025 }
1026 else
1027 {
1028 RTMsgError("File '%s' is no fixed/removable medium device", rawdisk.c_str());
1029 vrc = VERR_INVALID_PARAMETER;
1030 goto out;
1031 }
1032
1033 GET_LENGTH_INFORMATION DiskLenInfo;
1034 DWORD junk;
1035 if (DeviceIoControl((HANDLE)RawFile,
1036 IOCTL_DISK_GET_LENGTH_INFO, NULL, 0,
1037 &DiskLenInfo, sizeof(DiskLenInfo), &junk, (LPOVERLAPPED)NULL))
1038 {
1039 /* IOCTL_DISK_GET_LENGTH_INFO is supported -- override cbSize. */
1040 cbSize = DiskLenInfo.Length.QuadPart;
1041 }
1042 }
1043 else
1044 {
1045 vrc = RTErrConvertFromWin32(GetLastError());
1046 RTMsgError("Cannot get the geometry of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1047 goto out;
1048 }
1049#elif defined(RT_OS_LINUX)
1050 struct stat DevStat;
1051 if (!fstat(RawFile, &DevStat) && S_ISBLK(DevStat.st_mode))
1052 {
1053#ifdef BLKGETSIZE64
1054 /* BLKGETSIZE64 is broken up to 2.4.17 and in many 2.5.x. In 2.6.0
1055 * it works without problems. */
1056 struct utsname utsname;
1057 if ( uname(&utsname) == 0
1058 && ( (strncmp(utsname.release, "2.5.", 4) == 0 && atoi(&utsname.release[4]) >= 18)
1059 || (strncmp(utsname.release, "2.", 2) == 0 && atoi(&utsname.release[2]) >= 6)))
1060 {
1061 uint64_t cbBlk;
1062 if (!ioctl(RawFile, BLKGETSIZE64, &cbBlk))
1063 cbSize = cbBlk;
1064 }
1065#endif /* BLKGETSIZE64 */
1066 if (!cbSize)
1067 {
1068 long cBlocks;
1069 if (!ioctl(RawFile, BLKGETSIZE, &cBlocks))
1070 cbSize = (uint64_t)cBlocks << 9;
1071 else
1072 {
1073 vrc = RTErrConvertFromErrno(errno);
1074 RTMsgError("Cannot get the size of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1075 goto out;
1076 }
1077 }
1078 }
1079 else
1080 {
1081 RTMsgError("File '%s' is no block device", rawdisk.c_str());
1082 vrc = VERR_INVALID_PARAMETER;
1083 goto out;
1084 }
1085#elif defined(RT_OS_DARWIN)
1086 struct stat DevStat;
1087 if (!fstat(RawFile, &DevStat) && S_ISBLK(DevStat.st_mode))
1088 {
1089 uint64_t cBlocks;
1090 uint32_t cbBlock;
1091 if (!ioctl(RawFile, DKIOCGETBLOCKCOUNT, &cBlocks))
1092 {
1093 if (!ioctl(RawFile, DKIOCGETBLOCKSIZE, &cbBlock))
1094 cbSize = cBlocks * cbBlock;
1095 else
1096 {
1097 RTMsgError("Cannot get the block size for file '%s': %Rrc", rawdisk.c_str(), vrc);
1098 vrc = RTErrConvertFromErrno(errno);
1099 goto out;
1100 }
1101 }
1102 else
1103 {
1104 vrc = RTErrConvertFromErrno(errno);
1105 RTMsgError("Cannot get the block count for file '%s': %Rrc", rawdisk.c_str(), vrc);
1106 goto out;
1107 }
1108 }
1109 else
1110 {
1111 RTMsgError("File '%s' is no block device", rawdisk.c_str());
1112 vrc = VERR_INVALID_PARAMETER;
1113 goto out;
1114 }
1115#elif defined(RT_OS_SOLARIS)
1116 struct stat DevStat;
1117 if (!fstat(RawFile, &DevStat) && ( S_ISBLK(DevStat.st_mode)
1118 || S_ISCHR(DevStat.st_mode)))
1119 {
1120 struct dk_minfo mediainfo;
1121 if (!ioctl(RawFile, DKIOCGMEDIAINFO, &mediainfo))
1122 cbSize = mediainfo.dki_capacity * mediainfo.dki_lbsize;
1123 else
1124 {
1125 vrc = RTErrConvertFromErrno(errno);
1126 RTMsgError("Cannot get the size of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1127 goto out;
1128 }
1129 }
1130 else
1131 {
1132 RTMsgError("File '%s' is no block or char device", rawdisk.c_str());
1133 vrc = VERR_INVALID_PARAMETER;
1134 goto out;
1135 }
1136#elif defined(RT_OS_FREEBSD)
1137 struct stat DevStat;
1138 if (!fstat(RawFile, &DevStat) && S_ISCHR(DevStat.st_mode))
1139 {
1140 off_t cbMedia = 0;
1141 if (!ioctl(RawFile, DIOCGMEDIASIZE, &cbMedia))
1142 {
1143 cbSize = cbMedia;
1144 }
1145 else
1146 {
1147 vrc = RTErrConvertFromErrno(errno);
1148 RTMsgError("Cannot get the block count for file '%s': %Rrc", rawdisk.c_str(), vrc);
1149 goto out;
1150 }
1151 }
1152 else
1153 {
1154 RTMsgError("File '%s' is no character device", rawdisk.c_str());
1155 vrc = VERR_INVALID_PARAMETER;
1156 goto out;
1157 }
1158#else /* all unrecognized OSes */
1159 /* Hopefully this works on all other hosts. If it doesn't, it'll just fail
1160 * creating the VMDK, so no real harm done. */
1161 vrc = RTFileGetSize(RawFile, &cbSize);
1162 if (RT_FAILURE(vrc))
1163 {
1164 RTMsgError("Cannot get the size of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1165 goto out;
1166 }
1167#endif
1168
1169 /* Check whether cbSize is actually sensible. */
1170 if (!cbSize || cbSize % 512)
1171 {
1172 RTMsgError("Detected size of raw disk '%s' is %s, an invalid value", rawdisk.c_str(), cbSize);
1173 vrc = VERR_INVALID_PARAMETER;
1174 goto out;
1175 }
1176
1177 RawDescriptor.szSignature[0] = 'R';
1178 RawDescriptor.szSignature[1] = 'A';
1179 RawDescriptor.szSignature[2] = 'W';
1180 RawDescriptor.szSignature[3] = '\0';
1181 if (!pszPartitions)
1182 {
1183 RawDescriptor.fRawDisk = true;
1184 RawDescriptor.pszRawDisk = rawdisk.c_str();
1185 }
1186 else
1187 {
1188 RawDescriptor.fRawDisk = false;
1189 RawDescriptor.pszRawDisk = NULL;
1190 RawDescriptor.cPartDescs = 0;
1191 RawDescriptor.pPartDescs = NULL;
1192
1193 uint32_t uPartitions = 0;
1194
1195 const char *p = pszPartitions;
1196 char *pszNext;
1197 uint32_t u32;
1198 while (*p != '\0')
1199 {
1200 vrc = RTStrToUInt32Ex(p, &pszNext, 0, &u32);
1201 if (RT_FAILURE(vrc))
1202 {
1203 RTMsgError("Incorrect value in partitions parameter");
1204 goto out;
1205 }
1206 uPartitions |= RT_BIT(u32);
1207 p = pszNext;
1208 if (*p == ',')
1209 p++;
1210 else if (*p != '\0')
1211 {
1212 RTMsgError("Incorrect separator in partitions parameter");
1213 vrc = VERR_INVALID_PARAMETER;
1214 goto out;
1215 }
1216 }
1217
1218 HOSTPARTITIONS partitions;
1219 vrc = partRead(RawFile, &partitions);
1220 if (RT_FAILURE(vrc))
1221 {
1222 RTMsgError("Cannot read the partition information from '%s'", rawdisk.c_str());
1223 goto out;
1224 }
1225
1226 for (unsigned i = 0; i < partitions.cPartitions; i++)
1227 {
1228 if ( uPartitions & RT_BIT(partitions.aPartitions[i].uIndex)
1229 && PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1230 {
1231 /* Some ignorant user specified an extended partition.
1232 * Bad idea, as this would trigger an overlapping
1233 * partitions error later during VMDK creation. So warn
1234 * here and ignore what the user requested. */
1235 RTMsgWarning("It is not possible (and necessary) to explicitly give access to the "
1236 "extended partition %u. If required, enable access to all logical "
1237 "partitions inside this extended partition.",
1238 partitions.aPartitions[i].uIndex);
1239 uPartitions &= ~RT_BIT(partitions.aPartitions[i].uIndex);
1240 }
1241 }
1242
1243 for (unsigned i = 0; i < partitions.cPartitions; i++)
1244 {
1245 PVBOXHDDRAWPARTDESC pPartDesc = NULL;
1246
1247 /* first dump the MBR/EPT data area */
1248 if (partitions.aPartitions[i].cPartDataSectors)
1249 {
1250 pPartDesc = appendPartDesc(&RawDescriptor.cPartDescs,
1251 &RawDescriptor.pPartDescs);
1252 if (!pPartDesc)
1253 {
1254 RTMsgError("Out of memory allocating the partition list for '%s'", rawdisk.c_str());
1255 vrc = VERR_NO_MEMORY;
1256 goto out;
1257 }
1258
1259 /** @todo the clipping below isn't 100% accurate, as it should
1260 * actually clip to the track size. However that's easier said
1261 * than done as figuring out the track size is heuristics. In
1262 * any case the clipping is adjusted later after sorting, to
1263 * prevent overlapping data areas on the resulting image. */
1264 pPartDesc->cbData = RT_MIN(partitions.aPartitions[i].cPartDataSectors, 63) * 512;
1265 pPartDesc->uStart = partitions.aPartitions[i].uPartDataStart * 512;
1266 Assert(pPartDesc->cbData - (size_t)pPartDesc->cbData == 0);
1267 void *pPartData = RTMemAlloc((size_t)pPartDesc->cbData);
1268 if (!pPartData)
1269 {
1270 RTMsgError("Out of memory allocating the partition descriptor for '%s'", rawdisk.c_str());
1271 vrc = VERR_NO_MEMORY;
1272 goto out;
1273 }
1274 vrc = RTFileReadAt(RawFile, partitions.aPartitions[i].uPartDataStart * 512,
1275 pPartData, (size_t)pPartDesc->cbData, NULL);
1276 if (RT_FAILURE(vrc))
1277 {
1278 RTMsgError("Cannot read partition data from raw device '%s': %Rrc", rawdisk.c_str(), vrc);
1279 goto out;
1280 }
1281 /* Splice in the replacement MBR code if specified. */
1282 if ( partitions.aPartitions[i].uPartDataStart == 0
1283 && pszMBRFilename)
1284 {
1285 RTFILE MBRFile;
1286 vrc = RTFileOpen(&MBRFile, pszMBRFilename, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1287 if (RT_FAILURE(vrc))
1288 {
1289 RTMsgError("Cannot open replacement MBR file '%s' specified with -mbr: %Rrc", pszMBRFilename, vrc);
1290 goto out;
1291 }
1292 vrc = RTFileReadAt(MBRFile, 0, pPartData, 0x1be, NULL);
1293 RTFileClose(MBRFile);
1294 if (RT_FAILURE(vrc))
1295 {
1296 RTMsgError("Cannot read replacement MBR file '%s': %Rrc", pszMBRFilename, vrc);
1297 goto out;
1298 }
1299 }
1300 pPartDesc->pvPartitionData = pPartData;
1301 }
1302
1303 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1304 {
1305 /* Suppress exporting the actual extended partition. Only
1306 * logical partitions should be processed. However completely
1307 * ignoring it leads to leaving out the EBR data. */
1308 continue;
1309 }
1310
1311 /* set up values for non-relative device names */
1312 const char *pszRawName = rawdisk.c_str();
1313 uint64_t uStartOffset = partitions.aPartitions[i].uStart * 512;
1314
1315 pPartDesc = appendPartDesc(&RawDescriptor.cPartDescs,
1316 &RawDescriptor.pPartDescs);
1317 if (!pPartDesc)
1318 {
1319 RTMsgError("Out of memory allocating the partition list for '%s'", rawdisk.c_str());
1320 vrc = VERR_NO_MEMORY;
1321 goto out;
1322 }
1323
1324 if (uPartitions & RT_BIT(partitions.aPartitions[i].uIndex))
1325 {
1326 if (fRelative)
1327 {
1328#ifdef RT_OS_LINUX
1329 /* Refer to the correct partition and use offset 0. */
1330 char *psz;
1331 vrc = RTStrAPrintf(&psz, "%s%u", rawdisk.c_str(),
1332 partitions.aPartitions[i].uIndex);
1333 if (RT_FAILURE(vrc))
1334 {
1335 RTMsgError("Cannot create reference to individual partition %u, rc=%Rrc",
1336 partitions.aPartitions[i].uIndex, vrc);
1337 goto out;
1338 }
1339 pszRawName = psz;
1340 uStartOffset = 0;
1341#elif defined(RT_OS_DARWIN)
1342 /* Refer to the correct partition and use offset 0. */
1343 char *psz;
1344 vrc = RTStrAPrintf(&psz, "%ss%u", rawdisk.c_str(),
1345 partitions.aPartitions[i].uIndex);
1346 if (RT_FAILURE(vrc))
1347 {
1348 RTMsgError("Cannot create reference to individual partition %u, rc=%Rrc",
1349 partitions.aPartitions[i].uIndex, vrc);
1350 goto out;
1351 }
1352 pszRawName = psz;
1353 uStartOffset = 0;
1354#else
1355 /** @todo not implemented for other hosts. Treat just like
1356 * not specified (this code is actually never reached). */
1357#endif
1358 }
1359
1360 pPartDesc->pszRawDevice = pszRawName;
1361 pPartDesc->uStartOffset = uStartOffset;
1362 }
1363 else
1364 {
1365 pPartDesc->pszRawDevice = NULL;
1366 pPartDesc->uStartOffset = 0;
1367 }
1368
1369 pPartDesc->uStart = partitions.aPartitions[i].uStart * 512;
1370 pPartDesc->cbData = partitions.aPartitions[i].uSize * 512;
1371 }
1372
1373 /* Sort data areas in ascending order of start. */
1374 for (unsigned i = 0; i < RawDescriptor.cPartDescs-1; i++)
1375 {
1376 unsigned uMinIdx = i;
1377 uint64_t uMinVal = RawDescriptor.pPartDescs[i].uStart;
1378 for (unsigned j = i + 1; j < RawDescriptor.cPartDescs; j++)
1379 {
1380 if (RawDescriptor.pPartDescs[j].uStart < uMinVal)
1381 {
1382 uMinIdx = j;
1383 uMinVal = RawDescriptor.pPartDescs[j].uStart;
1384 }
1385 }
1386 if (uMinIdx != i)
1387 {
1388 /* Swap entries at index i and uMinIdx. */
1389 VBOXHDDRAWPARTDESC tmp;
1390 memcpy(&tmp, &RawDescriptor.pPartDescs[i], sizeof(tmp));
1391 memcpy(&RawDescriptor.pPartDescs[i], &RawDescriptor.pPartDescs[uMinIdx], sizeof(tmp));
1392 memcpy(&RawDescriptor.pPartDescs[uMinIdx], &tmp, sizeof(tmp));
1393 }
1394 }
1395
1396 /* Have a second go at MBR/EPT area clipping. Now that the data areas
1397 * are sorted this is much easier to get 100% right. */
1398 for (unsigned i = 0; i < RawDescriptor.cPartDescs-1; i++)
1399 {
1400 if (RawDescriptor.pPartDescs[i].pvPartitionData)
1401 {
1402 RawDescriptor.pPartDescs[i].cbData = RT_MIN(RawDescriptor.pPartDescs[i+1].uStart - RawDescriptor.pPartDescs[i].uStart, RawDescriptor.pPartDescs[i].cbData);
1403 if (!RawDescriptor.pPartDescs[i].cbData)
1404 {
1405 RTMsgError("MBR/EPT overlaps with data area");
1406 vrc = VERR_INVALID_PARAMETER;
1407 goto out;
1408 }
1409 }
1410 }
1411 }
1412
1413 RTFileClose(RawFile);
1414
1415#ifdef DEBUG_klaus
1416 RTPrintf("# start length startoffset partdataptr device\n");
1417 for (unsigned i = 0; i < RawDescriptor.cPartDescs; i++)
1418 {
1419 RTPrintf("%2u %14RU64 %14RU64 %14RU64 %#18p %s\n", i,
1420 RawDescriptor.pPartDescs[i].uStart,
1421 RawDescriptor.pPartDescs[i].cbData,
1422 RawDescriptor.pPartDescs[i].uStartOffset,
1423 RawDescriptor.pPartDescs[i].pvPartitionData,
1424 RawDescriptor.pPartDescs[i].pszRawDevice);
1425 }
1426#endif
1427
1428 VDINTERFACE vdInterfaceError;
1429 VDINTERFACEERROR vdInterfaceErrorCallbacks;
1430 vdInterfaceErrorCallbacks.cbSize = sizeof(VDINTERFACEERROR);
1431 vdInterfaceErrorCallbacks.enmInterface = VDINTERFACETYPE_ERROR;
1432 vdInterfaceErrorCallbacks.pfnError = handleVDError;
1433 vdInterfaceErrorCallbacks.pfnMessage = handleVDMessage;
1434
1435 vrc = VDInterfaceAdd(&vdInterfaceError, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1436 &vdInterfaceErrorCallbacks, NULL, &pVDIfs);
1437 AssertRC(vrc);
1438
1439 vrc = VDCreate(pVDIfs, &pDisk);
1440 if (RT_FAILURE(vrc))
1441 {
1442 RTMsgError("Cannot create the virtual disk container: %Rrc", vrc);
1443 goto out;
1444 }
1445
1446 Assert(RT_MIN(cbSize / 512 / 16 / 63, 16383) -
1447 (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383) == 0);
1448 VDGEOMETRY PCHS, LCHS;
1449 PCHS.cCylinders = (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383);
1450 PCHS.cHeads = 16;
1451 PCHS.cSectors = 63;
1452 LCHS.cCylinders = 0;
1453 LCHS.cHeads = 0;
1454 LCHS.cSectors = 0;
1455 vrc = VDCreateBase(pDisk, "VMDK", filename.c_str(), cbSize,
1456 VD_IMAGE_FLAGS_FIXED | VD_VMDK_IMAGE_FLAGS_RAWDISK,
1457 (char *)&RawDescriptor, &PCHS, &LCHS, NULL,
1458 VD_OPEN_FLAGS_NORMAL, NULL, NULL);
1459 if (RT_FAILURE(vrc))
1460 {
1461 RTMsgError("Cannot create the raw disk VMDK: %Rrc", vrc);
1462 goto out;
1463 }
1464 RTPrintf("RAW host disk access VMDK file %s created successfully.\n", filename.c_str());
1465
1466 VDCloseAll(pDisk);
1467
1468 /* Clean up allocated memory etc. */
1469 if (pszPartitions)
1470 {
1471 for (unsigned i = 0; i < RawDescriptor.cPartDescs; i++)
1472 {
1473 /* Free memory allocated for relative device name. */
1474 if (fRelative && RawDescriptor.pPartDescs[i].pszRawDevice)
1475 RTStrFree((char *)(void *)RawDescriptor.pPartDescs[i].pszRawDevice);
1476 if (RawDescriptor.pPartDescs[i].pvPartitionData)
1477 RTMemFree((void *)RawDescriptor.pPartDescs[i].pvPartitionData);
1478 }
1479 if (RawDescriptor.pPartDescs)
1480 RTMemFree(RawDescriptor.pPartDescs);
1481 }
1482
1483 if (fRegister)
1484 {
1485 ComPtr<IMedium> hardDisk;
1486 CHECK_ERROR(aVirtualBox, OpenMedium(Bstr(filename).raw(),
1487 DeviceType_HardDisk,
1488 AccessMode_ReadWrite,
1489 hardDisk.asOutParam()));
1490 }
1491
1492 return SUCCEEDED(rc) ? 0 : 1;
1493
1494out:
1495 RTMsgError("The raw disk vmdk file was not created");
1496 return RT_SUCCESS(vrc) ? 0 : 1;
1497}
1498
1499static int CmdRenameVMDK(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1500{
1501 Utf8Str src;
1502 Utf8Str dst;
1503 /* Parse the arguments. */
1504 for (int i = 0; i < argc; i++)
1505 {
1506 if (strcmp(argv[i], "-from") == 0)
1507 {
1508 if (argc <= i + 1)
1509 {
1510 return errorArgument("Missing argument to '%s'", argv[i]);
1511 }
1512 i++;
1513 src = argv[i];
1514 }
1515 else if (strcmp(argv[i], "-to") == 0)
1516 {
1517 if (argc <= i + 1)
1518 {
1519 return errorArgument("Missing argument to '%s'", argv[i]);
1520 }
1521 i++;
1522 dst = argv[i];
1523 }
1524 else
1525 {
1526 return errorSyntax(USAGE_RENAMEVMDK, "Invalid parameter '%s'", argv[i]);
1527 }
1528 }
1529
1530 if (src.isEmpty())
1531 return errorSyntax(USAGE_RENAMEVMDK, "Mandatory parameter -from missing");
1532 if (dst.isEmpty())
1533 return errorSyntax(USAGE_RENAMEVMDK, "Mandatory parameter -to missing");
1534
1535 PVBOXHDD pDisk = NULL;
1536
1537 PVDINTERFACE pVDIfs = NULL;
1538 VDINTERFACE vdInterfaceError;
1539 VDINTERFACEERROR vdInterfaceErrorCallbacks;
1540 vdInterfaceErrorCallbacks.cbSize = sizeof(VDINTERFACEERROR);
1541 vdInterfaceErrorCallbacks.enmInterface = VDINTERFACETYPE_ERROR;
1542 vdInterfaceErrorCallbacks.pfnError = handleVDError;
1543 vdInterfaceErrorCallbacks.pfnMessage = handleVDMessage;
1544
1545 int vrc = VDInterfaceAdd(&vdInterfaceError, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1546 &vdInterfaceErrorCallbacks, NULL, &pVDIfs);
1547 AssertRC(vrc);
1548
1549 vrc = VDCreate(pVDIfs, &pDisk);
1550 if (RT_FAILURE(vrc))
1551 {
1552 RTMsgError("Cannot create the virtual disk container: %Rrc", vrc);
1553 return vrc;
1554 }
1555 else
1556 {
1557 vrc = VDOpen(pDisk, "VMDK", src.c_str(), VD_OPEN_FLAGS_NORMAL, NULL);
1558 if (RT_FAILURE(vrc))
1559 {
1560 RTMsgError("Cannot create the source image: %Rrc", vrc);
1561 }
1562 else
1563 {
1564 vrc = VDCopy(pDisk, 0, pDisk, "VMDK", dst.c_str(), true, 0,
1565 VD_IMAGE_FLAGS_NONE, NULL, VD_OPEN_FLAGS_NORMAL,
1566 NULL, NULL, NULL);
1567 if (RT_FAILURE(vrc))
1568 {
1569 RTMsgError("Cannot rename the image: %Rrc", vrc);
1570 }
1571 }
1572 }
1573 VDCloseAll(pDisk);
1574 return vrc;
1575}
1576
1577static int CmdConvertToRaw(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1578{
1579 Utf8Str srcformat;
1580 Utf8Str src;
1581 Utf8Str dst;
1582 bool fWriteToStdOut = false;
1583
1584 /* Parse the arguments. */
1585 for (int i = 0; i < argc; i++)
1586 {
1587 if (strcmp(argv[i], "-format") == 0)
1588 {
1589 if (argc <= i + 1)
1590 {
1591 return errorArgument("Missing argument to '%s'", argv[i]);
1592 }
1593 i++;
1594 srcformat = argv[i];
1595 }
1596 else if (src.isEmpty())
1597 {
1598 src = argv[i];
1599 }
1600 else if (dst.isEmpty())
1601 {
1602 dst = argv[i];
1603#ifdef ENABLE_CONVERT_RAW_TO_STDOUT
1604 if (!strcmp(argv[i], "stdout"))
1605 fWriteToStdOut = true;
1606#endif /* ENABLE_CONVERT_RAW_TO_STDOUT */
1607 }
1608 else
1609 {
1610 return errorSyntax(USAGE_CONVERTTORAW, "Invalid parameter '%s'", argv[i]);
1611 }
1612 }
1613
1614 if (src.isEmpty())
1615 return errorSyntax(USAGE_CONVERTTORAW, "Mandatory filename parameter missing");
1616 if (dst.isEmpty())
1617 return errorSyntax(USAGE_CONVERTTORAW, "Mandatory outputfile parameter missing");
1618
1619 PVBOXHDD pDisk = NULL;
1620
1621 PVDINTERFACE pVDIfs = NULL;
1622 VDINTERFACE vdInterfaceError;
1623 VDINTERFACEERROR vdInterfaceErrorCallbacks;
1624 vdInterfaceErrorCallbacks.cbSize = sizeof(VDINTERFACEERROR);
1625 vdInterfaceErrorCallbacks.enmInterface = VDINTERFACETYPE_ERROR;
1626 vdInterfaceErrorCallbacks.pfnError = handleVDError;
1627 vdInterfaceErrorCallbacks.pfnMessage = handleVDMessage;
1628
1629 int vrc = VDInterfaceAdd(&vdInterfaceError, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1630 &vdInterfaceErrorCallbacks, NULL, &pVDIfs);
1631 AssertRC(vrc);
1632
1633 vrc = VDCreate(pVDIfs, &pDisk);
1634 if (RT_FAILURE(vrc))
1635 {
1636 RTMsgError("Cannot create the virtual disk container: %Rrc", vrc);
1637 return 1;
1638 }
1639
1640 /* Open raw output file. */
1641 RTFILE outFile;
1642 vrc = VINF_SUCCESS;
1643 if (fWriteToStdOut)
1644 outFile = 1;
1645 else
1646 vrc = RTFileOpen(&outFile, dst.c_str(), RTFILE_O_WRITE | RTFILE_O_CREATE | RTFILE_O_DENY_ALL);
1647 if (RT_FAILURE(vrc))
1648 {
1649 VDCloseAll(pDisk);
1650 RTMsgError("Cannot create destination file \"%s\": %Rrc", dst.c_str(), vrc);
1651 return 1;
1652 }
1653
1654 if (srcformat.isEmpty())
1655 {
1656 char *pszFormat = NULL;
1657 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
1658 src.c_str(), &pszFormat);
1659 if (RT_FAILURE(vrc))
1660 {
1661 VDCloseAll(pDisk);
1662 if (!fWriteToStdOut)
1663 {
1664 RTFileClose(outFile);
1665 RTFileDelete(dst.c_str());
1666 }
1667 RTMsgError("No file format specified and autodetect failed - please specify format: %Rrc", vrc);
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
1746 /* Parse the arguments. */
1747 for (int i = 0; i < argc; i++)
1748 {
1749 if (strcmp(argv[i], "-srcformat") == 0)
1750 {
1751 if (argc <= i + 1)
1752 {
1753 return errorArgument("Missing argument to '%s'", argv[i]);
1754 }
1755 i++;
1756 srcformat = argv[i];
1757 }
1758 else if (strcmp(argv[i], "-dstformat") == 0)
1759 {
1760 if (argc <= i + 1)
1761 {
1762 return errorArgument("Missing argument to '%s'", argv[i]);
1763 }
1764 i++;
1765 dstformat = argv[i];
1766 }
1767 else if (src.isEmpty())
1768 {
1769 src = argv[i];
1770 }
1771 else if (dst.isEmpty())
1772 {
1773 dst = argv[i];
1774 }
1775 else
1776 {
1777 return errorSyntax(USAGE_CONVERTHD, "Invalid parameter '%s'", argv[i]);
1778 }
1779 }
1780
1781 if (src.isEmpty())
1782 return errorSyntax(USAGE_CONVERTHD, "Mandatory input image parameter missing");
1783 if (dst.isEmpty())
1784 return errorSyntax(USAGE_CONVERTHD, "Mandatory output image parameter missing");
1785
1786
1787 PVDINTERFACE pVDIfs = NULL;
1788 VDINTERFACE vdInterfaceError;
1789 VDINTERFACEERROR vdInterfaceErrorCallbacks;
1790 vdInterfaceErrorCallbacks.cbSize = sizeof(VDINTERFACEERROR);
1791 vdInterfaceErrorCallbacks.enmInterface = VDINTERFACETYPE_ERROR;
1792 vdInterfaceErrorCallbacks.pfnError = handleVDError;
1793 vdInterfaceErrorCallbacks.pfnMessage = handleVDMessage;
1794
1795 vrc = VDInterfaceAdd(&vdInterfaceError, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1796 &vdInterfaceErrorCallbacks, NULL, &pVDIfs);
1797 AssertRC(vrc);
1798
1799 do
1800 {
1801 /* Try to determine input image format */
1802 if (srcformat.isEmpty())
1803 {
1804 char *pszFormat = NULL;
1805 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
1806 src.c_str(), &pszFormat);
1807 if (RT_FAILURE(vrc))
1808 {
1809 RTMsgError("No file format specified and autodetect failed - please specify format: %Rrc", vrc);
1810 break;
1811 }
1812 srcformat = pszFormat;
1813 RTStrFree(pszFormat);
1814 }
1815
1816 vrc = VDCreate(pVDIfs, &pSrcDisk);
1817 if (RT_FAILURE(vrc))
1818 {
1819 RTMsgError("Cannot create the source virtual disk container: %Rrc", vrc);
1820 break;
1821 }
1822
1823 /* Open the input image */
1824 vrc = VDOpen(pSrcDisk, srcformat.c_str(), src.c_str(), VD_OPEN_FLAGS_READONLY, NULL);
1825 if (RT_FAILURE(vrc))
1826 {
1827 RTMsgError("Cannot open the source image: %Rrc", vrc);
1828 break;
1829 }
1830
1831 /* Output format defaults to VDI */
1832 if (dstformat.isEmpty())
1833 dstformat = "VDI";
1834
1835 vrc = VDCreate(pVDIfs, &pDstDisk);
1836 if (RT_FAILURE(vrc))
1837 {
1838 RTMsgError("Cannot create the destination virtual disk container: %Rrc", vrc);
1839 break;
1840 }
1841
1842 uint64_t cbSize = VDGetSize(pSrcDisk, VD_LAST_IMAGE);
1843 RTStrmPrintf(g_pStdErr, "Converting image \"%s\" with size %RU64 bytes (%RU64MB)...\n", src.c_str(), cbSize, (cbSize + _1M - 1) / _1M);
1844
1845 /* Create the output image */
1846 vrc = VDCopy(pSrcDisk, VD_LAST_IMAGE, pDstDisk, dstformat.c_str(),
1847 dst.c_str(), false, 0, VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED,
1848 NULL, VD_OPEN_FLAGS_NORMAL, NULL, NULL, NULL);
1849 if (RT_FAILURE(vrc))
1850 {
1851 RTMsgError("Cannot copy the image: %Rrc", vrc);
1852 break;
1853 }
1854 }
1855 while (0);
1856 if (pDstDisk)
1857 VDCloseAll(pDstDisk);
1858 if (pSrcDisk)
1859 VDCloseAll(pSrcDisk);
1860
1861 return RT_SUCCESS(vrc) ? 0 : 1;
1862}
1863
1864/**
1865 * Unloads the neccessary driver.
1866 *
1867 * @returns VBox status code
1868 */
1869int CmdModUninstall(void)
1870{
1871 int rc;
1872
1873 rc = SUPR3Uninstall();
1874 if (RT_SUCCESS(rc))
1875 return 0;
1876 if (rc == VERR_NOT_IMPLEMENTED)
1877 return 0;
1878 return E_FAIL;
1879}
1880
1881/**
1882 * Loads the neccessary driver.
1883 *
1884 * @returns VBox status code
1885 */
1886int CmdModInstall(void)
1887{
1888 int rc;
1889
1890 rc = SUPR3Install();
1891 if (RT_SUCCESS(rc))
1892 return 0;
1893 if (rc == VERR_NOT_IMPLEMENTED)
1894 return 0;
1895 return E_FAIL;
1896}
1897
1898int CmdDebugLog(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1899{
1900 /*
1901 * The first parameter is the name or UUID of a VM with a direct session
1902 * that we wish to open.
1903 */
1904 if (argc < 1)
1905 return errorSyntax(USAGE_DEBUGLOG, "Missing VM name/UUID");
1906
1907 ComPtr<IMachine> ptrMachine;
1908 HRESULT rc = aVirtualBox->GetMachine(Bstr(argv[0]).raw(),
1909 ptrMachine.asOutParam());
1910 if (FAILED(rc) || ptrMachine.isNull())
1911 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
1912 ptrMachine.asOutParam()), 1);
1913
1914 CHECK_ERROR_RET(ptrMachine, LockMachine(aSession, LockType_Shared), 1);
1915
1916 /*
1917 * Get the debugger interface.
1918 */
1919 ComPtr<IConsole> ptrConsole;
1920 CHECK_ERROR_RET(aSession, COMGETTER(Console)(ptrConsole.asOutParam()), 1);
1921
1922 ComPtr<IMachineDebugger> ptrDebugger;
1923 CHECK_ERROR_RET(ptrConsole, COMGETTER(Debugger)(ptrDebugger.asOutParam()), 1);
1924
1925 /*
1926 * Parse the command.
1927 */
1928 bool fEnablePresent = false;
1929 bool fEnable = false;
1930 bool fFlagsPresent = false;
1931 iprt::MiniString strFlags;
1932 bool fGroupsPresent = false;
1933 iprt::MiniString strGroups;
1934 bool fDestsPresent = false;
1935 iprt::MiniString strDests;
1936
1937 static const RTGETOPTDEF s_aOptions[] =
1938 {
1939 { "--disable", 'E', RTGETOPT_REQ_NOTHING },
1940 { "--enable", 'e', RTGETOPT_REQ_NOTHING },
1941 { "--flags", 'f', RTGETOPT_REQ_STRING },
1942 { "--groups", 'g', RTGETOPT_REQ_STRING },
1943 { "--destinations", 'd', RTGETOPT_REQ_STRING }
1944 };
1945
1946 int ch;
1947 RTGETOPTUNION ValueUnion;
1948 RTGETOPTSTATE GetState;
1949 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
1950 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1951 {
1952 switch (ch)
1953 {
1954 case 'e':
1955 fEnablePresent = true;
1956 fEnable = true;
1957 break;
1958
1959 case 'E':
1960 fEnablePresent = true;
1961 fEnable = false;
1962 break;
1963
1964 case 'f':
1965 fFlagsPresent = true;
1966 if (*ValueUnion.psz)
1967 {
1968 if (strFlags.isNotEmpty())
1969 strFlags.append(' ');
1970 strFlags.append(ValueUnion.psz);
1971 }
1972 break;
1973
1974 case 'g':
1975 fGroupsPresent = true;
1976 if (*ValueUnion.psz)
1977 {
1978 if (strGroups.isNotEmpty())
1979 strGroups.append(' ');
1980 strGroups.append(ValueUnion.psz);
1981 }
1982 break;
1983
1984 case 'd':
1985 fDestsPresent = true;
1986 if (*ValueUnion.psz)
1987 {
1988 if (strDests.isNotEmpty())
1989 strDests.append(' ');
1990 strDests.append(ValueUnion.psz);
1991 }
1992 break;
1993
1994 default:
1995 return errorGetOpt(USAGE_DEBUGLOG , ch, &ValueUnion);
1996 }
1997 }
1998
1999 /*
2000 * Do the job.
2001 */
2002 if (fEnablePresent && !fEnable)
2003 CHECK_ERROR_RET(ptrDebugger, COMSETTER(LogEnabled)(FALSE), 1);
2004
2005 /** @todo flags, groups destination. */
2006 if (fFlagsPresent || fGroupsPresent || fDestsPresent)
2007 RTMsgWarning("One or more of the requested features are not implemented! Feel free to do this.");
2008
2009 if (fEnablePresent && fEnable)
2010 CHECK_ERROR_RET(ptrDebugger, COMSETTER(LogEnabled)(TRUE), 1);
2011 return 0;
2012}
2013
2014/**
2015 * Generate a SHA-256 password hash
2016 */
2017int CmdGeneratePasswordHash(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2018{
2019 /* one parameter, the password to hash */
2020 if (argc != 1)
2021 return errorSyntax(USAGE_PASSWORDHASH, "password to hash required");
2022
2023 uint8_t abDigest[RTSHA256_HASH_SIZE];
2024 RTSha256(argv[0], strlen(argv[0]), abDigest);
2025 char pszDigest[RTSHA256_DIGEST_LEN + 1];
2026 RTSha256ToString(abDigest, pszDigest, sizeof(pszDigest));
2027 RTPrintf("Password hash: %s\n", pszDigest);
2028
2029 return 0;
2030}
2031
2032/**
2033 * Wrapper for handling internal commands
2034 */
2035int handleInternalCommands(HandlerArg *a)
2036{
2037 g_fInternalMode = true;
2038
2039 /* at least a command is required */
2040 if (a->argc < 1)
2041 return errorSyntax(USAGE_ALL, "Command missing");
2042
2043 /*
2044 * The 'string switch' on command name.
2045 */
2046 const char *pszCmd = a->argv[0];
2047 if (!strcmp(pszCmd, "loadsyms"))
2048 return CmdLoadSyms(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2049 //if (!strcmp(pszCmd, "unloadsyms"))
2050 // return CmdUnloadSyms(argc - 1 , &a->argv[1]);
2051 if (!strcmp(pszCmd, "sethduuid") || !strcmp(pszCmd, "sethdparentuuid"))
2052 return CmdSetHDUUID(a->argc, &a->argv[0], a->virtualBox, a->session);
2053 if (!strcmp(pszCmd, "dumphdinfo"))
2054 return CmdDumpHDInfo(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2055 if (!strcmp(pszCmd, "listpartitions"))
2056 return CmdListPartitions(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2057 if (!strcmp(pszCmd, "createrawvmdk"))
2058 return CmdCreateRawVMDK(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2059 if (!strcmp(pszCmd, "renamevmdk"))
2060 return CmdRenameVMDK(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2061 if (!strcmp(pszCmd, "converttoraw"))
2062 return CmdConvertToRaw(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2063 if (!strcmp(pszCmd, "converthd"))
2064 return CmdConvertHardDisk(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2065 if (!strcmp(pszCmd, "modinstall"))
2066 return CmdModInstall();
2067 if (!strcmp(pszCmd, "moduninstall"))
2068 return CmdModUninstall();
2069 if (!strcmp(pszCmd, "debuglog"))
2070 return CmdDebugLog(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2071 if (!strcmp(pszCmd, "passwordhash"))
2072 return CmdGeneratePasswordHash(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2073
2074 /* default: */
2075 return errorSyntax(USAGE_ALL, "Invalid command '%s'", a->argv[0]);
2076}
2077
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