VirtualBox

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

Last change on this file since 39905 was 39660, checked in by vboxsync, 13 years ago

FE/VBoxManage: Add support for raw image files in createrawvmdk (based on a patch from Pawel Jakub Dawidek)

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