VirtualBox

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

Last change on this file since 42860 was 42860, checked in by vboxsync, 12 years ago

Frontends/VBoxManage: GPT partitioning for raw partition access has been imlemented. (See issue 4116 on xtracker)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 86.5 KB
Line 
1/* $Id: VBoxInternalManage.cpp 42860 2012-08-17 09:04:41Z vboxsync $ */
2/** @file
3 * VBoxManage - The 'internalcommands' command.
4 *
5 * VBoxInternalManage used to be a second CLI for doing special tricks,
6 * not intended for general usage, only for assisting VBox developers.
7 * It is now integrated into VBoxManage.
8 */
9
10/*
11 * Copyright (C) 2006-2010 Oracle Corporation
12 *
13 * This file is part of VirtualBox Open Source Edition (OSE), as
14 * available from http://www.virtualbox.org. This file is free software;
15 * you can redistribute it and/or modify it under the terms of the GNU
16 * General Public License (GPL) as published by the Free Software
17 * Foundation, in version 2 as it comes in the "COPYING" file of the
18 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
19 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
20 */
21
22
23
24/*******************************************************************************
25* Header Files *
26*******************************************************************************/
27#include <VBox/com/com.h>
28#include <VBox/com/string.h>
29#include <VBox/com/Guid.h>
30#include <VBox/com/ErrorInfo.h>
31#include <VBox/com/errorprint.h>
32
33#include <VBox/com/VirtualBox.h>
34
35#include <VBox/vd.h>
36#include <VBox/sup.h>
37#include <VBox/err.h>
38#include <VBox/log.h>
39
40#include <iprt/file.h>
41#include <iprt/getopt.h>
42#include <iprt/stream.h>
43#include <iprt/string.h>
44#include <iprt/uuid.h>
45#include <iprt/sha.h>
46
47#include "VBoxManage.h"
48
49/* Includes for the raw disk stuff. */
50#ifdef RT_OS_WINDOWS
51# include <windows.h>
52# include <winioctl.h>
53#elif defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) \
54 || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
55# include <errno.h>
56# include <sys/ioctl.h>
57# include <sys/types.h>
58# include <sys/stat.h>
59# include <fcntl.h>
60# include <unistd.h>
61#endif
62#ifdef RT_OS_LINUX
63# include <sys/utsname.h>
64# include <linux/hdreg.h>
65# include <linux/fs.h>
66# include <stdlib.h> /* atoi() */
67#endif /* RT_OS_LINUX */
68#ifdef RT_OS_DARWIN
69# include <sys/disk.h>
70#endif /* RT_OS_DARWIN */
71#ifdef RT_OS_SOLARIS
72# include <stropts.h>
73# include <sys/dkio.h>
74# include <sys/vtoc.h>
75#endif /* RT_OS_SOLARIS */
76#ifdef RT_OS_FREEBSD
77# include <sys/disk.h>
78#endif /* RT_OS_FREEBSD */
79
80using namespace com;
81
82
83/** Macro for checking whether a partition is of extended type or not. */
84#define PARTTYPE_IS_EXTENDED(x) ((x) == 0x05 || (x) == 0x0f || (x) == 0x85)
85
86/** Maximum number of partitions we can deal with.
87 * Ridiculously large number, but the memory consumption is rather low so who
88 * cares about never using most entries. */
89#define HOSTPARTITION_MAX 100
90
91
92typedef struct HOSTPARTITION
93{
94
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 PARTITIONING_TYPE 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"
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 int 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()), 1);
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 FAILED(hrc);
520}
521
522
523/**
524 * Identical to the 'loadmap' command.
525 */
526static int 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()), 1);
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 FAILED(hrc);
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 int 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 {
652 RTMsgError("Format autodetect failed: %Rrc", rc);
653 return 1;
654 }
655
656 PVBOXHDD pDisk = NULL;
657
658 PVDINTERFACE pVDIfs = NULL;
659 VDINTERFACEERROR vdInterfaceError;
660 vdInterfaceError.pfnError = handleVDError;
661 vdInterfaceError.pfnMessage = handleVDMessage;
662
663 rc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
664 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
665 AssertRC(rc);
666
667 rc = VDCreate(pVDIfs, enmType, &pDisk);
668 if (RT_FAILURE(rc))
669 {
670 RTMsgError("Cannot create the virtual disk container: %Rrc", rc);
671 return 1;
672 }
673
674 /* Open the image */
675 rc = VDOpen(pDisk, pszFormat, argv[1], VD_OPEN_FLAGS_NORMAL, NULL);
676 if (RT_FAILURE(rc))
677 {
678 RTMsgError("Cannot open the image: %Rrc", rc);
679 return 1;
680 }
681
682 if (uuidType == HDUUID)
683 rc = VDSetUuid(pDisk, VD_LAST_IMAGE, uuid.raw());
684 else
685 rc = VDSetParentUuid(pDisk, VD_LAST_IMAGE, uuid.raw());
686 if (RT_FAILURE(rc))
687 RTMsgError("Cannot set a new UUID: %Rrc", rc);
688 else
689 RTPrintf("UUID changed to: %s\n", uuid.toString().c_str());
690
691 VDCloseAll(pDisk);
692
693 return RT_FAILURE(rc);
694}
695
696
697static int CmdDumpHDInfo(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
698{
699 /* we need exactly one parameter: the image file */
700 if (argc != 1)
701 {
702 return errorSyntax(USAGE_DUMPHDINFO, "Not enough parameters");
703 }
704
705 /* just try it */
706 char *pszFormat = NULL;
707 VDTYPE enmType = VDTYPE_INVALID;
708 int rc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
709 argv[0], &pszFormat, &enmType);
710 if (RT_FAILURE(rc))
711 {
712 RTMsgError("Format autodetect failed: %Rrc", rc);
713 return 1;
714 }
715
716 PVBOXHDD pDisk = NULL;
717
718 PVDINTERFACE pVDIfs = NULL;
719 VDINTERFACEERROR vdInterfaceError;
720 vdInterfaceError.pfnError = handleVDError;
721 vdInterfaceError.pfnMessage = handleVDMessage;
722
723 rc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
724 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
725 AssertRC(rc);
726
727 rc = VDCreate(pVDIfs, enmType, &pDisk);
728 if (RT_FAILURE(rc))
729 {
730 RTMsgError("Cannot create the virtual disk container: %Rrc", rc);
731 return 1;
732 }
733
734 /* Open the image */
735 rc = VDOpen(pDisk, pszFormat, argv[0], VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO, NULL);
736 if (RT_FAILURE(rc))
737 {
738 RTMsgError("Cannot open the image: %Rrc", rc);
739 return 1;
740 }
741
742 VDDumpImages(pDisk);
743
744 VDCloseAll(pDisk);
745
746 return RT_FAILURE(rc);
747}
748
749static int partRead(RTFILE File, PHOSTPARTITIONS pPart)
750{
751 uint8_t aBuffer[512];
752 uint8_t partitionTableHeader[512];
753 uint32_t sector_size = 512;
754 uint64_t lastUsableLBA =0;
755 int rc;
756
757 PARTITIONING_TYPE partitioningType;
758
759 pPart->cPartitions = 0;
760 memset(pPart->aPartitions, '\0', sizeof(pPart->aPartitions));
761
762 rc = RTFileReadAt(File, 0, &aBuffer, sizeof(aBuffer), NULL);
763
764 if (RT_FAILURE(rc))
765 return rc;
766
767 if (aBuffer[450] == 0xEE)/* check the sign of the GPT disk*/
768 {
769 partitioningType = GPT;
770 pPart->uPartitioningType = GPT;//partitioningType;
771
772 if (aBuffer[510] != 0x55 || aBuffer[511] != 0xaa)
773 return VERR_INVALID_PARAMETER;
774
775 rc = RTFileReadAt(File, sector_size, &partitionTableHeader, sector_size, NULL);
776 if (RT_SUCCESS(rc))
777 {
778 const char* l_ppth = (char*)partitionTableHeader;
779 rc = strncmp(l_ppth, "EFI PART", 8);
780 if(RT_FAILURE(rc))
781 return VERR_INVALID_PARAMETER;
782
783 /** @todo check GPT Version */
784
785 uint64_t firstUsableLBA = RT_MAKE_U64_FROM_U8(partitionTableHeader[40],
786 partitionTableHeader[41],
787 partitionTableHeader[42],
788 partitionTableHeader[43],
789 partitionTableHeader[44],
790 partitionTableHeader[45],
791 partitionTableHeader[46],
792 partitionTableHeader[47]
793 );
794 lastUsableLBA = RT_MAKE_U64_FROM_U8( partitionTableHeader[48],
795 partitionTableHeader[49],
796 partitionTableHeader[50],
797 partitionTableHeader[51],
798 partitionTableHeader[52],
799 partitionTableHeader[53],
800 partitionTableHeader[54],
801 partitionTableHeader[55]
802 );
803 uint32_t partitionsNumber = RT_MAKE_U32_FROM_U8( partitionTableHeader[80],
804 partitionTableHeader[81],
805 partitionTableHeader[82],
806 partitionTableHeader[83]
807 );
808 uint32_t partitionEntrySize = RT_MAKE_U32_FROM_U8( partitionTableHeader[84],
809 partitionTableHeader[85],
810 partitionTableHeader[86],
811 partitionTableHeader[87]
812 );
813
814 uint32_t currentEntry = 0;
815 while(currentEntry<partitionsNumber)
816 {
817 uint8_t partitionEntry[128];
818
819 /*partition entries begin from LBA2*/
820 rc = RTFileReadAt(File, 1024 + currentEntry*partitionEntrySize, &partitionEntry, partitionEntrySize, NULL);
821
822 uint64_t start = RT_MAKE_U64_FROM_U8( partitionEntry[32],
823 partitionEntry[33],
824 partitionEntry[34],
825 partitionEntry[35],
826 partitionEntry[36],
827 partitionEntry[37],
828 partitionEntry[38],
829 partitionEntry[39]
830 );
831 uint64_t end = RT_MAKE_U64_FROM_U8( partitionEntry[40],
832 partitionEntry[41],
833 partitionEntry[42],
834 partitionEntry[43],
835 partitionEntry[44],
836 partitionEntry[45],
837 partitionEntry[46],
838 partitionEntry[47]
839 );
840
841 PHOSTPARTITION pCP = &pPart->aPartitions[pPart->cPartitions++];
842 pCP->uIndex = currentEntry + 1;
843 pCP->uType = 0;
844 pCP->uStartCylinder = 0;
845 pCP->uStartHead = 0;
846 pCP->uStartSector = 0;
847 pCP->uEndCylinder = 0;
848 pCP->uEndHead = 0;
849 pCP->uEndSector = 0;
850 pCP->uPartDataStart = 0; /* will be filled out later properly. */
851 pCP->cPartDataSectors = 0;
852 if(start==0 || end==0)
853 {
854 pCP->uIndex = 0;
855 --pPart->cPartitions;
856 break;
857 }
858 else{
859 pCP->uStart = start;
860 pCP->uSize = (end +1) - start;/*+1 LBA because the last address is included*/
861 }
862
863 ++currentEntry;
864 }
865 }
866 }
867 else
868 {
869 partitioningType = MBR;
870 pPart->uPartitioningType = MBR;//partitioningType;
871
872 if (aBuffer[510] != 0x55 || aBuffer[511] != 0xaa)
873 return VERR_INVALID_PARAMETER;
874
875 unsigned uExtended = (unsigned)-1;
876
877 for (unsigned i = 0; i < 4; i++)
878 {
879 uint8_t *p = &aBuffer[0x1be + i * 16];
880 if (p[4] == 0)
881 continue;
882 PHOSTPARTITION pCP = &pPart->aPartitions[pPart->cPartitions++];
883 pCP->uIndex = i + 1;
884 pCP->uType = p[4];
885 pCP->uStartCylinder = (uint32_t)p[3] + ((uint32_t)(p[2] & 0xc0) << 2);
886 pCP->uStartHead = p[1];
887 pCP->uStartSector = p[2] & 0x3f;
888 pCP->uEndCylinder = (uint32_t)p[7] + ((uint32_t)(p[6] & 0xc0) << 2);
889 pCP->uEndHead = p[5];
890 pCP->uEndSector = p[6] & 0x3f;
891 pCP->uStart = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
892 pCP->uSize = RT_MAKE_U32_FROM_U8(p[12], p[13], p[14], p[15]);
893 pCP->uPartDataStart = 0; /* will be filled out later properly. */
894 pCP->cPartDataSectors = 0;
895
896 if (PARTTYPE_IS_EXTENDED(p[4]))
897 {
898 if (uExtended == (unsigned)-1)
899 uExtended = (unsigned)(pCP - pPart->aPartitions);
900 else
901 {
902 RTMsgError("More than one extended partition");
903 return VERR_INVALID_PARAMETER;
904 }
905 }
906 }
907
908 if (uExtended != (unsigned)-1)
909 {
910 unsigned uIndex = 5;
911 uint64_t uStart = pPart->aPartitions[uExtended].uStart;
912 uint64_t uOffset = 0;
913 if (!uStart)
914 {
915 RTMsgError("Inconsistency for logical partition start");
916 return VERR_INVALID_PARAMETER;
917 }
918
919 do
920 {
921 rc = RTFileReadAt(File, (uStart + uOffset) * 512, &aBuffer, sizeof(aBuffer), NULL);
922 if (RT_FAILURE(rc))
923 return rc;
924
925 if (aBuffer[510] != 0x55 || aBuffer[511] != 0xaa)
926 {
927 RTMsgError("Logical partition without magic");
928 return VERR_INVALID_PARAMETER;
929 }
930 uint8_t *p = &aBuffer[0x1be];
931
932 if (p[4] == 0)
933 {
934 RTMsgError("Logical partition with type 0 encountered");
935 return VERR_INVALID_PARAMETER;
936 }
937
938 PHOSTPARTITION pCP = &pPart->aPartitions[pPart->cPartitions++];
939 pCP->uIndex = uIndex;
940 pCP->uType = p[4];
941 pCP->uStartCylinder = (uint32_t)p[3] + ((uint32_t)(p[2] & 0xc0) << 2);
942 pCP->uStartHead = p[1];
943 pCP->uStartSector = p[2] & 0x3f;
944 pCP->uEndCylinder = (uint32_t)p[7] + ((uint32_t)(p[6] & 0xc0) << 2);
945 pCP->uEndHead = p[5];
946 pCP->uEndSector = p[6] & 0x3f;
947 uint32_t uStartOffset = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
948 if (!uStartOffset)
949 {
950 RTMsgError("Invalid partition start offset");
951 return VERR_INVALID_PARAMETER;
952 }
953 pCP->uStart = uStart + uOffset + uStartOffset;
954 pCP->uSize = RT_MAKE_U32_FROM_U8(p[12], p[13], p[14], p[15]);
955 /* Fill out partitioning location info for EBR. */
956 pCP->uPartDataStart = uStart + uOffset;
957 pCP->cPartDataSectors = uStartOffset;
958 p += 16;
959 if (p[4] == 0)
960 uExtended = (unsigned)-1;
961 else if (PARTTYPE_IS_EXTENDED(p[4]))
962 {
963 uExtended = uIndex++;
964 uOffset = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
965 }
966 else
967 {
968 RTMsgError("Logical partition chain broken");
969 return VERR_INVALID_PARAMETER;
970 }
971 } while (uExtended != (unsigned)-1);
972 }
973 }
974
975
976 /* Sort partitions in ascending order of start sector, plus a trivial
977 * bit of consistency checking. */
978 for (unsigned i = 0; i < pPart->cPartitions-1; i++)
979 {
980 unsigned uMinIdx = i;
981 uint64_t uMinVal = pPart->aPartitions[i].uStart;
982 for (unsigned j = i + 1; j < pPart->cPartitions; j++)
983 {
984 if (pPart->aPartitions[j].uStart < uMinVal)
985 {
986 uMinIdx = j;
987 uMinVal = pPart->aPartitions[j].uStart;
988 }
989 else if (pPart->aPartitions[j].uStart == uMinVal)
990 {
991 RTMsgError("Two partitions start at the same place");
992 return VERR_INVALID_PARAMETER;
993 }
994 else if (pPart->aPartitions[j].uStart == 0)
995 {
996 RTMsgError("Partition starts at sector 0");
997 return VERR_INVALID_PARAMETER;
998 }
999 }
1000 if (uMinIdx != i)
1001 {
1002 /* Swap entries at index i and uMinIdx. */
1003 memcpy(&pPart->aPartitions[pPart->cPartitions],
1004 &pPart->aPartitions[i], sizeof(HOSTPARTITION));
1005 memcpy(&pPart->aPartitions[i],
1006 &pPart->aPartitions[uMinIdx], sizeof(HOSTPARTITION));
1007 memcpy(&pPart->aPartitions[uMinIdx],
1008 &pPart->aPartitions[pPart->cPartitions], sizeof(HOSTPARTITION));
1009 }
1010 }
1011
1012 /* Fill out partitioning location info for MBR or GPT. */
1013 pPart->aPartitions[0].uPartDataStart = 0;
1014 pPart->aPartitions[0].cPartDataSectors = pPart->aPartitions[0].uStart;
1015
1016 /* Fill out partitioning location info for backup GPT. */
1017 if(partitioningType == GPT)
1018 {
1019 pPart->aPartitions[pPart->cPartitions-1].uPartDataStart = lastUsableLBA+1;
1020 pPart->aPartitions[pPart->cPartitions-1].cPartDataSectors = 33;
1021
1022 /* Now do a some partition table consistency checking, to reject the most
1023 * obvious garbage which can lead to trouble later. */
1024 uint64_t uPrevEnd = 0;
1025 for (unsigned i = 0; i < pPart->cPartitions; i++)
1026 {
1027 if (pPart->aPartitions[i].cPartDataSectors)
1028 uPrevEnd = pPart->aPartitions[i].uPartDataStart + pPart->aPartitions[i].cPartDataSectors;
1029 if (pPart->aPartitions[i].uStart < uPrevEnd &&
1030 pPart->cPartitions-1 != i)
1031 {
1032 RTMsgError("Overlapping GPT partitions");
1033 return VERR_INVALID_PARAMETER;
1034 }
1035 }
1036 }
1037 else
1038 {
1039 /* Now do a some partition table consistency checking, to reject the most
1040 * obvious garbage which can lead to trouble later. */
1041 uint64_t uPrevEnd = 0;
1042 for (unsigned i = 0; i < pPart->cPartitions; i++)
1043 {
1044 if (pPart->aPartitions[i].cPartDataSectors)
1045 uPrevEnd = pPart->aPartitions[i].uPartDataStart + pPart->aPartitions[i].cPartDataSectors;
1046 if (pPart->aPartitions[i].uStart < uPrevEnd)
1047 {
1048 RTMsgError("Overlapping MBR partitions");
1049 return VERR_INVALID_PARAMETER;
1050 }
1051 if (!PARTTYPE_IS_EXTENDED(pPart->aPartitions[i].uType))
1052 uPrevEnd = pPart->aPartitions[i].uStart + pPart->aPartitions[i].uSize;
1053 }
1054 }
1055
1056 return VINF_SUCCESS;
1057}
1058
1059static int CmdListPartitions(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1060{
1061 Utf8Str rawdisk;
1062
1063 /* let's have a closer look at the arguments */
1064 for (int i = 0; i < argc; i++)
1065 {
1066 if (strcmp(argv[i], "-rawdisk") == 0)
1067 {
1068 if (argc <= i + 1)
1069 {
1070 return errorArgument("Missing argument to '%s'", argv[i]);
1071 }
1072 i++;
1073 rawdisk = argv[i];
1074 }
1075 else
1076 {
1077 return errorSyntax(USAGE_LISTPARTITIONS, "Invalid parameter '%s'", argv[i]);
1078 }
1079 }
1080
1081 if (rawdisk.isEmpty())
1082 return errorSyntax(USAGE_LISTPARTITIONS, "Mandatory parameter -rawdisk missing");
1083
1084 RTFILE hRawFile;
1085 int vrc = RTFileOpen(&hRawFile, rawdisk.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1086 if (RT_FAILURE(vrc))
1087 {
1088 RTMsgError("Cannot open the raw disk: %Rrc", vrc);
1089 return vrc;
1090 }
1091
1092 HOSTPARTITIONS partitions;
1093 vrc = partRead(hRawFile, &partitions);
1094 /* Don't bail out on errors, print the table and return the result code. */
1095
1096 RTPrintf("Number Type StartCHS EndCHS Size (MiB) Start (Sect)\n");
1097 for (unsigned i = 0; i < partitions.cPartitions; i++)
1098 {
1099 /* Don't show the extended partition, otherwise users might think they
1100 * can add it to the list of partitions for raw partition access. */
1101 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1102 continue;
1103
1104 RTPrintf("%-7u %#04x %-4u/%-3u/%-2u %-4u/%-3u/%-2u %10llu %10llu\n",
1105 partitions.aPartitions[i].uIndex,
1106 partitions.aPartitions[i].uType,
1107 partitions.aPartitions[i].uStartCylinder,
1108 partitions.aPartitions[i].uStartHead,
1109 partitions.aPartitions[i].uStartSector,
1110 partitions.aPartitions[i].uEndCylinder,
1111 partitions.aPartitions[i].uEndHead,
1112 partitions.aPartitions[i].uEndSector,
1113 partitions.aPartitions[i].uSize / 2048,
1114 partitions.aPartitions[i].uStart);
1115 }
1116
1117 return vrc;
1118}
1119
1120static PVBOXHDDRAWPARTDESC appendPartDesc(uint32_t *pcPartDescs, PVBOXHDDRAWPARTDESC *ppPartDescs)
1121{
1122 (*pcPartDescs)++;
1123 PVBOXHDDRAWPARTDESC p;
1124 p = (PVBOXHDDRAWPARTDESC)RTMemRealloc(*ppPartDescs,
1125 *pcPartDescs * sizeof(VBOXHDDRAWPARTDESC));
1126 *ppPartDescs = p;
1127 if (p)
1128 {
1129 p = p + *pcPartDescs - 1;
1130 memset(p, '\0', sizeof(VBOXHDDRAWPARTDESC));
1131 }
1132
1133 return p;
1134}
1135
1136static int CmdCreateRawVMDK(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1137{
1138 HRESULT rc = S_OK;
1139 Utf8Str filename;
1140 const char *pszMBRFilename = NULL;
1141 Utf8Str rawdisk;
1142 const char *pszPartitions = NULL;
1143 bool fRelative = false;
1144
1145 uint64_t cbSize = 0;
1146 PVBOXHDD pDisk = NULL;
1147 VBOXHDDRAW RawDescriptor;
1148 PVDINTERFACE pVDIfs = NULL;
1149
1150 /* let's have a closer look at the arguments */
1151 for (int i = 0; i < argc; i++)
1152 {
1153 if (strcmp(argv[i], "-filename") == 0)
1154 {
1155 if (argc <= i + 1)
1156 {
1157 return errorArgument("Missing argument to '%s'", argv[i]);
1158 }
1159 i++;
1160 filename = argv[i];
1161 }
1162 else if (strcmp(argv[i], "-mbr") == 0)
1163 {
1164 if (argc <= i + 1)
1165 {
1166 return errorArgument("Missing argument to '%s'", argv[i]);
1167 }
1168 i++;
1169 pszMBRFilename = argv[i];
1170 }
1171 else if (strcmp(argv[i], "-rawdisk") == 0)
1172 {
1173 if (argc <= i + 1)
1174 {
1175 return errorArgument("Missing argument to '%s'", argv[i]);
1176 }
1177 i++;
1178 rawdisk = argv[i];
1179 }
1180 else if (strcmp(argv[i], "-partitions") == 0)
1181 {
1182 if (argc <= i + 1)
1183 {
1184 return errorArgument("Missing argument to '%s'", argv[i]);
1185 }
1186 i++;
1187 pszPartitions = argv[i];
1188 }
1189#if defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
1190 else if (strcmp(argv[i], "-relative") == 0)
1191 {
1192 fRelative = true;
1193 }
1194#endif /* RT_OS_LINUX || RT_OS_FREEBSD */
1195 else
1196 return errorSyntax(USAGE_CREATERAWVMDK, "Invalid parameter '%s'", argv[i]);
1197 }
1198
1199 if (filename.isEmpty())
1200 return errorSyntax(USAGE_CREATERAWVMDK, "Mandatory parameter -filename missing");
1201 if (rawdisk.isEmpty())
1202 return errorSyntax(USAGE_CREATERAWVMDK, "Mandatory parameter -rawdisk missing");
1203 if (!pszPartitions && pszMBRFilename)
1204 return errorSyntax(USAGE_CREATERAWVMDK, "The parameter -mbr is only valid when the parameter -partitions is also present");
1205
1206#ifdef RT_OS_DARWIN
1207 fRelative = true;
1208#endif /* RT_OS_DARWIN */
1209 RTFILE hRawFile;
1210 int vrc = RTFileOpen(&hRawFile, rawdisk.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1211 if (RT_FAILURE(vrc))
1212 {
1213 RTMsgError("Cannot open the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1214 goto out;
1215 }
1216
1217#ifdef RT_OS_WINDOWS
1218 /* Windows NT has no IOCTL_DISK_GET_LENGTH_INFORMATION ioctl. This was
1219 * added to Windows XP, so we have to use the available info from DriveGeo.
1220 * Note that we cannot simply use IOCTL_DISK_GET_DRIVE_GEOMETRY as it
1221 * yields a slightly different result than IOCTL_DISK_GET_LENGTH_INFO.
1222 * We call IOCTL_DISK_GET_DRIVE_GEOMETRY first as we need to check the media
1223 * type anyway, and if IOCTL_DISK_GET_LENGTH_INFORMATION is supported
1224 * we will later override cbSize.
1225 */
1226 DISK_GEOMETRY DriveGeo;
1227 DWORD cbDriveGeo;
1228 if (DeviceIoControl((HANDLE)RTFileToNative(hRawFile),
1229 IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,
1230 &DriveGeo, sizeof(DriveGeo), &cbDriveGeo, NULL))
1231 {
1232 if ( DriveGeo.MediaType == FixedMedia
1233 || DriveGeo.MediaType == RemovableMedia)
1234 {
1235 cbSize = DriveGeo.Cylinders.QuadPart
1236 * DriveGeo.TracksPerCylinder
1237 * DriveGeo.SectorsPerTrack
1238 * DriveGeo.BytesPerSector;
1239 }
1240 else
1241 {
1242 RTMsgError("File '%s' is no fixed/removable medium device", rawdisk.c_str());
1243 vrc = VERR_INVALID_PARAMETER;
1244 goto out;
1245 }
1246
1247 GET_LENGTH_INFORMATION DiskLenInfo;
1248 DWORD junk;
1249 if (DeviceIoControl((HANDLE)RTFileToNative(hRawFile),
1250 IOCTL_DISK_GET_LENGTH_INFO, NULL, 0,
1251 &DiskLenInfo, sizeof(DiskLenInfo), &junk, (LPOVERLAPPED)NULL))
1252 {
1253 /* IOCTL_DISK_GET_LENGTH_INFO is supported -- override cbSize. */
1254 cbSize = DiskLenInfo.Length.QuadPart;
1255 }
1256 }
1257 else
1258 {
1259 /*
1260 * Could be raw image, remember error code and try to get the size first
1261 * before failing.
1262 */
1263 vrc = RTErrConvertFromWin32(GetLastError());
1264 if (RT_FAILURE(RTFileGetSize(hRawFile, &cbSize)))
1265 {
1266 RTMsgError("Cannot get the geometry of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1267 goto out;
1268 }
1269 else
1270 vrc = VINF_SUCCESS;
1271 }
1272#elif defined(RT_OS_LINUX)
1273 struct stat DevStat;
1274 if(!fstat(RTFileToNative(hRawFile), &DevStat))
1275 {
1276 if (S_ISBLK(DevStat.st_mode))
1277 {
1278#ifdef BLKGETSIZE64
1279 /* BLKGETSIZE64 is broken up to 2.4.17 and in many 2.5.x. In 2.6.0
1280 * it works without problems. */
1281 struct utsname utsname;
1282 if ( uname(&utsname) == 0
1283 && ( (strncmp(utsname.release, "2.5.", 4) == 0 && atoi(&utsname.release[4]) >= 18)
1284 || (strncmp(utsname.release, "2.", 2) == 0 && atoi(&utsname.release[2]) >= 6)))
1285 {
1286 uint64_t cbBlk;
1287 if (!ioctl(RTFileToNative(hRawFile), BLKGETSIZE64, &cbBlk))
1288 cbSize = cbBlk;
1289 }
1290#endif /* BLKGETSIZE64 */
1291 if (!cbSize)
1292 {
1293 long cBlocks;
1294 if (!ioctl(RTFileToNative(hRawFile), BLKGETSIZE, &cBlocks))
1295 cbSize = (uint64_t)cBlocks << 9;
1296 else
1297 {
1298 vrc = RTErrConvertFromErrno(errno);
1299 RTMsgError("Cannot get the size of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1300 goto out;
1301 }
1302 }
1303 }
1304 else if (S_ISREG(DevStat.st_mode))
1305 {
1306 vrc = RTFileGetSize(hRawFile, &cbSize);
1307 if (RT_FAILURE(vrc))
1308 {
1309 RTMsgError("Failed to get size of file '%s': %Rrc", rawdisk.c_str(), vrc);
1310 goto out;
1311 }
1312 else if (fRelative)
1313 {
1314 RTMsgError("The -relative parameter is invalid for raw images");
1315 vrc = VERR_INVALID_PARAMETER;
1316 goto out;
1317 }
1318 }
1319 else
1320 {
1321 RTMsgError("File '%s' is no block device", rawdisk.c_str());
1322 vrc = VERR_INVALID_PARAMETER;
1323 goto out;
1324 }
1325 }
1326 else
1327 {
1328 vrc = RTErrConvertFromErrno(errno);
1329 RTMsgError("Failed to get file informtation for raw disk '%s': %Rrc",
1330 rawdisk.c_str(), vrc);
1331 }
1332#elif defined(RT_OS_DARWIN)
1333 struct stat DevStat;
1334 if (!fstat(RTFileToNative(hRawFile), &DevStat))
1335 {
1336 if (S_ISBLK(DevStat.st_mode))
1337 {
1338 uint64_t cBlocks;
1339 uint32_t cbBlock;
1340 if (!ioctl(RTFileToNative(hRawFile), DKIOCGETBLOCKCOUNT, &cBlocks))
1341 {
1342 if (!ioctl(RTFileToNative(hRawFile), DKIOCGETBLOCKSIZE, &cbBlock))
1343 cbSize = cBlocks * cbBlock;
1344 else
1345 {
1346 RTMsgError("Cannot get the block size for file '%s': %Rrc", rawdisk.c_str(), vrc);
1347 vrc = RTErrConvertFromErrno(errno);
1348 goto out;
1349 }
1350 }
1351 else
1352 {
1353 vrc = RTErrConvertFromErrno(errno);
1354 RTMsgError("Cannot get the block count for file '%s': %Rrc", rawdisk.c_str(), vrc);
1355 goto out;
1356 }
1357 }
1358 else if (S_ISREG(DevStat.st_mode))
1359 {
1360 fRelative = false; /* Must be false for raw image files. */
1361 vrc = RTFileGetSize(hRawFile, &cbSize);
1362 if (RT_FAILURE(vrc))
1363 {
1364 RTMsgError("Failed to get size of file '%s': %Rrc", rawdisk.c_str(), vrc);
1365 goto out;
1366 }
1367 }
1368 else
1369 {
1370 RTMsgError("File '%s' is neither block device nor regular file", rawdisk.c_str());
1371 vrc = VERR_INVALID_PARAMETER;
1372 goto out;
1373 }
1374 }
1375 else
1376 {
1377 vrc = RTErrConvertFromErrno(errno);
1378 RTMsgError("Failed to get file informtation for raw disk '%s': %Rrc",
1379 rawdisk.c_str(), vrc);
1380 }
1381#elif defined(RT_OS_SOLARIS)
1382 struct stat DevStat;
1383 if (!fstat(RTFileToNative(hRawFile), &DevStat))
1384 {
1385 if (S_ISBLK(DevStat.st_mode) || S_ISCHR(DevStat.st_mode))
1386 {
1387 struct dk_minfo mediainfo;
1388 if (!ioctl(RTFileToNative(hRawFile), DKIOCGMEDIAINFO, &mediainfo))
1389 cbSize = mediainfo.dki_capacity * mediainfo.dki_lbsize;
1390 else
1391 {
1392 vrc = RTErrConvertFromErrno(errno);
1393 RTMsgError("Cannot get the size of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1394 goto out;
1395 }
1396 }
1397 else if (S_ISREG(DevStat.st_mode))
1398 {
1399 vrc = RTFileGetSize(hRawFile, &cbSize);
1400 if (RT_FAILURE(vrc))
1401 {
1402 RTMsgError("Failed to get size of file '%s': %Rrc", rawdisk.c_str(), vrc);
1403 goto out;
1404 }
1405 }
1406 else
1407 {
1408 RTMsgError("File '%s' is no block or char device", rawdisk.c_str());
1409 vrc = VERR_INVALID_PARAMETER;
1410 goto out;
1411 }
1412 }
1413 else
1414 {
1415 vrc = RTErrConvertFromErrno(errno);
1416 RTMsgError("Failed to get file informtation for raw disk '%s': %Rrc",
1417 rawdisk.c_str(), vrc);
1418 }
1419#elif defined(RT_OS_FREEBSD)
1420 struct stat DevStat;
1421 if (!fstat(RTFileToNative(hRawFile), &DevStat))
1422 {
1423 if (S_ISCHR(DevStat.st_mode))
1424 {
1425 off_t cbMedia = 0;
1426 if (!ioctl(RTFileToNative(hRawFile), DIOCGMEDIASIZE, &cbMedia))
1427 cbSize = cbMedia;
1428 else
1429 {
1430 vrc = RTErrConvertFromErrno(errno);
1431 RTMsgError("Cannot get the block count for file '%s': %Rrc", rawdisk.c_str(), vrc);
1432 goto out;
1433 }
1434 }
1435 else if (S_ISREG(DevStat.st_mode))
1436 {
1437 if (fRelative)
1438 {
1439 RTMsgError("The -relative parameter is invalid for raw images");
1440 vrc = VERR_INVALID_PARAMETER;
1441 goto out;
1442 }
1443 cbSize = DevStat.st_size;
1444 }
1445 else
1446 {
1447 RTMsgError("File '%s' is neither character device nor regular file", rawdisk.c_str());
1448 vrc = VERR_INVALID_PARAMETER;
1449 goto out;
1450 }
1451 }
1452 else
1453 {
1454 vrc = RTErrConvertFromErrno(errno);
1455 RTMsgError("Failed to get file informtation for raw disk '%s': %Rrc",
1456 rawdisk.c_str(), vrc);
1457 }
1458#else /* all unrecognized OSes */
1459 /* Hopefully this works on all other hosts. If it doesn't, it'll just fail
1460 * creating the VMDK, so no real harm done. */
1461 vrc = RTFileGetSize(hRawFile, &cbSize);
1462 if (RT_FAILURE(vrc))
1463 {
1464 RTMsgError("Cannot get the size of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1465 goto out;
1466 }
1467#endif
1468
1469 /* Check whether cbSize is actually sensible. */
1470 if (!cbSize || cbSize % 512)
1471 {
1472 RTMsgError("Detected size of raw disk '%s' is %s, an invalid value", rawdisk.c_str(), cbSize);
1473 vrc = VERR_INVALID_PARAMETER;
1474 goto out;
1475 }
1476
1477 RawDescriptor.szSignature[0] = 'R';
1478 RawDescriptor.szSignature[1] = 'A';
1479 RawDescriptor.szSignature[2] = 'W';
1480 RawDescriptor.szSignature[3] = '\0';
1481 if (!pszPartitions)
1482 {
1483 RawDescriptor.fRawDisk = true;
1484 RawDescriptor.pszRawDisk = rawdisk.c_str();
1485 }
1486 else
1487 {
1488 RawDescriptor.fRawDisk = false;
1489 RawDescriptor.pszRawDisk = NULL;
1490 RawDescriptor.cPartDescs = 0;
1491 RawDescriptor.pPartDescs = NULL;
1492
1493 uint32_t uPartitions = 0;
1494
1495 const char *p = pszPartitions;
1496 char *pszNext;
1497 uint32_t u32;
1498 while (*p != '\0')
1499 {
1500 vrc = RTStrToUInt32Ex(p, &pszNext, 0, &u32);
1501 if (RT_FAILURE(vrc))
1502 {
1503 RTMsgError("Incorrect value in partitions parameter");
1504 goto out;
1505 }
1506 uPartitions |= RT_BIT(u32);
1507 p = pszNext;
1508 if (*p == ',')
1509 p++;
1510 else if (*p != '\0')
1511 {
1512 RTMsgError("Incorrect separator in partitions parameter");
1513 vrc = VERR_INVALID_PARAMETER;
1514 goto out;
1515 }
1516 }
1517
1518 HOSTPARTITIONS partitions;
1519 vrc = partRead(hRawFile, &partitions);
1520 if (RT_FAILURE(vrc))
1521 {
1522 RTMsgError("Cannot read the partition information from '%s'", rawdisk.c_str());
1523 goto out;
1524 }
1525
1526 RawDescriptor.uPartitioningType = partitions.uPartitioningType;
1527
1528 for (unsigned i = 0; i < partitions.cPartitions; i++)
1529 {
1530 if ( uPartitions & RT_BIT(partitions.aPartitions[i].uIndex)
1531 && PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1532 {
1533 /* Some ignorant user specified an extended partition.
1534 * Bad idea, as this would trigger an overlapping
1535 * partitions error later during VMDK creation. So warn
1536 * here and ignore what the user requested. */
1537 RTMsgWarning("It is not possible (and necessary) to explicitly give access to the "
1538 "extended partition %u. If required, enable access to all logical "
1539 "partitions inside this extended partition.",
1540 partitions.aPartitions[i].uIndex);
1541 uPartitions &= ~RT_BIT(partitions.aPartitions[i].uIndex);
1542 }
1543 }
1544
1545 for (unsigned i = 0; i < partitions.cPartitions; i++)
1546 {
1547 PVBOXHDDRAWPARTDESC pPartDesc = NULL;
1548
1549 /* first dump the MBR/EPT data area */
1550 if (partitions.aPartitions[i].cPartDataSectors)
1551 {
1552 pPartDesc = appendPartDesc(&RawDescriptor.cPartDescs,
1553 &RawDescriptor.pPartDescs);
1554 if (!pPartDesc)
1555 {
1556 RTMsgError("Out of memory allocating the partition list for '%s'", rawdisk.c_str());
1557 vrc = VERR_NO_MEMORY;
1558 goto out;
1559 }
1560
1561 /** @todo the clipping below isn't 100% accurate, as it should
1562 * actually clip to the track size. However, that's easier said
1563 * than done as figuring out the track size is heuristics. In
1564 * any case the clipping is adjusted later after sorting, to
1565 * prevent overlapping data areas on the resulting image. */
1566 pPartDesc->cbData = RT_MIN(partitions.aPartitions[i].cPartDataSectors, 63) * 512;
1567 pPartDesc->uStart = partitions.aPartitions[i].uPartDataStart * 512;
1568 Assert(pPartDesc->cbData - (size_t)pPartDesc->cbData == 0);
1569 void *pPartData = RTMemAlloc((size_t)pPartDesc->cbData);
1570 if (!pPartData)
1571 {
1572 RTMsgError("Out of memory allocating the partition descriptor for '%s'", rawdisk.c_str());
1573 vrc = VERR_NO_MEMORY;
1574 goto out;
1575 }
1576 vrc = RTFileReadAt(hRawFile, partitions.aPartitions[i].uPartDataStart * 512,
1577 pPartData, (size_t)pPartDesc->cbData, NULL);
1578 if (RT_FAILURE(vrc))
1579 {
1580 RTMsgError("Cannot read partition data from raw device '%s': %Rrc", rawdisk.c_str(), vrc);
1581 goto out;
1582 }
1583 /* Splice in the replacement MBR code if specified. */
1584 if ( partitions.aPartitions[i].uPartDataStart == 0
1585 && pszMBRFilename)
1586 {
1587 RTFILE MBRFile;
1588 vrc = RTFileOpen(&MBRFile, pszMBRFilename, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1589 if (RT_FAILURE(vrc))
1590 {
1591 RTMsgError("Cannot open replacement MBR file '%s' specified with -mbr: %Rrc", pszMBRFilename, vrc);
1592 goto out;
1593 }
1594 vrc = RTFileReadAt(MBRFile, 0, pPartData, 0x1be, NULL);
1595 RTFileClose(MBRFile);
1596 if (RT_FAILURE(vrc))
1597 {
1598 RTMsgError("Cannot read replacement MBR file '%s': %Rrc", pszMBRFilename, vrc);
1599 goto out;
1600 }
1601 }
1602 pPartDesc->pvPartitionData = pPartData;
1603 }
1604
1605 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1606 {
1607 /* Suppress exporting the actual extended partition. Only
1608 * logical partitions should be processed. However completely
1609 * ignoring it leads to leaving out the EBR data. */
1610 continue;
1611 }
1612
1613 /* set up values for non-relative device names */
1614 const char *pszRawName = rawdisk.c_str();
1615 uint64_t uStartOffset = partitions.aPartitions[i].uStart * 512;
1616
1617 pPartDesc = appendPartDesc(&RawDescriptor.cPartDescs,
1618 &RawDescriptor.pPartDescs);
1619 if (!pPartDesc)
1620 {
1621 RTMsgError("Out of memory allocating the partition list for '%s'", rawdisk.c_str());
1622 vrc = VERR_NO_MEMORY;
1623 goto out;
1624 }
1625
1626 if (uPartitions & RT_BIT(partitions.aPartitions[i].uIndex))
1627 {
1628 if (fRelative)
1629 {
1630#if defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
1631 /* Refer to the correct partition and use offset 0. */
1632 char *psz;
1633 RTStrAPrintf(&psz,
1634#if defined(RT_OS_LINUX)
1635 "%s%u",
1636#elif defined(RT_OS_FREEBSD)
1637 "%ss%u",
1638#endif
1639 rawdisk.c_str(),
1640 partitions.aPartitions[i].uIndex);
1641 if (!psz)
1642 {
1643 vrc = VERR_NO_STR_MEMORY;
1644 RTMsgError("Cannot create reference to individual partition %u, rc=%Rrc",
1645 partitions.aPartitions[i].uIndex, vrc);
1646 goto out;
1647 }
1648 pszRawName = psz;
1649 uStartOffset = 0;
1650#elif defined(RT_OS_DARWIN)
1651 /* Refer to the correct partition and use offset 0. */
1652 char *psz;
1653 RTStrAPrintf(&psz, "%ss%u", rawdisk.c_str(),
1654 partitions.aPartitions[i].uIndex);
1655 if (!psz)
1656 {
1657 vrc = VERR_NO_STR_MEMORY;
1658 RTMsgError("Cannot create reference to individual partition %u, rc=%Rrc",
1659 partitions.aPartitions[i].uIndex, vrc);
1660 goto out;
1661 }
1662 pszRawName = psz;
1663 uStartOffset = 0;
1664#else
1665 /** @todo not implemented for other hosts. Treat just like
1666 * not specified (this code is actually never reached). */
1667#endif
1668 }
1669
1670 pPartDesc->pszRawDevice = pszRawName;
1671 pPartDesc->uStartOffset = uStartOffset;
1672 }
1673 else
1674 {
1675 pPartDesc->pszRawDevice = NULL;
1676 pPartDesc->uStartOffset = 0;
1677 }
1678
1679 pPartDesc->uStart = partitions.aPartitions[i].uStart * 512;
1680 pPartDesc->cbData = partitions.aPartitions[i].uSize * 512;
1681 }
1682
1683 /* Sort data areas in ascending order of start. */
1684 for (unsigned i = 0; i < RawDescriptor.cPartDescs-1; i++)
1685 {
1686 unsigned uMinIdx = i;
1687 uint64_t uMinVal = RawDescriptor.pPartDescs[i].uStart;
1688 for (unsigned j = i + 1; j < RawDescriptor.cPartDescs; j++)
1689 {
1690 if (RawDescriptor.pPartDescs[j].uStart < uMinVal)
1691 {
1692 uMinIdx = j;
1693 uMinVal = RawDescriptor.pPartDescs[j].uStart;
1694 }
1695 }
1696 if (uMinIdx != i)
1697 {
1698 /* Swap entries at index i and uMinIdx. */
1699 VBOXHDDRAWPARTDESC tmp;
1700 memcpy(&tmp, &RawDescriptor.pPartDescs[i], sizeof(tmp));
1701 memcpy(&RawDescriptor.pPartDescs[i], &RawDescriptor.pPartDescs[uMinIdx], sizeof(tmp));
1702 memcpy(&RawDescriptor.pPartDescs[uMinIdx], &tmp, sizeof(tmp));
1703 }
1704 }
1705
1706 /* Have a second go at MBR/EPT, GPT area clipping. Now that the data areas
1707 * are sorted this is much easier to get 100% right. */
1708 //for (unsigned i = 0; i < RawDescriptor.cPartDescs-1; i++)
1709 for (unsigned i = 0; i < RawDescriptor.cPartDescs; i++)
1710 {
1711 if (RawDescriptor.pPartDescs[i].pvPartitionData)
1712 {
1713 RawDescriptor.pPartDescs[i].cbData = RT_MIN(RawDescriptor.pPartDescs[i+1].uStart - RawDescriptor.pPartDescs[i].uStart, RawDescriptor.pPartDescs[i].cbData);
1714 if (!RawDescriptor.pPartDescs[i].cbData)
1715 {
1716 if(RawDescriptor.uPartitioningType == MBR)
1717 {
1718 RTMsgError("MBR/EPT overlaps with data area");
1719 vrc = VERR_INVALID_PARAMETER;
1720 goto out;
1721 }
1722 else
1723 {
1724 if(RawDescriptor.cPartDescs != i+1)
1725 {
1726 RTMsgError("GPT overlaps with data area");
1727 vrc = VERR_INVALID_PARAMETER;
1728 goto out;
1729 }
1730 }
1731 }
1732 }
1733 }
1734 }
1735
1736 RTFileClose(hRawFile);
1737
1738#ifdef DEBUG_klaus
1739 if (!RawDescriptor.fRawDisk)
1740 {
1741 RTPrintf("# start length startoffset partdataptr device\n");
1742 for (unsigned i = 0; i < RawDescriptor.cPartDescs; i++)
1743 {
1744 RTPrintf("%2u %14RU64 %14RU64 %14RU64 %#18p %s\n", i,
1745 RawDescriptor.pPartDescs[i].uStart,
1746 RawDescriptor.pPartDescs[i].cbData,
1747 RawDescriptor.pPartDescs[i].uStartOffset,
1748 RawDescriptor.pPartDescs[i].pvPartitionData,
1749 RawDescriptor.pPartDescs[i].pszRawDevice);
1750 }
1751 }
1752#endif
1753
1754 VDINTERFACEERROR vdInterfaceError;
1755 vdInterfaceError.pfnError = handleVDError;
1756 vdInterfaceError.pfnMessage = handleVDMessage;
1757
1758 rc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1759 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1760 AssertRC(vrc);
1761
1762 vrc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk); /* Raw VMDK's are harddisk only. */
1763 if (RT_FAILURE(vrc))
1764 {
1765 RTMsgError("Cannot create the virtual disk container: %Rrc", vrc);
1766 goto out;
1767 }
1768
1769 Assert(RT_MIN(cbSize / 512 / 16 / 63, 16383) -
1770 (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383) == 0);
1771 VDGEOMETRY PCHS, LCHS;
1772 PCHS.cCylinders = (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383);
1773 PCHS.cHeads = 16;
1774 PCHS.cSectors = 63;
1775 LCHS.cCylinders = 0;
1776 LCHS.cHeads = 0;
1777 LCHS.cSectors = 0;
1778 vrc = VDCreateBase(pDisk, "VMDK", filename.c_str(), cbSize,
1779 VD_IMAGE_FLAGS_FIXED | VD_VMDK_IMAGE_FLAGS_RAWDISK,
1780 (char *)&RawDescriptor, &PCHS, &LCHS, NULL,
1781 VD_OPEN_FLAGS_NORMAL, NULL, NULL);
1782 if (RT_FAILURE(vrc))
1783 {
1784 RTMsgError("Cannot create the raw disk VMDK: %Rrc", vrc);
1785 goto out;
1786 }
1787 RTPrintf("RAW host disk access VMDK file %s created successfully.\n", filename.c_str());
1788
1789 VDCloseAll(pDisk);
1790
1791 /* Clean up allocated memory etc. */
1792 if (pszPartitions)
1793 {
1794 for (unsigned i = 0; i < RawDescriptor.cPartDescs; i++)
1795 {
1796 /* Free memory allocated for relative device name. */
1797 if (fRelative && RawDescriptor.pPartDescs[i].pszRawDevice)
1798 RTStrFree((char *)(void *)RawDescriptor.pPartDescs[i].pszRawDevice);
1799 if (RawDescriptor.pPartDescs[i].pvPartitionData)
1800 RTMemFree((void *)RawDescriptor.pPartDescs[i].pvPartitionData);
1801 }
1802 if (RawDescriptor.pPartDescs)
1803 RTMemFree(RawDescriptor.pPartDescs);
1804 }
1805
1806 return SUCCEEDED(rc) ? 0 : 1;
1807
1808out:
1809 RTMsgError("The raw disk vmdk file was not created");
1810 return RT_SUCCESS(vrc) ? 0 : 1;
1811}
1812
1813static int CmdRenameVMDK(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1814{
1815 Utf8Str src;
1816 Utf8Str dst;
1817 /* Parse the arguments. */
1818 for (int i = 0; i < argc; i++)
1819 {
1820 if (strcmp(argv[i], "-from") == 0)
1821 {
1822 if (argc <= i + 1)
1823 {
1824 return errorArgument("Missing argument to '%s'", argv[i]);
1825 }
1826 i++;
1827 src = argv[i];
1828 }
1829 else if (strcmp(argv[i], "-to") == 0)
1830 {
1831 if (argc <= i + 1)
1832 {
1833 return errorArgument("Missing argument to '%s'", argv[i]);
1834 }
1835 i++;
1836 dst = argv[i];
1837 }
1838 else
1839 {
1840 return errorSyntax(USAGE_RENAMEVMDK, "Invalid parameter '%s'", argv[i]);
1841 }
1842 }
1843
1844 if (src.isEmpty())
1845 return errorSyntax(USAGE_RENAMEVMDK, "Mandatory parameter -from missing");
1846 if (dst.isEmpty())
1847 return errorSyntax(USAGE_RENAMEVMDK, "Mandatory parameter -to missing");
1848
1849 PVBOXHDD pDisk = NULL;
1850
1851 PVDINTERFACE pVDIfs = NULL;
1852 VDINTERFACEERROR vdInterfaceError;
1853 vdInterfaceError.pfnError = handleVDError;
1854 vdInterfaceError.pfnMessage = handleVDMessage;
1855
1856 int vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1857 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1858 AssertRC(vrc);
1859
1860 vrc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk);
1861 if (RT_FAILURE(vrc))
1862 {
1863 RTMsgError("Cannot create the virtual disk container: %Rrc", vrc);
1864 return vrc;
1865 }
1866 else
1867 {
1868 vrc = VDOpen(pDisk, "VMDK", src.c_str(), VD_OPEN_FLAGS_NORMAL, NULL);
1869 if (RT_FAILURE(vrc))
1870 {
1871 RTMsgError("Cannot create the source image: %Rrc", vrc);
1872 }
1873 else
1874 {
1875 vrc = VDCopy(pDisk, 0, pDisk, "VMDK", dst.c_str(), true, 0,
1876 VD_IMAGE_FLAGS_NONE, NULL, VD_OPEN_FLAGS_NORMAL,
1877 NULL, NULL, NULL);
1878 if (RT_FAILURE(vrc))
1879 {
1880 RTMsgError("Cannot rename the image: %Rrc", vrc);
1881 }
1882 }
1883 }
1884 VDCloseAll(pDisk);
1885 return vrc;
1886}
1887
1888static int CmdConvertToRaw(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1889{
1890 Utf8Str srcformat;
1891 Utf8Str src;
1892 Utf8Str dst;
1893 bool fWriteToStdOut = false;
1894
1895 /* Parse the arguments. */
1896 for (int i = 0; i < argc; i++)
1897 {
1898 if (strcmp(argv[i], "-format") == 0)
1899 {
1900 if (argc <= i + 1)
1901 {
1902 return errorArgument("Missing argument to '%s'", argv[i]);
1903 }
1904 i++;
1905 srcformat = argv[i];
1906 }
1907 else if (src.isEmpty())
1908 {
1909 src = argv[i];
1910 }
1911 else if (dst.isEmpty())
1912 {
1913 dst = argv[i];
1914#ifdef ENABLE_CONVERT_RAW_TO_STDOUT
1915 if (!strcmp(argv[i], "stdout"))
1916 fWriteToStdOut = true;
1917#endif /* ENABLE_CONVERT_RAW_TO_STDOUT */
1918 }
1919 else
1920 {
1921 return errorSyntax(USAGE_CONVERTTORAW, "Invalid parameter '%s'", argv[i]);
1922 }
1923 }
1924
1925 if (src.isEmpty())
1926 return errorSyntax(USAGE_CONVERTTORAW, "Mandatory filename parameter missing");
1927 if (dst.isEmpty())
1928 return errorSyntax(USAGE_CONVERTTORAW, "Mandatory outputfile parameter missing");
1929
1930 PVBOXHDD pDisk = NULL;
1931
1932 PVDINTERFACE pVDIfs = NULL;
1933 VDINTERFACEERROR vdInterfaceError;
1934 vdInterfaceError.pfnError = handleVDError;
1935 vdInterfaceError.pfnMessage = handleVDMessage;
1936
1937 int vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1938 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1939 AssertRC(vrc);
1940
1941 /** @todo: Support convert to raw for floppy and DVD images too. */
1942 vrc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk);
1943 if (RT_FAILURE(vrc))
1944 {
1945 RTMsgError("Cannot create the virtual disk container: %Rrc", vrc);
1946 return 1;
1947 }
1948
1949 /* Open raw output file. */
1950 RTFILE outFile;
1951 vrc = VINF_SUCCESS;
1952 if (fWriteToStdOut)
1953 vrc = RTFileFromNative(&outFile, 1);
1954 else
1955 vrc = RTFileOpen(&outFile, dst.c_str(), RTFILE_O_WRITE | RTFILE_O_CREATE | RTFILE_O_DENY_ALL);
1956 if (RT_FAILURE(vrc))
1957 {
1958 VDCloseAll(pDisk);
1959 RTMsgError("Cannot create destination file \"%s\": %Rrc", dst.c_str(), vrc);
1960 return 1;
1961 }
1962
1963 if (srcformat.isEmpty())
1964 {
1965 char *pszFormat = NULL;
1966 VDTYPE enmType = VDTYPE_INVALID;
1967 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
1968 src.c_str(), &pszFormat, &enmType);
1969 if (RT_FAILURE(vrc) || enmType != VDTYPE_HDD)
1970 {
1971 VDCloseAll(pDisk);
1972 if (!fWriteToStdOut)
1973 {
1974 RTFileClose(outFile);
1975 RTFileDelete(dst.c_str());
1976 }
1977 if (RT_FAILURE(vrc))
1978 RTMsgError("No file format specified and autodetect failed - please specify format: %Rrc", vrc);
1979 else
1980 RTMsgError("Only converting harddisk images is supported");
1981 return 1;
1982 }
1983 srcformat = pszFormat;
1984 RTStrFree(pszFormat);
1985 }
1986 vrc = VDOpen(pDisk, srcformat.c_str(), src.c_str(), VD_OPEN_FLAGS_READONLY, NULL);
1987 if (RT_FAILURE(vrc))
1988 {
1989 VDCloseAll(pDisk);
1990 if (!fWriteToStdOut)
1991 {
1992 RTFileClose(outFile);
1993 RTFileDelete(dst.c_str());
1994 }
1995 RTMsgError("Cannot open the source image: %Rrc", vrc);
1996 return 1;
1997 }
1998
1999 uint64_t cbSize = VDGetSize(pDisk, VD_LAST_IMAGE);
2000 uint64_t offFile = 0;
2001#define RAW_BUFFER_SIZE _128K
2002 size_t cbBuf = RAW_BUFFER_SIZE;
2003 void *pvBuf = RTMemAlloc(cbBuf);
2004 if (pvBuf)
2005 {
2006 RTStrmPrintf(g_pStdErr, "Converting image \"%s\" with size %RU64 bytes (%RU64MB) to raw...\n", src.c_str(), cbSize, (cbSize + _1M - 1) / _1M);
2007 while (offFile < cbSize)
2008 {
2009 size_t cb = (size_t)RT_MIN(cbSize - offFile, cbBuf);
2010 vrc = VDRead(pDisk, offFile, pvBuf, cb);
2011 if (RT_FAILURE(vrc))
2012 break;
2013 vrc = RTFileWrite(outFile, pvBuf, cb, NULL);
2014 if (RT_FAILURE(vrc))
2015 break;
2016 offFile += cb;
2017 }
2018 if (RT_FAILURE(vrc))
2019 {
2020 VDCloseAll(pDisk);
2021 if (!fWriteToStdOut)
2022 {
2023 RTFileClose(outFile);
2024 RTFileDelete(dst.c_str());
2025 }
2026 RTMsgError("Cannot copy image data: %Rrc", vrc);
2027 return 1;
2028 }
2029 }
2030 else
2031 {
2032 vrc = VERR_NO_MEMORY;
2033 VDCloseAll(pDisk);
2034 if (!fWriteToStdOut)
2035 {
2036 RTFileClose(outFile);
2037 RTFileDelete(dst.c_str());
2038 }
2039 RTMsgError("Out of memory allocating read buffer");
2040 return 1;
2041 }
2042
2043 if (!fWriteToStdOut)
2044 RTFileClose(outFile);
2045 VDCloseAll(pDisk);
2046 return 0;
2047}
2048
2049static int CmdConvertHardDisk(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2050{
2051 Utf8Str srcformat;
2052 Utf8Str dstformat;
2053 Utf8Str src;
2054 Utf8Str dst;
2055 int vrc;
2056 PVBOXHDD pSrcDisk = NULL;
2057 PVBOXHDD pDstDisk = NULL;
2058 VDTYPE enmSrcType = VDTYPE_INVALID;
2059
2060 /* Parse the arguments. */
2061 for (int i = 0; i < argc; i++)
2062 {
2063 if (strcmp(argv[i], "-srcformat") == 0)
2064 {
2065 if (argc <= i + 1)
2066 {
2067 return errorArgument("Missing argument to '%s'", argv[i]);
2068 }
2069 i++;
2070 srcformat = argv[i];
2071 }
2072 else if (strcmp(argv[i], "-dstformat") == 0)
2073 {
2074 if (argc <= i + 1)
2075 {
2076 return errorArgument("Missing argument to '%s'", argv[i]);
2077 }
2078 i++;
2079 dstformat = argv[i];
2080 }
2081 else if (src.isEmpty())
2082 {
2083 src = argv[i];
2084 }
2085 else if (dst.isEmpty())
2086 {
2087 dst = argv[i];
2088 }
2089 else
2090 {
2091 return errorSyntax(USAGE_CONVERTHD, "Invalid parameter '%s'", argv[i]);
2092 }
2093 }
2094
2095 if (src.isEmpty())
2096 return errorSyntax(USAGE_CONVERTHD, "Mandatory input image parameter missing");
2097 if (dst.isEmpty())
2098 return errorSyntax(USAGE_CONVERTHD, "Mandatory output image parameter missing");
2099
2100
2101 PVDINTERFACE pVDIfs = NULL;
2102 VDINTERFACEERROR vdInterfaceError;
2103 vdInterfaceError.pfnError = handleVDError;
2104 vdInterfaceError.pfnMessage = handleVDMessage;
2105
2106 vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
2107 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
2108 AssertRC(vrc);
2109
2110 do
2111 {
2112 /* Try to determine input image format */
2113 if (srcformat.isEmpty())
2114 {
2115 char *pszFormat = NULL;
2116 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
2117 src.c_str(), &pszFormat, &enmSrcType);
2118 if (RT_FAILURE(vrc))
2119 {
2120 RTMsgError("No file format specified and autodetect failed - please specify format: %Rrc", vrc);
2121 break;
2122 }
2123 srcformat = pszFormat;
2124 RTStrFree(pszFormat);
2125 }
2126
2127 vrc = VDCreate(pVDIfs, enmSrcType, &pSrcDisk);
2128 if (RT_FAILURE(vrc))
2129 {
2130 RTMsgError("Cannot create the source virtual disk container: %Rrc", vrc);
2131 break;
2132 }
2133
2134 /* Open the input image */
2135 vrc = VDOpen(pSrcDisk, srcformat.c_str(), src.c_str(), VD_OPEN_FLAGS_READONLY, NULL);
2136 if (RT_FAILURE(vrc))
2137 {
2138 RTMsgError("Cannot open the source image: %Rrc", vrc);
2139 break;
2140 }
2141
2142 /* Output format defaults to VDI */
2143 if (dstformat.isEmpty())
2144 dstformat = "VDI";
2145
2146 vrc = VDCreate(pVDIfs, enmSrcType, &pDstDisk);
2147 if (RT_FAILURE(vrc))
2148 {
2149 RTMsgError("Cannot create the destination virtual disk container: %Rrc", vrc);
2150 break;
2151 }
2152
2153 uint64_t cbSize = VDGetSize(pSrcDisk, VD_LAST_IMAGE);
2154 RTStrmPrintf(g_pStdErr, "Converting image \"%s\" with size %RU64 bytes (%RU64MB)...\n", src.c_str(), cbSize, (cbSize + _1M - 1) / _1M);
2155
2156 /* Create the output image */
2157 vrc = VDCopy(pSrcDisk, VD_LAST_IMAGE, pDstDisk, dstformat.c_str(),
2158 dst.c_str(), false, 0, VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED,
2159 NULL, VD_OPEN_FLAGS_NORMAL, NULL, NULL, NULL);
2160 if (RT_FAILURE(vrc))
2161 {
2162 RTMsgError("Cannot copy the image: %Rrc", vrc);
2163 break;
2164 }
2165 }
2166 while (0);
2167 if (pDstDisk)
2168 VDCloseAll(pDstDisk);
2169 if (pSrcDisk)
2170 VDCloseAll(pSrcDisk);
2171
2172 return RT_SUCCESS(vrc) ? 0 : 1;
2173}
2174
2175/**
2176 * Tries to repair a corrupted hard disk image.
2177 *
2178 * @returns VBox status code
2179 */
2180static int CmdRepairHardDisk(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2181{
2182 Utf8Str image;
2183 Utf8Str format;
2184 int vrc;
2185 bool fDryRun = false;
2186 PVBOXHDD pDisk = NULL;
2187
2188 /* Parse the arguments. */
2189 for (int i = 0; i < argc; i++)
2190 {
2191 if (strcmp(argv[i], "-dry-run") == 0)
2192 {
2193 fDryRun = true;
2194 }
2195 else if (strcmp(argv[i], "-format") == 0)
2196 {
2197 if (argc <= i + 1)
2198 {
2199 return errorArgument("Missing argument to '%s'", argv[i]);
2200 }
2201 i++;
2202 format = argv[i];
2203 }
2204 else if (image.isEmpty())
2205 {
2206 image = argv[i];
2207 }
2208 else
2209 {
2210 return errorSyntax(USAGE_REPAIRHD, "Invalid parameter '%s'", argv[i]);
2211 }
2212 }
2213
2214 if (image.isEmpty())
2215 return errorSyntax(USAGE_REPAIRHD, "Mandatory input image parameter missing");
2216
2217 PVDINTERFACE pVDIfs = NULL;
2218 VDINTERFACEERROR vdInterfaceError;
2219 vdInterfaceError.pfnError = handleVDError;
2220 vdInterfaceError.pfnMessage = handleVDMessage;
2221
2222 vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
2223 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
2224 AssertRC(vrc);
2225
2226 do
2227 {
2228 /* Try to determine input image format */
2229 if (format.isEmpty())
2230 {
2231 char *pszFormat = NULL;
2232 VDTYPE enmSrcType = VDTYPE_INVALID;
2233
2234 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
2235 image.c_str(), &pszFormat, &enmSrcType);
2236 if (RT_FAILURE(vrc) && (vrc != VERR_VD_IMAGE_CORRUPTED))
2237 {
2238 RTMsgError("No file format specified and autodetect failed - please specify format: %Rrc", vrc);
2239 break;
2240 }
2241 format = pszFormat;
2242 RTStrFree(pszFormat);
2243 }
2244
2245 uint32_t fFlags = 0;
2246 if (fDryRun)
2247 fFlags |= VD_REPAIR_DRY_RUN;
2248
2249 vrc = VDRepair(pVDIfs, NULL, image.c_str(), format.c_str(), fFlags);
2250 }
2251 while (0);
2252
2253 return RT_SUCCESS(vrc) ? 0 : 1;
2254}
2255
2256/**
2257 * Unloads the necessary driver.
2258 *
2259 * @returns VBox status code
2260 */
2261int CmdModUninstall(void)
2262{
2263 int rc;
2264
2265 rc = SUPR3Uninstall();
2266 if (RT_SUCCESS(rc))
2267 return 0;
2268 if (rc == VERR_NOT_IMPLEMENTED)
2269 return 0;
2270 return E_FAIL;
2271}
2272
2273/**
2274 * Loads the necessary driver.
2275 *
2276 * @returns VBox status code
2277 */
2278int CmdModInstall(void)
2279{
2280 int rc;
2281
2282 rc = SUPR3Install();
2283 if (RT_SUCCESS(rc))
2284 return 0;
2285 if (rc == VERR_NOT_IMPLEMENTED)
2286 return 0;
2287 return E_FAIL;
2288}
2289
2290int CmdDebugLog(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2291{
2292 /*
2293 * The first parameter is the name or UUID of a VM with a direct session
2294 * that we wish to open.
2295 */
2296 if (argc < 1)
2297 return errorSyntax(USAGE_DEBUGLOG, "Missing VM name/UUID");
2298
2299 ComPtr<IMachine> ptrMachine;
2300 HRESULT rc;
2301 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
2302 ptrMachine.asOutParam()), 1);
2303
2304 CHECK_ERROR_RET(ptrMachine, LockMachine(aSession, LockType_Shared), 1);
2305
2306 /*
2307 * Get the debugger interface.
2308 */
2309 ComPtr<IConsole> ptrConsole;
2310 CHECK_ERROR_RET(aSession, COMGETTER(Console)(ptrConsole.asOutParam()), 1);
2311
2312 ComPtr<IMachineDebugger> ptrDebugger;
2313 CHECK_ERROR_RET(ptrConsole, COMGETTER(Debugger)(ptrDebugger.asOutParam()), 1);
2314
2315 /*
2316 * Parse the command.
2317 */
2318 bool fEnablePresent = false;
2319 bool fEnable = false;
2320 bool fFlagsPresent = false;
2321 RTCString strFlags;
2322 bool fGroupsPresent = false;
2323 RTCString strGroups;
2324 bool fDestsPresent = false;
2325 RTCString strDests;
2326
2327 static const RTGETOPTDEF s_aOptions[] =
2328 {
2329 { "--disable", 'E', RTGETOPT_REQ_NOTHING },
2330 { "--enable", 'e', RTGETOPT_REQ_NOTHING },
2331 { "--flags", 'f', RTGETOPT_REQ_STRING },
2332 { "--groups", 'g', RTGETOPT_REQ_STRING },
2333 { "--destinations", 'd', RTGETOPT_REQ_STRING }
2334 };
2335
2336 int ch;
2337 RTGETOPTUNION ValueUnion;
2338 RTGETOPTSTATE GetState;
2339 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
2340 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
2341 {
2342 switch (ch)
2343 {
2344 case 'e':
2345 fEnablePresent = true;
2346 fEnable = true;
2347 break;
2348
2349 case 'E':
2350 fEnablePresent = true;
2351 fEnable = false;
2352 break;
2353
2354 case 'f':
2355 fFlagsPresent = true;
2356 if (*ValueUnion.psz)
2357 {
2358 if (strFlags.isNotEmpty())
2359 strFlags.append(' ');
2360 strFlags.append(ValueUnion.psz);
2361 }
2362 break;
2363
2364 case 'g':
2365 fGroupsPresent = true;
2366 if (*ValueUnion.psz)
2367 {
2368 if (strGroups.isNotEmpty())
2369 strGroups.append(' ');
2370 strGroups.append(ValueUnion.psz);
2371 }
2372 break;
2373
2374 case 'd':
2375 fDestsPresent = true;
2376 if (*ValueUnion.psz)
2377 {
2378 if (strDests.isNotEmpty())
2379 strDests.append(' ');
2380 strDests.append(ValueUnion.psz);
2381 }
2382 break;
2383
2384 default:
2385 return errorGetOpt(USAGE_DEBUGLOG , ch, &ValueUnion);
2386 }
2387 }
2388
2389 /*
2390 * Do the job.
2391 */
2392 if (fEnablePresent && !fEnable)
2393 CHECK_ERROR_RET(ptrDebugger, COMSETTER(LogEnabled)(FALSE), 1);
2394
2395 /** @todo flags, groups destination. */
2396 if (fFlagsPresent || fGroupsPresent || fDestsPresent)
2397 RTMsgWarning("One or more of the requested features are not implemented! Feel free to do this.");
2398
2399 if (fEnablePresent && fEnable)
2400 CHECK_ERROR_RET(ptrDebugger, COMSETTER(LogEnabled)(TRUE), 1);
2401 return 0;
2402}
2403
2404/**
2405 * Generate a SHA-256 password hash
2406 */
2407int CmdGeneratePasswordHash(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2408{
2409 /* one parameter, the password to hash */
2410 if (argc != 1)
2411 return errorSyntax(USAGE_PASSWORDHASH, "password to hash required");
2412
2413 uint8_t abDigest[RTSHA256_HASH_SIZE];
2414 RTSha256(argv[0], strlen(argv[0]), abDigest);
2415 char pszDigest[RTSHA256_DIGEST_LEN + 1];
2416 RTSha256ToString(abDigest, pszDigest, sizeof(pszDigest));
2417 RTPrintf("Password hash: %s\n", pszDigest);
2418
2419 return 0;
2420}
2421
2422/**
2423 * Print internal guest statistics or
2424 * set internal guest statistics update interval if specified
2425 */
2426int CmdGuestStats(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2427{
2428 /* one parameter, guest name */
2429 if (argc < 1)
2430 return errorSyntax(USAGE_GUESTSTATS, "Missing VM name/UUID");
2431
2432 /*
2433 * Parse the command.
2434 */
2435 ULONG aUpdateInterval = 0;
2436
2437 static const RTGETOPTDEF s_aOptions[] =
2438 {
2439 { "--interval", 'i', RTGETOPT_REQ_UINT32 }
2440 };
2441
2442 int ch;
2443 RTGETOPTUNION ValueUnion;
2444 RTGETOPTSTATE GetState;
2445 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
2446 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
2447 {
2448 switch (ch)
2449 {
2450 case 'i':
2451 aUpdateInterval = ValueUnion.u32;
2452 break;
2453
2454 default:
2455 return errorGetOpt(USAGE_GUESTSTATS , ch, &ValueUnion);
2456 }
2457 }
2458
2459 if (argc > 1 && aUpdateInterval == 0)
2460 return errorSyntax(USAGE_GUESTSTATS, "Invalid update interval specified");
2461
2462 RTPrintf("argc=%d interval=%u\n", argc, aUpdateInterval);
2463
2464 ComPtr<IMachine> ptrMachine;
2465 HRESULT rc;
2466 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
2467 ptrMachine.asOutParam()), 1);
2468
2469 CHECK_ERROR_RET(ptrMachine, LockMachine(aSession, LockType_Shared), 1);
2470
2471 /*
2472 * Get the guest interface.
2473 */
2474 ComPtr<IConsole> ptrConsole;
2475 CHECK_ERROR_RET(aSession, COMGETTER(Console)(ptrConsole.asOutParam()), 1);
2476
2477 ComPtr<IGuest> ptrGuest;
2478 CHECK_ERROR_RET(ptrConsole, COMGETTER(Guest)(ptrGuest.asOutParam()), 1);
2479
2480 if (aUpdateInterval)
2481 CHECK_ERROR_RET(ptrGuest, COMSETTER(StatisticsUpdateInterval)(aUpdateInterval), 1);
2482 else
2483 {
2484 ULONG mCpuUser, mCpuKernel, mCpuIdle;
2485 ULONG mMemTotal, mMemFree, mMemBalloon, mMemShared, mMemCache, mPageTotal;
2486 ULONG ulMemAllocTotal, ulMemFreeTotal, ulMemBalloonTotal, ulMemSharedTotal;
2487
2488 CHECK_ERROR_RET(ptrGuest, InternalGetStatistics(&mCpuUser, &mCpuKernel, &mCpuIdle,
2489 &mMemTotal, &mMemFree, &mMemBalloon, &mMemShared, &mMemCache,
2490 &mPageTotal, &ulMemAllocTotal, &ulMemFreeTotal, &ulMemBalloonTotal, &ulMemSharedTotal), 1);
2491 RTPrintf("mCpuUser=%u mCpuKernel=%u mCpuIdle=%u\n"
2492 "mMemTotal=%u mMemFree=%u mMemBalloon=%u mMemShared=%u mMemCache=%u\n"
2493 "mPageTotal=%u ulMemAllocTotal=%u ulMemFreeTotal=%u ulMemBalloonTotal=%u ulMemSharedTotal=%u\n",
2494 mCpuUser, mCpuKernel, mCpuIdle,
2495 mMemTotal, mMemFree, mMemBalloon, mMemShared, mMemCache,
2496 mPageTotal, ulMemAllocTotal, ulMemFreeTotal, ulMemBalloonTotal, ulMemSharedTotal);
2497
2498 }
2499
2500 return 0;
2501}
2502
2503
2504/**
2505 * Wrapper for handling internal commands
2506 */
2507int handleInternalCommands(HandlerArg *a)
2508{
2509 g_fInternalMode = true;
2510
2511 /* at least a command is required */
2512 if (a->argc < 1)
2513 return errorSyntax(USAGE_ALL, "Command missing");
2514
2515 /*
2516 * The 'string switch' on command name.
2517 */
2518 const char *pszCmd = a->argv[0];
2519 if (!strcmp(pszCmd, "loadmap"))
2520 return CmdLoadMap(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2521 if (!strcmp(pszCmd, "loadsyms"))
2522 return CmdLoadSyms(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2523 //if (!strcmp(pszCmd, "unloadsyms"))
2524 // return CmdUnloadSyms(argc - 1 , &a->argv[1]);
2525 if (!strcmp(pszCmd, "sethduuid") || !strcmp(pszCmd, "sethdparentuuid"))
2526 return CmdSetHDUUID(a->argc, &a->argv[0], a->virtualBox, a->session);
2527 if (!strcmp(pszCmd, "dumphdinfo"))
2528 return CmdDumpHDInfo(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2529 if (!strcmp(pszCmd, "listpartitions"))
2530 return CmdListPartitions(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2531 if (!strcmp(pszCmd, "createrawvmdk"))
2532 return CmdCreateRawVMDK(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2533 if (!strcmp(pszCmd, "renamevmdk"))
2534 return CmdRenameVMDK(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2535 if (!strcmp(pszCmd, "converttoraw"))
2536 return CmdConvertToRaw(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2537 if (!strcmp(pszCmd, "converthd"))
2538 return CmdConvertHardDisk(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2539 if (!strcmp(pszCmd, "modinstall"))
2540 return CmdModInstall();
2541 if (!strcmp(pszCmd, "moduninstall"))
2542 return CmdModUninstall();
2543 if (!strcmp(pszCmd, "debuglog"))
2544 return CmdDebugLog(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2545 if (!strcmp(pszCmd, "passwordhash"))
2546 return CmdGeneratePasswordHash(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2547 if (!strcmp(pszCmd, "gueststats"))
2548 return CmdGuestStats(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2549 if (!strcmp(pszCmd, "repairhd"))
2550 return CmdRepairHardDisk(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2551
2552 /* default: */
2553 return errorSyntax(USAGE_ALL, "Invalid command '%s'", a->argv[0]);
2554}
2555
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use