VirtualBox

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

Last change on this file since 30734 was 30321, checked in by vboxsync, 15 years ago

VBoxInternalManage.cpp: Copy & past in debuglog.

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