VirtualBox

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

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

Main/Medium+MediumFormat+GuestOSType+SystemPropertiesImpl+Console+Global: consistently use bytes as size units, forgotten const value in API, MaxVDISize method renamed to InfoVDSize, STDMETHOD macro usage fixes, whitespace cleanup

Frontends/VirtualBox+VBoxManage+VBoxShell: adapt to changed disk size units

Main/StorageControllerImpl: check the storage controller instance limit to avoid creating unusable VM configs, simplify unnecessarily complex code for querying the controller properties

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