VirtualBox

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

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

VBoxManage: don't hide the help for 'internalcommands gueststats'

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