VirtualBox

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

Last change on this file since 56910 was 56910, checked in by vboxsync, 10 years ago

Main/VBoxManage: cleanup in raw partition handling, eliminating redundant code

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