VirtualBox

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

Last change on this file since 70693 was 69706, checked in by vboxsync, 7 years ago

VBoxManage: Fix format string. ticketref:17236

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