VirtualBox

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

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

FE/VBoxManage: New internal command to repair dis images

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 75.9 KB
Line 
1/* $Id: VBoxInternalManage.cpp 39576 2011-12-10 20:34:39Z 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.215389.xyz. 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 vrc = RTErrConvertFromWin32(GetLastError());
1119 RTMsgError("Cannot get the geometry of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1120 goto out;
1121 }
1122#elif defined(RT_OS_LINUX)
1123 struct stat DevStat;
1124 if (!fstat(RTFileToNative(hRawFile), &DevStat) && S_ISBLK(DevStat.st_mode))
1125 {
1126#ifdef BLKGETSIZE64
1127 /* BLKGETSIZE64 is broken up to 2.4.17 and in many 2.5.x. In 2.6.0
1128 * it works without problems. */
1129 struct utsname utsname;
1130 if ( uname(&utsname) == 0
1131 && ( (strncmp(utsname.release, "2.5.", 4) == 0 && atoi(&utsname.release[4]) >= 18)
1132 || (strncmp(utsname.release, "2.", 2) == 0 && atoi(&utsname.release[2]) >= 6)))
1133 {
1134 uint64_t cbBlk;
1135 if (!ioctl(RTFileToNative(hRawFile), BLKGETSIZE64, &cbBlk))
1136 cbSize = cbBlk;
1137 }
1138#endif /* BLKGETSIZE64 */
1139 if (!cbSize)
1140 {
1141 long cBlocks;
1142 if (!ioctl(RTFileToNative(hRawFile), BLKGETSIZE, &cBlocks))
1143 cbSize = (uint64_t)cBlocks << 9;
1144 else
1145 {
1146 vrc = RTErrConvertFromErrno(errno);
1147 RTMsgError("Cannot get the size of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1148 goto out;
1149 }
1150 }
1151 }
1152 else
1153 {
1154 RTMsgError("File '%s' is no block device", rawdisk.c_str());
1155 vrc = VERR_INVALID_PARAMETER;
1156 goto out;
1157 }
1158#elif defined(RT_OS_DARWIN)
1159 struct stat DevStat;
1160 if (!fstat(RTFileToNative(hRawFile), &DevStat) && S_ISBLK(DevStat.st_mode))
1161 {
1162 uint64_t cBlocks;
1163 uint32_t cbBlock;
1164 if (!ioctl(RTFileToNative(hRawFile), DKIOCGETBLOCKCOUNT, &cBlocks))
1165 {
1166 if (!ioctl(RTFileToNative(hRawFile), DKIOCGETBLOCKSIZE, &cbBlock))
1167 cbSize = cBlocks * cbBlock;
1168 else
1169 {
1170 RTMsgError("Cannot get the block size for file '%s': %Rrc", rawdisk.c_str(), vrc);
1171 vrc = RTErrConvertFromErrno(errno);
1172 goto out;
1173 }
1174 }
1175 else
1176 {
1177 vrc = RTErrConvertFromErrno(errno);
1178 RTMsgError("Cannot get the block count for file '%s': %Rrc", rawdisk.c_str(), vrc);
1179 goto out;
1180 }
1181 }
1182 else
1183 {
1184 RTMsgError("File '%s' is no block device", rawdisk.c_str());
1185 vrc = VERR_INVALID_PARAMETER;
1186 goto out;
1187 }
1188#elif defined(RT_OS_SOLARIS)
1189 struct stat DevStat;
1190 if (!fstat(RTFileToNative(hRawFile), &DevStat) && ( S_ISBLK(DevStat.st_mode)
1191 || S_ISCHR(DevStat.st_mode)))
1192 {
1193 struct dk_minfo mediainfo;
1194 if (!ioctl(RTFileToNative(hRawFile), DKIOCGMEDIAINFO, &mediainfo))
1195 cbSize = mediainfo.dki_capacity * mediainfo.dki_lbsize;
1196 else
1197 {
1198 vrc = RTErrConvertFromErrno(errno);
1199 RTMsgError("Cannot get the size of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1200 goto out;
1201 }
1202 }
1203 else
1204 {
1205 RTMsgError("File '%s' is no block or char device", rawdisk.c_str());
1206 vrc = VERR_INVALID_PARAMETER;
1207 goto out;
1208 }
1209#elif defined(RT_OS_FREEBSD)
1210 struct stat DevStat;
1211 if (!fstat(RTFileToNative(hRawFile), &DevStat) && S_ISCHR(DevStat.st_mode))
1212 {
1213 off_t cbMedia = 0;
1214 if (!ioctl(RTFileToNative(hRawFile), DIOCGMEDIASIZE, &cbMedia))
1215 {
1216 cbSize = cbMedia;
1217 }
1218 else
1219 {
1220 vrc = RTErrConvertFromErrno(errno);
1221 RTMsgError("Cannot get the block count for file '%s': %Rrc", rawdisk.c_str(), vrc);
1222 goto out;
1223 }
1224 }
1225 else
1226 {
1227 RTMsgError("File '%s' is no character device", rawdisk.c_str());
1228 vrc = VERR_INVALID_PARAMETER;
1229 goto out;
1230 }
1231#else /* all unrecognized OSes */
1232 /* Hopefully this works on all other hosts. If it doesn't, it'll just fail
1233 * creating the VMDK, so no real harm done. */
1234 vrc = RTFileGetSize(hRawFile, &cbSize);
1235 if (RT_FAILURE(vrc))
1236 {
1237 RTMsgError("Cannot get the size of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1238 goto out;
1239 }
1240#endif
1241
1242 /* Check whether cbSize is actually sensible. */
1243 if (!cbSize || cbSize % 512)
1244 {
1245 RTMsgError("Detected size of raw disk '%s' is %s, an invalid value", rawdisk.c_str(), cbSize);
1246 vrc = VERR_INVALID_PARAMETER;
1247 goto out;
1248 }
1249
1250 RawDescriptor.szSignature[0] = 'R';
1251 RawDescriptor.szSignature[1] = 'A';
1252 RawDescriptor.szSignature[2] = 'W';
1253 RawDescriptor.szSignature[3] = '\0';
1254 if (!pszPartitions)
1255 {
1256 RawDescriptor.fRawDisk = true;
1257 RawDescriptor.pszRawDisk = rawdisk.c_str();
1258 }
1259 else
1260 {
1261 RawDescriptor.fRawDisk = false;
1262 RawDescriptor.pszRawDisk = NULL;
1263 RawDescriptor.cPartDescs = 0;
1264 RawDescriptor.pPartDescs = NULL;
1265
1266 uint32_t uPartitions = 0;
1267
1268 const char *p = pszPartitions;
1269 char *pszNext;
1270 uint32_t u32;
1271 while (*p != '\0')
1272 {
1273 vrc = RTStrToUInt32Ex(p, &pszNext, 0, &u32);
1274 if (RT_FAILURE(vrc))
1275 {
1276 RTMsgError("Incorrect value in partitions parameter");
1277 goto out;
1278 }
1279 uPartitions |= RT_BIT(u32);
1280 p = pszNext;
1281 if (*p == ',')
1282 p++;
1283 else if (*p != '\0')
1284 {
1285 RTMsgError("Incorrect separator in partitions parameter");
1286 vrc = VERR_INVALID_PARAMETER;
1287 goto out;
1288 }
1289 }
1290
1291 HOSTPARTITIONS partitions;
1292 vrc = partRead(hRawFile, &partitions);
1293 if (RT_FAILURE(vrc))
1294 {
1295 RTMsgError("Cannot read the partition information from '%s'", rawdisk.c_str());
1296 goto out;
1297 }
1298
1299 for (unsigned i = 0; i < partitions.cPartitions; i++)
1300 {
1301 if ( uPartitions & RT_BIT(partitions.aPartitions[i].uIndex)
1302 && PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1303 {
1304 /* Some ignorant user specified an extended partition.
1305 * Bad idea, as this would trigger an overlapping
1306 * partitions error later during VMDK creation. So warn
1307 * here and ignore what the user requested. */
1308 RTMsgWarning("It is not possible (and necessary) to explicitly give access to the "
1309 "extended partition %u. If required, enable access to all logical "
1310 "partitions inside this extended partition.",
1311 partitions.aPartitions[i].uIndex);
1312 uPartitions &= ~RT_BIT(partitions.aPartitions[i].uIndex);
1313 }
1314 }
1315
1316 for (unsigned i = 0; i < partitions.cPartitions; i++)
1317 {
1318 PVBOXHDDRAWPARTDESC pPartDesc = NULL;
1319
1320 /* first dump the MBR/EPT data area */
1321 if (partitions.aPartitions[i].cPartDataSectors)
1322 {
1323 pPartDesc = appendPartDesc(&RawDescriptor.cPartDescs,
1324 &RawDescriptor.pPartDescs);
1325 if (!pPartDesc)
1326 {
1327 RTMsgError("Out of memory allocating the partition list for '%s'", rawdisk.c_str());
1328 vrc = VERR_NO_MEMORY;
1329 goto out;
1330 }
1331
1332 /** @todo the clipping below isn't 100% accurate, as it should
1333 * actually clip to the track size. However, that's easier said
1334 * than done as figuring out the track size is heuristics. In
1335 * any case the clipping is adjusted later after sorting, to
1336 * prevent overlapping data areas on the resulting image. */
1337 pPartDesc->cbData = RT_MIN(partitions.aPartitions[i].cPartDataSectors, 63) * 512;
1338 pPartDesc->uStart = partitions.aPartitions[i].uPartDataStart * 512;
1339 Assert(pPartDesc->cbData - (size_t)pPartDesc->cbData == 0);
1340 void *pPartData = RTMemAlloc((size_t)pPartDesc->cbData);
1341 if (!pPartData)
1342 {
1343 RTMsgError("Out of memory allocating the partition descriptor for '%s'", rawdisk.c_str());
1344 vrc = VERR_NO_MEMORY;
1345 goto out;
1346 }
1347 vrc = RTFileReadAt(hRawFile, partitions.aPartitions[i].uPartDataStart * 512,
1348 pPartData, (size_t)pPartDesc->cbData, NULL);
1349 if (RT_FAILURE(vrc))
1350 {
1351 RTMsgError("Cannot read partition data from raw device '%s': %Rrc", rawdisk.c_str(), vrc);
1352 goto out;
1353 }
1354 /* Splice in the replacement MBR code if specified. */
1355 if ( partitions.aPartitions[i].uPartDataStart == 0
1356 && pszMBRFilename)
1357 {
1358 RTFILE MBRFile;
1359 vrc = RTFileOpen(&MBRFile, pszMBRFilename, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1360 if (RT_FAILURE(vrc))
1361 {
1362 RTMsgError("Cannot open replacement MBR file '%s' specified with -mbr: %Rrc", pszMBRFilename, vrc);
1363 goto out;
1364 }
1365 vrc = RTFileReadAt(MBRFile, 0, pPartData, 0x1be, NULL);
1366 RTFileClose(MBRFile);
1367 if (RT_FAILURE(vrc))
1368 {
1369 RTMsgError("Cannot read replacement MBR file '%s': %Rrc", pszMBRFilename, vrc);
1370 goto out;
1371 }
1372 }
1373 pPartDesc->pvPartitionData = pPartData;
1374 }
1375
1376 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1377 {
1378 /* Suppress exporting the actual extended partition. Only
1379 * logical partitions should be processed. However completely
1380 * ignoring it leads to leaving out the EBR data. */
1381 continue;
1382 }
1383
1384 /* set up values for non-relative device names */
1385 const char *pszRawName = rawdisk.c_str();
1386 uint64_t uStartOffset = partitions.aPartitions[i].uStart * 512;
1387
1388 pPartDesc = appendPartDesc(&RawDescriptor.cPartDescs,
1389 &RawDescriptor.pPartDescs);
1390 if (!pPartDesc)
1391 {
1392 RTMsgError("Out of memory allocating the partition list for '%s'", rawdisk.c_str());
1393 vrc = VERR_NO_MEMORY;
1394 goto out;
1395 }
1396
1397 if (uPartitions & RT_BIT(partitions.aPartitions[i].uIndex))
1398 {
1399 if (fRelative)
1400 {
1401#if defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
1402 /* Refer to the correct partition and use offset 0. */
1403 char *psz;
1404 RTStrAPrintf(&psz,
1405#if defined(RT_OS_LINUX)
1406 "%s%u",
1407#elif defined(RT_OS_FREEBSD)
1408 "%ss%u",
1409#endif
1410 rawdisk.c_str(),
1411 partitions.aPartitions[i].uIndex);
1412 if (!psz)
1413 {
1414 vrc = VERR_NO_STR_MEMORY;
1415 RTMsgError("Cannot create reference to individual partition %u, rc=%Rrc",
1416 partitions.aPartitions[i].uIndex, vrc);
1417 goto out;
1418 }
1419 pszRawName = psz;
1420 uStartOffset = 0;
1421#elif defined(RT_OS_DARWIN)
1422 /* Refer to the correct partition and use offset 0. */
1423 char *psz;
1424 RTStrAPrintf(&psz, "%ss%u", rawdisk.c_str(),
1425 partitions.aPartitions[i].uIndex);
1426 if (!psz)
1427 {
1428 vrc = VERR_NO_STR_MEMORY;
1429 RTMsgError("Cannot create reference to individual partition %u, rc=%Rrc",
1430 partitions.aPartitions[i].uIndex, vrc);
1431 goto out;
1432 }
1433 pszRawName = psz;
1434 uStartOffset = 0;
1435#else
1436 /** @todo not implemented for other hosts. Treat just like
1437 * not specified (this code is actually never reached). */
1438#endif
1439 }
1440
1441 pPartDesc->pszRawDevice = pszRawName;
1442 pPartDesc->uStartOffset = uStartOffset;
1443 }
1444 else
1445 {
1446 pPartDesc->pszRawDevice = NULL;
1447 pPartDesc->uStartOffset = 0;
1448 }
1449
1450 pPartDesc->uStart = partitions.aPartitions[i].uStart * 512;
1451 pPartDesc->cbData = partitions.aPartitions[i].uSize * 512;
1452 }
1453
1454 /* Sort data areas in ascending order of start. */
1455 for (unsigned i = 0; i < RawDescriptor.cPartDescs-1; i++)
1456 {
1457 unsigned uMinIdx = i;
1458 uint64_t uMinVal = RawDescriptor.pPartDescs[i].uStart;
1459 for (unsigned j = i + 1; j < RawDescriptor.cPartDescs; j++)
1460 {
1461 if (RawDescriptor.pPartDescs[j].uStart < uMinVal)
1462 {
1463 uMinIdx = j;
1464 uMinVal = RawDescriptor.pPartDescs[j].uStart;
1465 }
1466 }
1467 if (uMinIdx != i)
1468 {
1469 /* Swap entries at index i and uMinIdx. */
1470 VBOXHDDRAWPARTDESC tmp;
1471 memcpy(&tmp, &RawDescriptor.pPartDescs[i], sizeof(tmp));
1472 memcpy(&RawDescriptor.pPartDescs[i], &RawDescriptor.pPartDescs[uMinIdx], sizeof(tmp));
1473 memcpy(&RawDescriptor.pPartDescs[uMinIdx], &tmp, sizeof(tmp));
1474 }
1475 }
1476
1477 /* Have a second go at MBR/EPT area clipping. Now that the data areas
1478 * are sorted this is much easier to get 100% right. */
1479 for (unsigned i = 0; i < RawDescriptor.cPartDescs-1; i++)
1480 {
1481 if (RawDescriptor.pPartDescs[i].pvPartitionData)
1482 {
1483 RawDescriptor.pPartDescs[i].cbData = RT_MIN(RawDescriptor.pPartDescs[i+1].uStart - RawDescriptor.pPartDescs[i].uStart, RawDescriptor.pPartDescs[i].cbData);
1484 if (!RawDescriptor.pPartDescs[i].cbData)
1485 {
1486 RTMsgError("MBR/EPT overlaps with data area");
1487 vrc = VERR_INVALID_PARAMETER;
1488 goto out;
1489 }
1490 }
1491 }
1492 }
1493
1494 RTFileClose(hRawFile);
1495
1496#ifdef DEBUG_klaus
1497 RTPrintf("# start length startoffset partdataptr device\n");
1498 for (unsigned i = 0; i < RawDescriptor.cPartDescs; i++)
1499 {
1500 RTPrintf("%2u %14RU64 %14RU64 %14RU64 %#18p %s\n", i,
1501 RawDescriptor.pPartDescs[i].uStart,
1502 RawDescriptor.pPartDescs[i].cbData,
1503 RawDescriptor.pPartDescs[i].uStartOffset,
1504 RawDescriptor.pPartDescs[i].pvPartitionData,
1505 RawDescriptor.pPartDescs[i].pszRawDevice);
1506 }
1507#endif
1508
1509 VDINTERFACEERROR vdInterfaceError;
1510 vdInterfaceError.pfnError = handleVDError;
1511 vdInterfaceError.pfnMessage = handleVDMessage;
1512
1513 rc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1514 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1515 AssertRC(vrc);
1516
1517 vrc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk); /* Raw VMDK's are harddisk only. */
1518 if (RT_FAILURE(vrc))
1519 {
1520 RTMsgError("Cannot create the virtual disk container: %Rrc", vrc);
1521 goto out;
1522 }
1523
1524 Assert(RT_MIN(cbSize / 512 / 16 / 63, 16383) -
1525 (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383) == 0);
1526 VDGEOMETRY PCHS, LCHS;
1527 PCHS.cCylinders = (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383);
1528 PCHS.cHeads = 16;
1529 PCHS.cSectors = 63;
1530 LCHS.cCylinders = 0;
1531 LCHS.cHeads = 0;
1532 LCHS.cSectors = 0;
1533 vrc = VDCreateBase(pDisk, "VMDK", filename.c_str(), cbSize,
1534 VD_IMAGE_FLAGS_FIXED | VD_VMDK_IMAGE_FLAGS_RAWDISK,
1535 (char *)&RawDescriptor, &PCHS, &LCHS, NULL,
1536 VD_OPEN_FLAGS_NORMAL, NULL, NULL);
1537 if (RT_FAILURE(vrc))
1538 {
1539 RTMsgError("Cannot create the raw disk VMDK: %Rrc", vrc);
1540 goto out;
1541 }
1542 RTPrintf("RAW host disk access VMDK file %s created successfully.\n", filename.c_str());
1543
1544 VDCloseAll(pDisk);
1545
1546 /* Clean up allocated memory etc. */
1547 if (pszPartitions)
1548 {
1549 for (unsigned i = 0; i < RawDescriptor.cPartDescs; i++)
1550 {
1551 /* Free memory allocated for relative device name. */
1552 if (fRelative && RawDescriptor.pPartDescs[i].pszRawDevice)
1553 RTStrFree((char *)(void *)RawDescriptor.pPartDescs[i].pszRawDevice);
1554 if (RawDescriptor.pPartDescs[i].pvPartitionData)
1555 RTMemFree((void *)RawDescriptor.pPartDescs[i].pvPartitionData);
1556 }
1557 if (RawDescriptor.pPartDescs)
1558 RTMemFree(RawDescriptor.pPartDescs);
1559 }
1560
1561 return SUCCEEDED(rc) ? 0 : 1;
1562
1563out:
1564 RTMsgError("The raw disk vmdk file was not created");
1565 return RT_SUCCESS(vrc) ? 0 : 1;
1566}
1567
1568static int CmdRenameVMDK(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1569{
1570 Utf8Str src;
1571 Utf8Str dst;
1572 /* Parse the arguments. */
1573 for (int i = 0; i < argc; i++)
1574 {
1575 if (strcmp(argv[i], "-from") == 0)
1576 {
1577 if (argc <= i + 1)
1578 {
1579 return errorArgument("Missing argument to '%s'", argv[i]);
1580 }
1581 i++;
1582 src = argv[i];
1583 }
1584 else if (strcmp(argv[i], "-to") == 0)
1585 {
1586 if (argc <= i + 1)
1587 {
1588 return errorArgument("Missing argument to '%s'", argv[i]);
1589 }
1590 i++;
1591 dst = argv[i];
1592 }
1593 else
1594 {
1595 return errorSyntax(USAGE_RENAMEVMDK, "Invalid parameter '%s'", argv[i]);
1596 }
1597 }
1598
1599 if (src.isEmpty())
1600 return errorSyntax(USAGE_RENAMEVMDK, "Mandatory parameter -from missing");
1601 if (dst.isEmpty())
1602 return errorSyntax(USAGE_RENAMEVMDK, "Mandatory parameter -to missing");
1603
1604 PVBOXHDD pDisk = NULL;
1605
1606 PVDINTERFACE pVDIfs = NULL;
1607 VDINTERFACEERROR vdInterfaceError;
1608 vdInterfaceError.pfnError = handleVDError;
1609 vdInterfaceError.pfnMessage = handleVDMessage;
1610
1611 int vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1612 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1613 AssertRC(vrc);
1614
1615 vrc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk);
1616 if (RT_FAILURE(vrc))
1617 {
1618 RTMsgError("Cannot create the virtual disk container: %Rrc", vrc);
1619 return vrc;
1620 }
1621 else
1622 {
1623 vrc = VDOpen(pDisk, "VMDK", src.c_str(), VD_OPEN_FLAGS_NORMAL, NULL);
1624 if (RT_FAILURE(vrc))
1625 {
1626 RTMsgError("Cannot create the source image: %Rrc", vrc);
1627 }
1628 else
1629 {
1630 vrc = VDCopy(pDisk, 0, pDisk, "VMDK", dst.c_str(), true, 0,
1631 VD_IMAGE_FLAGS_NONE, NULL, VD_OPEN_FLAGS_NORMAL,
1632 NULL, NULL, NULL);
1633 if (RT_FAILURE(vrc))
1634 {
1635 RTMsgError("Cannot rename the image: %Rrc", vrc);
1636 }
1637 }
1638 }
1639 VDCloseAll(pDisk);
1640 return vrc;
1641}
1642
1643static int CmdConvertToRaw(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1644{
1645 Utf8Str srcformat;
1646 Utf8Str src;
1647 Utf8Str dst;
1648 bool fWriteToStdOut = false;
1649
1650 /* Parse the arguments. */
1651 for (int i = 0; i < argc; i++)
1652 {
1653 if (strcmp(argv[i], "-format") == 0)
1654 {
1655 if (argc <= i + 1)
1656 {
1657 return errorArgument("Missing argument to '%s'", argv[i]);
1658 }
1659 i++;
1660 srcformat = argv[i];
1661 }
1662 else if (src.isEmpty())
1663 {
1664 src = argv[i];
1665 }
1666 else if (dst.isEmpty())
1667 {
1668 dst = argv[i];
1669#ifdef ENABLE_CONVERT_RAW_TO_STDOUT
1670 if (!strcmp(argv[i], "stdout"))
1671 fWriteToStdOut = true;
1672#endif /* ENABLE_CONVERT_RAW_TO_STDOUT */
1673 }
1674 else
1675 {
1676 return errorSyntax(USAGE_CONVERTTORAW, "Invalid parameter '%s'", argv[i]);
1677 }
1678 }
1679
1680 if (src.isEmpty())
1681 return errorSyntax(USAGE_CONVERTTORAW, "Mandatory filename parameter missing");
1682 if (dst.isEmpty())
1683 return errorSyntax(USAGE_CONVERTTORAW, "Mandatory outputfile parameter missing");
1684
1685 PVBOXHDD pDisk = NULL;
1686
1687 PVDINTERFACE pVDIfs = NULL;
1688 VDINTERFACEERROR vdInterfaceError;
1689 vdInterfaceError.pfnError = handleVDError;
1690 vdInterfaceError.pfnMessage = handleVDMessage;
1691
1692 int vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1693 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1694 AssertRC(vrc);
1695
1696 /** @todo: Support convert to raw for floppy and DVD images too. */
1697 vrc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk);
1698 if (RT_FAILURE(vrc))
1699 {
1700 RTMsgError("Cannot create the virtual disk container: %Rrc", vrc);
1701 return 1;
1702 }
1703
1704 /* Open raw output file. */
1705 RTFILE outFile;
1706 vrc = VINF_SUCCESS;
1707 if (fWriteToStdOut)
1708 vrc = RTFileFromNative(&outFile, 1);
1709 else
1710 vrc = RTFileOpen(&outFile, dst.c_str(), RTFILE_O_WRITE | RTFILE_O_CREATE | RTFILE_O_DENY_ALL);
1711 if (RT_FAILURE(vrc))
1712 {
1713 VDCloseAll(pDisk);
1714 RTMsgError("Cannot create destination file \"%s\": %Rrc", dst.c_str(), vrc);
1715 return 1;
1716 }
1717
1718 if (srcformat.isEmpty())
1719 {
1720 char *pszFormat = NULL;
1721 VDTYPE enmType = VDTYPE_INVALID;
1722 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
1723 src.c_str(), &pszFormat, &enmType);
1724 if (RT_FAILURE(vrc) || enmType != VDTYPE_HDD)
1725 {
1726 VDCloseAll(pDisk);
1727 if (!fWriteToStdOut)
1728 {
1729 RTFileClose(outFile);
1730 RTFileDelete(dst.c_str());
1731 }
1732 if (RT_FAILURE(vrc))
1733 RTMsgError("No file format specified and autodetect failed - please specify format: %Rrc", vrc);
1734 else
1735 RTMsgError("Only converting harddisk images is supported");
1736 return 1;
1737 }
1738 srcformat = pszFormat;
1739 RTStrFree(pszFormat);
1740 }
1741 vrc = VDOpen(pDisk, srcformat.c_str(), src.c_str(), VD_OPEN_FLAGS_READONLY, NULL);
1742 if (RT_FAILURE(vrc))
1743 {
1744 VDCloseAll(pDisk);
1745 if (!fWriteToStdOut)
1746 {
1747 RTFileClose(outFile);
1748 RTFileDelete(dst.c_str());
1749 }
1750 RTMsgError("Cannot open the source image: %Rrc", vrc);
1751 return 1;
1752 }
1753
1754 uint64_t cbSize = VDGetSize(pDisk, VD_LAST_IMAGE);
1755 uint64_t offFile = 0;
1756#define RAW_BUFFER_SIZE _128K
1757 size_t cbBuf = RAW_BUFFER_SIZE;
1758 void *pvBuf = RTMemAlloc(cbBuf);
1759 if (pvBuf)
1760 {
1761 RTStrmPrintf(g_pStdErr, "Converting image \"%s\" with size %RU64 bytes (%RU64MB) to raw...\n", src.c_str(), cbSize, (cbSize + _1M - 1) / _1M);
1762 while (offFile < cbSize)
1763 {
1764 size_t cb = (size_t)RT_MIN(cbSize - offFile, cbBuf);
1765 vrc = VDRead(pDisk, offFile, pvBuf, cb);
1766 if (RT_FAILURE(vrc))
1767 break;
1768 vrc = RTFileWrite(outFile, pvBuf, cb, NULL);
1769 if (RT_FAILURE(vrc))
1770 break;
1771 offFile += cb;
1772 }
1773 if (RT_FAILURE(vrc))
1774 {
1775 VDCloseAll(pDisk);
1776 if (!fWriteToStdOut)
1777 {
1778 RTFileClose(outFile);
1779 RTFileDelete(dst.c_str());
1780 }
1781 RTMsgError("Cannot copy image data: %Rrc", vrc);
1782 return 1;
1783 }
1784 }
1785 else
1786 {
1787 vrc = VERR_NO_MEMORY;
1788 VDCloseAll(pDisk);
1789 if (!fWriteToStdOut)
1790 {
1791 RTFileClose(outFile);
1792 RTFileDelete(dst.c_str());
1793 }
1794 RTMsgError("Out of memory allocating read buffer");
1795 return 1;
1796 }
1797
1798 if (!fWriteToStdOut)
1799 RTFileClose(outFile);
1800 VDCloseAll(pDisk);
1801 return 0;
1802}
1803
1804static int CmdConvertHardDisk(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1805{
1806 Utf8Str srcformat;
1807 Utf8Str dstformat;
1808 Utf8Str src;
1809 Utf8Str dst;
1810 int vrc;
1811 PVBOXHDD pSrcDisk = NULL;
1812 PVBOXHDD pDstDisk = NULL;
1813 VDTYPE enmSrcType = VDTYPE_INVALID;
1814
1815 /* Parse the arguments. */
1816 for (int i = 0; i < argc; i++)
1817 {
1818 if (strcmp(argv[i], "-srcformat") == 0)
1819 {
1820 if (argc <= i + 1)
1821 {
1822 return errorArgument("Missing argument to '%s'", argv[i]);
1823 }
1824 i++;
1825 srcformat = argv[i];
1826 }
1827 else if (strcmp(argv[i], "-dstformat") == 0)
1828 {
1829 if (argc <= i + 1)
1830 {
1831 return errorArgument("Missing argument to '%s'", argv[i]);
1832 }
1833 i++;
1834 dstformat = argv[i];
1835 }
1836 else if (src.isEmpty())
1837 {
1838 src = argv[i];
1839 }
1840 else if (dst.isEmpty())
1841 {
1842 dst = argv[i];
1843 }
1844 else
1845 {
1846 return errorSyntax(USAGE_CONVERTHD, "Invalid parameter '%s'", argv[i]);
1847 }
1848 }
1849
1850 if (src.isEmpty())
1851 return errorSyntax(USAGE_CONVERTHD, "Mandatory input image parameter missing");
1852 if (dst.isEmpty())
1853 return errorSyntax(USAGE_CONVERTHD, "Mandatory output image parameter missing");
1854
1855
1856 PVDINTERFACE pVDIfs = NULL;
1857 VDINTERFACEERROR vdInterfaceError;
1858 vdInterfaceError.pfnError = handleVDError;
1859 vdInterfaceError.pfnMessage = handleVDMessage;
1860
1861 vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1862 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1863 AssertRC(vrc);
1864
1865 do
1866 {
1867 /* Try to determine input image format */
1868 if (srcformat.isEmpty())
1869 {
1870 char *pszFormat = NULL;
1871 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
1872 src.c_str(), &pszFormat, &enmSrcType);
1873 if (RT_FAILURE(vrc))
1874 {
1875 RTMsgError("No file format specified and autodetect failed - please specify format: %Rrc", vrc);
1876 break;
1877 }
1878 srcformat = pszFormat;
1879 RTStrFree(pszFormat);
1880 }
1881
1882 vrc = VDCreate(pVDIfs, enmSrcType, &pSrcDisk);
1883 if (RT_FAILURE(vrc))
1884 {
1885 RTMsgError("Cannot create the source virtual disk container: %Rrc", vrc);
1886 break;
1887 }
1888
1889 /* Open the input image */
1890 vrc = VDOpen(pSrcDisk, srcformat.c_str(), src.c_str(), VD_OPEN_FLAGS_READONLY, NULL);
1891 if (RT_FAILURE(vrc))
1892 {
1893 RTMsgError("Cannot open the source image: %Rrc", vrc);
1894 break;
1895 }
1896
1897 /* Output format defaults to VDI */
1898 if (dstformat.isEmpty())
1899 dstformat = "VDI";
1900
1901 vrc = VDCreate(pVDIfs, enmSrcType, &pDstDisk);
1902 if (RT_FAILURE(vrc))
1903 {
1904 RTMsgError("Cannot create the destination virtual disk container: %Rrc", vrc);
1905 break;
1906 }
1907
1908 uint64_t cbSize = VDGetSize(pSrcDisk, VD_LAST_IMAGE);
1909 RTStrmPrintf(g_pStdErr, "Converting image \"%s\" with size %RU64 bytes (%RU64MB)...\n", src.c_str(), cbSize, (cbSize + _1M - 1) / _1M);
1910
1911 /* Create the output image */
1912 vrc = VDCopy(pSrcDisk, VD_LAST_IMAGE, pDstDisk, dstformat.c_str(),
1913 dst.c_str(), false, 0, VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED,
1914 NULL, VD_OPEN_FLAGS_NORMAL, NULL, NULL, NULL);
1915 if (RT_FAILURE(vrc))
1916 {
1917 RTMsgError("Cannot copy the image: %Rrc", vrc);
1918 break;
1919 }
1920 }
1921 while (0);
1922 if (pDstDisk)
1923 VDCloseAll(pDstDisk);
1924 if (pSrcDisk)
1925 VDCloseAll(pSrcDisk);
1926
1927 return RT_SUCCESS(vrc) ? 0 : 1;
1928}
1929
1930/**
1931 * Tries to repair a corrupted hard disk image.
1932 *
1933 * @returns VBox status code
1934 */
1935static int CmdRepairHardDisk(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1936{
1937 Utf8Str image;
1938 Utf8Str format;
1939 int vrc;
1940 bool fDryRun = false;
1941 PVBOXHDD pDisk = NULL;
1942
1943 /* Parse the arguments. */
1944 for (int i = 0; i < argc; i++)
1945 {
1946 if (strcmp(argv[i], "-dry-run") == 0)
1947 {
1948 fDryRun = true;
1949 }
1950 else if (strcmp(argv[i], "-format") == 0)
1951 {
1952 if (argc <= i + 1)
1953 {
1954 return errorArgument("Missing argument to '%s'", argv[i]);
1955 }
1956 i++;
1957 format = argv[i];
1958 }
1959 else if (image.isEmpty())
1960 {
1961 image = argv[i];
1962 }
1963 else
1964 {
1965 return errorSyntax(USAGE_REPAIRHD, "Invalid parameter '%s'", argv[i]);
1966 }
1967 }
1968
1969 if (image.isEmpty())
1970 return errorSyntax(USAGE_REPAIRHD, "Mandatory input image parameter missing");
1971
1972 PVDINTERFACE pVDIfs = NULL;
1973 VDINTERFACEERROR vdInterfaceError;
1974 vdInterfaceError.pfnError = handleVDError;
1975 vdInterfaceError.pfnMessage = handleVDMessage;
1976
1977 vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1978 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1979 AssertRC(vrc);
1980
1981 do
1982 {
1983 /* Try to determine input image format */
1984 if (format.isEmpty())
1985 {
1986 char *pszFormat = NULL;
1987 VDTYPE enmSrcType = VDTYPE_INVALID;
1988
1989 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
1990 image.c_str(), &pszFormat, &enmSrcType);
1991 if (RT_FAILURE(vrc) && (vrc != VERR_VD_IMAGE_CORRUPTED))
1992 {
1993 RTMsgError("No file format specified and autodetect failed - please specify format: %Rrc", vrc);
1994 break;
1995 }
1996 format = pszFormat;
1997 RTStrFree(pszFormat);
1998 }
1999
2000 uint32_t fFlags = 0;
2001 if (fDryRun)
2002 fFlags |= VD_REPAIR_DRY_RUN;
2003
2004 vrc = VDRepair(pVDIfs, NULL, image.c_str(), format.c_str(), fFlags);
2005 }
2006 while (0);
2007
2008 return RT_SUCCESS(vrc) ? 0 : 1;
2009}
2010
2011/**
2012 * Unloads the necessary driver.
2013 *
2014 * @returns VBox status code
2015 */
2016int CmdModUninstall(void)
2017{
2018 int rc;
2019
2020 rc = SUPR3Uninstall();
2021 if (RT_SUCCESS(rc))
2022 return 0;
2023 if (rc == VERR_NOT_IMPLEMENTED)
2024 return 0;
2025 return E_FAIL;
2026}
2027
2028/**
2029 * Loads the necessary driver.
2030 *
2031 * @returns VBox status code
2032 */
2033int CmdModInstall(void)
2034{
2035 int rc;
2036
2037 rc = SUPR3Install();
2038 if (RT_SUCCESS(rc))
2039 return 0;
2040 if (rc == VERR_NOT_IMPLEMENTED)
2041 return 0;
2042 return E_FAIL;
2043}
2044
2045int CmdDebugLog(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2046{
2047 /*
2048 * The first parameter is the name or UUID of a VM with a direct session
2049 * that we wish to open.
2050 */
2051 if (argc < 1)
2052 return errorSyntax(USAGE_DEBUGLOG, "Missing VM name/UUID");
2053
2054 ComPtr<IMachine> ptrMachine;
2055 HRESULT rc;
2056 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
2057 ptrMachine.asOutParam()), 1);
2058
2059 CHECK_ERROR_RET(ptrMachine, LockMachine(aSession, LockType_Shared), 1);
2060
2061 /*
2062 * Get the debugger interface.
2063 */
2064 ComPtr<IConsole> ptrConsole;
2065 CHECK_ERROR_RET(aSession, COMGETTER(Console)(ptrConsole.asOutParam()), 1);
2066
2067 ComPtr<IMachineDebugger> ptrDebugger;
2068 CHECK_ERROR_RET(ptrConsole, COMGETTER(Debugger)(ptrDebugger.asOutParam()), 1);
2069
2070 /*
2071 * Parse the command.
2072 */
2073 bool fEnablePresent = false;
2074 bool fEnable = false;
2075 bool fFlagsPresent = false;
2076 RTCString strFlags;
2077 bool fGroupsPresent = false;
2078 RTCString strGroups;
2079 bool fDestsPresent = false;
2080 RTCString strDests;
2081
2082 static const RTGETOPTDEF s_aOptions[] =
2083 {
2084 { "--disable", 'E', RTGETOPT_REQ_NOTHING },
2085 { "--enable", 'e', RTGETOPT_REQ_NOTHING },
2086 { "--flags", 'f', RTGETOPT_REQ_STRING },
2087 { "--groups", 'g', RTGETOPT_REQ_STRING },
2088 { "--destinations", 'd', RTGETOPT_REQ_STRING }
2089 };
2090
2091 int ch;
2092 RTGETOPTUNION ValueUnion;
2093 RTGETOPTSTATE GetState;
2094 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
2095 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
2096 {
2097 switch (ch)
2098 {
2099 case 'e':
2100 fEnablePresent = true;
2101 fEnable = true;
2102 break;
2103
2104 case 'E':
2105 fEnablePresent = true;
2106 fEnable = false;
2107 break;
2108
2109 case 'f':
2110 fFlagsPresent = true;
2111 if (*ValueUnion.psz)
2112 {
2113 if (strFlags.isNotEmpty())
2114 strFlags.append(' ');
2115 strFlags.append(ValueUnion.psz);
2116 }
2117 break;
2118
2119 case 'g':
2120 fGroupsPresent = true;
2121 if (*ValueUnion.psz)
2122 {
2123 if (strGroups.isNotEmpty())
2124 strGroups.append(' ');
2125 strGroups.append(ValueUnion.psz);
2126 }
2127 break;
2128
2129 case 'd':
2130 fDestsPresent = true;
2131 if (*ValueUnion.psz)
2132 {
2133 if (strDests.isNotEmpty())
2134 strDests.append(' ');
2135 strDests.append(ValueUnion.psz);
2136 }
2137 break;
2138
2139 default:
2140 return errorGetOpt(USAGE_DEBUGLOG , ch, &ValueUnion);
2141 }
2142 }
2143
2144 /*
2145 * Do the job.
2146 */
2147 if (fEnablePresent && !fEnable)
2148 CHECK_ERROR_RET(ptrDebugger, COMSETTER(LogEnabled)(FALSE), 1);
2149
2150 /** @todo flags, groups destination. */
2151 if (fFlagsPresent || fGroupsPresent || fDestsPresent)
2152 RTMsgWarning("One or more of the requested features are not implemented! Feel free to do this.");
2153
2154 if (fEnablePresent && fEnable)
2155 CHECK_ERROR_RET(ptrDebugger, COMSETTER(LogEnabled)(TRUE), 1);
2156 return 0;
2157}
2158
2159/**
2160 * Generate a SHA-256 password hash
2161 */
2162int CmdGeneratePasswordHash(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2163{
2164 /* one parameter, the password to hash */
2165 if (argc != 1)
2166 return errorSyntax(USAGE_PASSWORDHASH, "password to hash required");
2167
2168 uint8_t abDigest[RTSHA256_HASH_SIZE];
2169 RTSha256(argv[0], strlen(argv[0]), abDigest);
2170 char pszDigest[RTSHA256_DIGEST_LEN + 1];
2171 RTSha256ToString(abDigest, pszDigest, sizeof(pszDigest));
2172 RTPrintf("Password hash: %s\n", pszDigest);
2173
2174 return 0;
2175}
2176
2177/**
2178 * Print internal guest statistics or
2179 * set internal guest statistics update interval if specified
2180 */
2181int CmdGuestStats(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2182{
2183 /* one parameter, guest name */
2184 if (argc < 1)
2185 return errorSyntax(USAGE_GUESTSTATS, "Missing VM name/UUID");
2186
2187 /*
2188 * Parse the command.
2189 */
2190 ULONG aUpdateInterval = 0;
2191
2192 static const RTGETOPTDEF s_aOptions[] =
2193 {
2194 { "--interval", 'i', RTGETOPT_REQ_UINT32 }
2195 };
2196
2197 int ch;
2198 RTGETOPTUNION ValueUnion;
2199 RTGETOPTSTATE GetState;
2200 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
2201 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
2202 {
2203 switch (ch)
2204 {
2205 case 'i':
2206 aUpdateInterval = ValueUnion.u32;
2207 break;
2208
2209 default:
2210 return errorGetOpt(USAGE_GUESTSTATS , ch, &ValueUnion);
2211 }
2212 }
2213
2214 if (argc > 1 && aUpdateInterval == 0)
2215 return errorSyntax(USAGE_GUESTSTATS, "Invalid update interval specified");
2216
2217 RTPrintf("argc=%d interval=%u\n", argc, aUpdateInterval);
2218
2219 ComPtr<IMachine> ptrMachine;
2220 HRESULT rc;
2221 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
2222 ptrMachine.asOutParam()), 1);
2223
2224 CHECK_ERROR_RET(ptrMachine, LockMachine(aSession, LockType_Shared), 1);
2225
2226 /*
2227 * Get the guest interface.
2228 */
2229 ComPtr<IConsole> ptrConsole;
2230 CHECK_ERROR_RET(aSession, COMGETTER(Console)(ptrConsole.asOutParam()), 1);
2231
2232 ComPtr<IGuest> ptrGuest;
2233 CHECK_ERROR_RET(ptrConsole, COMGETTER(Guest)(ptrGuest.asOutParam()), 1);
2234
2235 if (aUpdateInterval)
2236 CHECK_ERROR_RET(ptrGuest, COMSETTER(StatisticsUpdateInterval)(aUpdateInterval), 1);
2237 else
2238 {
2239 ULONG mCpuUser, mCpuKernel, mCpuIdle;
2240 ULONG mMemTotal, mMemFree, mMemBalloon, mMemShared, mMemCache, mPageTotal;
2241 ULONG ulMemAllocTotal, ulMemFreeTotal, ulMemBalloonTotal, ulMemSharedTotal;
2242
2243 CHECK_ERROR_RET(ptrGuest, InternalGetStatistics(&mCpuUser, &mCpuKernel, &mCpuIdle,
2244 &mMemTotal, &mMemFree, &mMemBalloon, &mMemShared, &mMemCache,
2245 &mPageTotal, &ulMemAllocTotal, &ulMemFreeTotal, &ulMemBalloonTotal, &ulMemSharedTotal), 1);
2246 RTPrintf("mCpuUser=%u mCpuKernel=%u mCpuIdle=%u\n"
2247 "mMemTotal=%u mMemFree=%u mMemBalloon=%u mMemShared=%u mMemCache=%u\n"
2248 "mPageTotal=%u ulMemAllocTotal=%u ulMemFreeTotal=%u ulMemBalloonTotal=%u ulMemSharedTotal=%u\n",
2249 mCpuUser, mCpuKernel, mCpuIdle,
2250 mMemTotal, mMemFree, mMemBalloon, mMemShared, mMemCache,
2251 mPageTotal, ulMemAllocTotal, ulMemFreeTotal, ulMemBalloonTotal, ulMemSharedTotal);
2252
2253 }
2254
2255 return 0;
2256}
2257
2258
2259/**
2260 * Wrapper for handling internal commands
2261 */
2262int handleInternalCommands(HandlerArg *a)
2263{
2264 g_fInternalMode = true;
2265
2266 /* at least a command is required */
2267 if (a->argc < 1)
2268 return errorSyntax(USAGE_ALL, "Command missing");
2269
2270 /*
2271 * The 'string switch' on command name.
2272 */
2273 const char *pszCmd = a->argv[0];
2274 if (!strcmp(pszCmd, "loadmap"))
2275 return CmdLoadMap(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2276 if (!strcmp(pszCmd, "loadsyms"))
2277 return CmdLoadSyms(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2278 //if (!strcmp(pszCmd, "unloadsyms"))
2279 // return CmdUnloadSyms(argc - 1 , &a->argv[1]);
2280 if (!strcmp(pszCmd, "sethduuid") || !strcmp(pszCmd, "sethdparentuuid"))
2281 return CmdSetHDUUID(a->argc, &a->argv[0], a->virtualBox, a->session);
2282 if (!strcmp(pszCmd, "dumphdinfo"))
2283 return CmdDumpHDInfo(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2284 if (!strcmp(pszCmd, "listpartitions"))
2285 return CmdListPartitions(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2286 if (!strcmp(pszCmd, "createrawvmdk"))
2287 return CmdCreateRawVMDK(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2288 if (!strcmp(pszCmd, "renamevmdk"))
2289 return CmdRenameVMDK(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2290 if (!strcmp(pszCmd, "converttoraw"))
2291 return CmdConvertToRaw(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2292 if (!strcmp(pszCmd, "converthd"))
2293 return CmdConvertHardDisk(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2294 if (!strcmp(pszCmd, "modinstall"))
2295 return CmdModInstall();
2296 if (!strcmp(pszCmd, "moduninstall"))
2297 return CmdModUninstall();
2298 if (!strcmp(pszCmd, "debuglog"))
2299 return CmdDebugLog(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2300 if (!strcmp(pszCmd, "passwordhash"))
2301 return CmdGeneratePasswordHash(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2302 if (!strcmp(pszCmd, "gueststats"))
2303 return CmdGuestStats(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2304 if (!strcmp(pszCmd, "repairhd"))
2305 return CmdRepairHardDisk(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2306
2307 /* default: */
2308 return errorSyntax(USAGE_ALL, "Invalid command '%s'", a->argv[0]);
2309}
2310
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette