VirtualBox

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

最後變更 在這個檔案從56912是 56912,由 vboxsync 提交於 10 年 前

Frontends/VBoxManage: add -relative support for creating raw partition vmdk on Windows host, should help with permission trouble (but the 1:1 mapping of windows partition numbers to what vbox uses isn't verified yet)

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

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