VirtualBox

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

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

src/*: more spelling fixes (logging), thanks Timeless!

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