VirtualBox

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

Last change on this file since 15240 was 14838, checked in by vboxsync, 16 years ago

compile fix

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 55.5 KB
Line 
1/* $Id: VBoxInternalManage.cpp 14838 2008-11-30 21:31: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-2007 Sun Microsystems, Inc.
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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
22 * Clara, CA 95054 USA or visit http://www.sun.com if you need
23 * additional information or have any questions.
24 */
25
26
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#include <VBox/com/com.h>
32#include <VBox/com/string.h>
33#include <VBox/com/Guid.h>
34#include <VBox/com/ErrorInfo.h>
35
36#include <VBox/com/VirtualBox.h>
37
38#include <VBox/VBoxHDD.h>
39#include <VBox/VBoxHDD-new.h>
40#include <VBox/sup.h>
41#include <VBox/err.h>
42#include <VBox/log.h>
43
44#include <iprt/file.h>
45#include <iprt/initterm.h>
46#include <iprt/stream.h>
47#include <iprt/string.h>
48#include <iprt/uuid.h>
49
50
51#include "VBoxManage.h"
52
53/* Includes for the raw disk stuff. */
54#ifdef RT_OS_WINDOWS
55# include <windows.h>
56# include <winioctl.h>
57#elif defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS)
58# include <errno.h>
59# include <sys/ioctl.h>
60# include <sys/types.h>
61# include <sys/stat.h>
62# include <fcntl.h>
63# include <unistd.h>
64#endif
65#ifdef RT_OS_LINUX
66# include <sys/utsname.h>
67# include <linux/hdreg.h>
68# include <linux/fs.h>
69# include <stdlib.h> /* atoi() */
70#endif /* RT_OS_LINUX */
71#ifdef RT_OS_DARWIN
72# include <sys/disk.h>
73#endif /* RT_OS_DARWIN */
74#ifdef RT_OS_SOLARIS
75# include <stropts.h>
76# include <sys/dkio.h>
77# include <sys/vtoc.h>
78#endif /* RT_OS_SOLARIS */
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. Ridiculously large number,
87 * but the memory consumption is rather low so who cares about never using
88 * most entries. */
89#define HOSTPARTITION_MAX 100
90
91
92typedef struct HOSTPARTITION
93{
94 unsigned uIndex;
95 unsigned uType;
96 unsigned uStartCylinder;
97 unsigned uStartHead;
98 unsigned uStartSector;
99 unsigned uEndCylinder;
100 unsigned uEndHead;
101 unsigned uEndSector;
102 uint64_t uStart;
103 uint64_t uSize;
104 uint64_t uPartDataStart;
105 uint64_t cPartDataSectors;
106} HOSTPARTITION, *PHOSTPARTITION;
107
108typedef struct HOSTPARTITIONS
109{
110 unsigned cPartitions;
111 HOSTPARTITION aPartitions[HOSTPARTITION_MAX];
112} HOSTPARTITIONS, *PHOSTPARTITIONS;
113
114/** flag whether we're in internal mode */
115bool g_fInternalMode;
116
117/**
118 * Print the usage info.
119 */
120void printUsageInternal(USAGECATEGORY u64Cmd)
121{
122 RTPrintf("Usage: VBoxManage internalcommands <command> [command arguments]\n"
123 "\n"
124 "Commands:\n"
125 "\n"
126 "%s%s%s%s%s%s%s%s"
127 "WARNING: This is a development tool and shall only be used to analyse\n"
128 " problems. It is completely unsupported and will change in\n"
129 " incompatible ways without warning.\n",
130 (u64Cmd & USAGE_LOADSYMS) ?
131 " loadsyms <vmname>|<uuid> <symfile> [delta] [module] [module address]\n"
132 " This will instruct DBGF to load the given symbolfile\n"
133 " during initialization.\n"
134 "\n"
135 : "",
136 (u64Cmd & USAGE_UNLOADSYMS) ?
137 " unloadsyms <vmname>|<uuid> <symfile>\n"
138 " Removes <symfile> from the list of symbol files that\n"
139 " should be loaded during DBF initialization.\n"
140 "\n"
141 : "",
142 (u64Cmd & USAGE_SETVDIUUID) ?
143 " setvdiuuid <filepath>\n"
144 " Assigns a new UUID to the given VDI file. This way, multiple copies\n"
145 " of VDI containers can be registered.\n"
146 "\n"
147 : "",
148 (u64Cmd & USAGE_LISTPARTITIONS) ?
149 " listpartitions -rawdisk <diskname>\n"
150 " Lists all partitions on <diskname>.\n"
151 "\n"
152 : "",
153 (u64Cmd & USAGE_CREATERAWVMDK) ?
154 " createrawvmdk -filename <filename> -rawdisk <diskname>\n"
155 " [-partitions <list of partition numbers> [-mbr <filename>] ]\n"
156 " [-register] [-relative]\n"
157 " Creates a new VMDK image which gives access to an entite host disk (if\n"
158 " the parameter -partitions is not specified) or some partitions of a\n"
159 " host disk. If access to individual partitions is granted, then the\n"
160 " parameter -mbr can be used to specify an alternative MBR to be used\n"
161 " (the partitioning information in the MBR file is ignored).\n"
162 " The diskname is on Linux e.g. /dev/sda, and on Windows e.g.\n"
163 " \\\\.\\PhysicalDrive0).\n"
164 " On Linux host the parameter -relative causes a VMDK file to be created\n"
165 " which refers to individual partitions instead to the entire disk.\n"
166 " Optionally the created image can be immediately registered.\n"
167 " The necessary partition numbers can be queried with\n"
168 " VBoxManage internalcommands listpartitions\n"
169 "\n"
170 : "",
171 (u64Cmd & USAGE_RENAMEVMDK) ?
172 " renamevmdk -from <filename> -to <filename>\n"
173 " Renames an existing VMDK image, including the base file and all its extents.\n"
174 "\n"
175 : "",
176 (u64Cmd & USAGE_CONVERTTORAW) ?
177 " converttoraw [-format <fileformat>] <filename> <outputfile>"
178#ifdef ENABLE_CONVERT_RAW_TO_STDOUT
179 "|stdout"
180#endif /* ENABLE_CONVERT_RAW_TO_STDOUT */
181 "\n"
182 " Convert image to raw, writing to file"
183#ifdef ENABLE_CONVERT_RAW_TO_STDOUT
184 " or stdout"
185#endif /* ENABLE_CONVERT_RAW_TO_STDOUT */
186 ".\n"
187 "\n"
188 : "",
189 (u64Cmd & USAGE_CONVERTDISK) ?
190 " convertdisk [-srcformat <fmt>] [-dstformat <fmt>] <inputfile> <outputfile>"
191 "\n"
192 " Convert image to another image format.\n"
193 "\n"
194 : "",
195#ifdef RT_OS_WINDOWS
196 (u64Cmd & USAGE_MODINSTALL) ?
197 " modinstall\n"
198 " Installs the neccessary driver for the host OS\n"
199 "\n"
200 : "",
201 (u64Cmd & USAGE_MODUNINSTALL) ?
202 " moduninstall\n"
203 " Deinstalls the driver\n"
204 "\n"
205 : ""
206#else
207 "",
208 ""
209#endif
210 );
211}
212
213/** @todo this is no longer necessary, we can enumerate extra data */
214/**
215 * Finds a new unique key name.
216 *
217 * I don't think this is 100% race condition proof, but we assumes
218 * the user is not trying to push this point.
219 *
220 * @returns Result from the insert.
221 * @param pMachine The Machine object.
222 * @param pszKeyBase The base key.
223 * @param rKey Reference to the string object in which we will return the key.
224 */
225static HRESULT NewUniqueKey(ComPtr<IMachine> pMachine, const char *pszKeyBase, Utf8Str &rKey)
226{
227 Bstr Keys;
228 HRESULT hrc = pMachine->GetExtraData(Bstr(pszKeyBase), Keys.asOutParam());
229 if (FAILED(hrc))
230 return hrc;
231
232 /* if there are no keys, it's simple. */
233 if (Keys.isEmpty())
234 {
235 rKey = "1";
236 return pMachine->SetExtraData(Bstr(pszKeyBase), Bstr("1"));
237 }
238
239 /* find a unique number - brute force rulez. */
240 Utf8Str KeysUtf8(Keys);
241 const char *pszKeys = RTStrStripL(KeysUtf8.raw());
242 for (unsigned i = 1; i < 1000000; i++)
243 {
244 char szKey[32];
245 size_t cchKey = RTStrPrintf(szKey, sizeof(szKey), "%#x", i);
246 const char *psz = strstr(pszKeys, szKey);
247 while (psz)
248 {
249 if ( ( psz == pszKeys
250 || psz[-1] == ' ')
251 && ( psz[cchKey] == ' '
252 || !psz[cchKey])
253 )
254 break;
255 psz = strstr(psz + cchKey, szKey);
256 }
257 if (!psz)
258 {
259 rKey = szKey;
260 Utf8StrFmt NewKeysUtf8("%s %s", pszKeys, szKey);
261 return pMachine->SetExtraData(Bstr(pszKeyBase), Bstr(NewKeysUtf8));
262 }
263 }
264 RTPrintf("Error: Cannot find unique key for '%s'!\n", pszKeyBase);
265 return E_FAIL;
266}
267
268
269#if 0
270/**
271 * Remove a key.
272 *
273 * I don't think this isn't 100% race condition proof, but we assumes
274 * the user is not trying to push this point.
275 *
276 * @returns Result from the insert.
277 * @param pMachine The machine object.
278 * @param pszKeyBase The base key.
279 * @param pszKey The key to remove.
280 */
281static HRESULT RemoveKey(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey)
282{
283 Bstr Keys;
284 HRESULT hrc = pMachine->GetExtraData(Bstr(pszKeyBase), Keys.asOutParam());
285 if (FAILED(hrc))
286 return hrc;
287
288 /* if there are no keys, it's simple. */
289 if (Keys.isEmpty())
290 return S_OK;
291
292 char *pszKeys;
293 int rc = RTUtf16ToUtf8(Keys.raw(), &pszKeys);
294 if (RT_SUCCESS(rc))
295 {
296 /* locate it */
297 size_t cchKey = strlen(pszKey);
298 char *psz = strstr(pszKeys, pszKey);
299 while (psz)
300 {
301 if ( ( psz == pszKeys
302 || psz[-1] == ' ')
303 && ( psz[cchKey] == ' '
304 || !psz[cchKey])
305 )
306 break;
307 psz = strstr(psz + cchKey, pszKey);
308 }
309 if (psz)
310 {
311 /* remove it */
312 char *pszNext = RTStrStripL(psz + cchKey);
313 if (*pszNext)
314 memmove(psz, pszNext, strlen(pszNext) + 1);
315 else
316 *psz = '\0';
317 psz = RTStrStrip(pszKeys);
318
319 /* update */
320 hrc = pMachine->SetExtraData(Bstr(pszKeyBase), Bstr(psz));
321 }
322
323 RTStrFree(pszKeys);
324 return hrc;
325 }
326 else
327 RTPrintf("error: failed to delete key '%s' from '%s', string conversion error %Rrc!\n",
328 pszKey, pszKeyBase, rc);
329
330 return E_FAIL;
331}
332#endif
333
334
335/**
336 * Sets a key value, does necessary error bitching.
337 *
338 * @returns COM status code.
339 * @param pMachine The Machine object.
340 * @param pszKeyBase The key base.
341 * @param pszKey The key.
342 * @param pszAttribute The attribute name.
343 * @param pszValue The string value.
344 */
345static HRESULT SetString(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey, const char *pszAttribute, const char *pszValue)
346{
347 HRESULT hrc = pMachine->SetExtraData(Bstr(Utf8StrFmt("%s/%s/%s", pszKeyBase, pszKey, pszAttribute)), Bstr(pszValue));
348 if (FAILED(hrc))
349 RTPrintf("error: Failed to set '%s/%s/%s' to '%s'! hrc=%#x\n",
350 pszKeyBase, pszKey, pszAttribute, pszValue, hrc);
351 return hrc;
352}
353
354
355/**
356 * Sets a key value, does necessary error bitching.
357 *
358 * @returns COM status code.
359 * @param pMachine The Machine object.
360 * @param pszKeyBase The key base.
361 * @param pszKey The key.
362 * @param pszAttribute The attribute name.
363 * @param u64Value The value.
364 */
365static HRESULT SetUInt64(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey, const char *pszAttribute, uint64_t u64Value)
366{
367 char szValue[64];
368 RTStrPrintf(szValue, sizeof(szValue), "%#RX64", u64Value);
369 return SetString(pMachine, pszKeyBase, pszKey, pszAttribute, szValue);
370}
371
372
373/**
374 * Sets a key value, does necessary error bitching.
375 *
376 * @returns COM status code.
377 * @param pMachine The Machine object.
378 * @param pszKeyBase The key base.
379 * @param pszKey The key.
380 * @param pszAttribute The attribute name.
381 * @param i64Value The value.
382 */
383static HRESULT SetInt64(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey, const char *pszAttribute, int64_t i64Value)
384{
385 char szValue[64];
386 RTStrPrintf(szValue, sizeof(szValue), "%RI64", i64Value);
387 return SetString(pMachine, pszKeyBase, pszKey, pszAttribute, szValue);
388}
389
390
391/**
392 * Identical to the 'loadsyms' command.
393 */
394static int CmdLoadSyms(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
395{
396 HRESULT rc;
397
398 /*
399 * Get the VM
400 */
401 ComPtr<IMachine> machine;
402 /* assume it's a UUID */
403 rc = aVirtualBox->GetMachine(Guid(argv[0]), machine.asOutParam());
404 if (FAILED(rc) || !machine)
405 {
406 /* must be a name */
407 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]), machine.asOutParam()), 1);
408 }
409
410 /*
411 * Parse the command.
412 */
413 const char *pszFilename;
414 int64_t offDelta = 0;
415 const char *pszModule = NULL;
416 uint64_t ModuleAddress = ~0;
417 uint64_t ModuleSize = 0;
418
419 /* filename */
420 if (argc < 2)
421 return errorArgument("Missing the filename argument!\n");
422 pszFilename = argv[1];
423
424 /* offDelta */
425 if (argc >= 3)
426 {
427 int rc = RTStrToInt64Ex(argv[2], NULL, 0, &offDelta);
428 if (RT_FAILURE(rc))
429 return errorArgument(argv[0], "Failed to read delta '%s', rc=%Rrc\n", argv[2], rc);
430 }
431
432 /* pszModule */
433 if (argc >= 4)
434 pszModule = argv[3];
435
436 /* ModuleAddress */
437 if (argc >= 5)
438 {
439 int rc = RTStrToUInt64Ex(argv[4], NULL, 0, &ModuleAddress);
440 if (RT_FAILURE(rc))
441 return errorArgument(argv[0], "Failed to read module address '%s', rc=%Rrc\n", argv[4], rc);
442 }
443
444 /* ModuleSize */
445 if (argc >= 6)
446 {
447 int rc = RTStrToUInt64Ex(argv[5], NULL, 0, &ModuleSize);
448 if (RT_FAILURE(rc))
449 return errorArgument(argv[0], "Failed to read module size '%s', rc=%Rrc\n", argv[5], rc);
450 }
451
452 /*
453 * Add extra data.
454 */
455 Utf8Str KeyStr;
456 HRESULT hrc = NewUniqueKey(machine, "VBoxInternal/DBGF/loadsyms", KeyStr);
457 if (SUCCEEDED(hrc))
458 hrc = SetString(machine, "VBoxInternal/DBGF/loadsyms", KeyStr, "Filename", pszFilename);
459 if (SUCCEEDED(hrc) && argc >= 3)
460 hrc = SetInt64(machine, "VBoxInternal/DBGF/loadsyms", KeyStr, "Delta", offDelta);
461 if (SUCCEEDED(hrc) && argc >= 4)
462 hrc = SetString(machine, "VBoxInternal/DBGF/loadsyms", KeyStr, "Module", pszModule);
463 if (SUCCEEDED(hrc) && argc >= 5)
464 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadsyms", KeyStr, "ModuleAddress", ModuleAddress);
465 if (SUCCEEDED(hrc) && argc >= 6)
466 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadsyms", KeyStr, "ModuleSize", ModuleSize);
467
468 return FAILED(hrc);
469}
470
471static int handleSetVDIUUID(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
472{
473 /* we need exactly one parameter: the vdi file */
474 if (argc != 1)
475 {
476 return errorSyntax(USAGE_SETVDIUUID, "Not enough parameters");
477 }
478
479 /* generate a new UUID */
480 Guid uuid;
481 uuid.create();
482
483 /* just try it */
484 int rc = VDISetImageUUIDs(argv[0], uuid.raw(), NULL, NULL, NULL);
485 if (RT_FAILURE(rc))
486 {
487 RTPrintf("Error while setting a new UUID: %Rrc (%d)\n", rc, rc);
488 }
489 else
490 {
491 RTPrintf("UUID changed to: %s\n", uuid.toString().raw());
492 }
493
494 return 0;
495}
496
497
498static DECLCALLBACK(void) handleVDError(void *pvUser, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list va)
499{
500 RTPrintf("ERROR: ");
501 RTPrintfV(pszFormat, va);
502 RTPrintf("\n");
503 RTPrintf("Error code %Rrc at %s(%u) in function %s\n", rc, RT_SRC_POS_ARGS);
504}
505
506static int partRead(RTFILE File, PHOSTPARTITIONS pPart)
507{
508 uint8_t aBuffer[512];
509 int rc;
510
511 pPart->cPartitions = 0;
512 memset(pPart->aPartitions, '\0', sizeof(pPart->aPartitions));
513 rc = RTFileReadAt(File, 0, &aBuffer, sizeof(aBuffer), NULL);
514 if (RT_FAILURE(rc))
515 return rc;
516 if (aBuffer[510] != 0x55 || aBuffer[511] != 0xaa)
517 return VERR_INVALID_PARAMETER;
518
519 unsigned uExtended = (unsigned)-1;
520
521 for (unsigned i = 0; i < 4; i++)
522 {
523 uint8_t *p = &aBuffer[0x1be + i * 16];
524 if (p[4] == 0)
525 continue;
526 PHOSTPARTITION pCP = &pPart->aPartitions[pPart->cPartitions++];
527 pCP->uIndex = i + 1;
528 pCP->uType = p[4];
529 pCP->uStartCylinder = (uint32_t)p[3] + ((uint32_t)(p[2] & 0xc0) << 2);
530 pCP->uStartHead = p[1];
531 pCP->uStartSector = p[2] & 0x3f;
532 pCP->uEndCylinder = (uint32_t)p[7] + ((uint32_t)(p[6] & 0xc0) << 2);
533 pCP->uEndHead = p[5];
534 pCP->uEndSector = p[6] & 0x3f;
535 pCP->uStart = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
536 pCP->uSize = RT_MAKE_U32_FROM_U8(p[12], p[13], p[14], p[15]);
537 pCP->uPartDataStart = 0; /* will be filled out later properly. */
538 pCP->cPartDataSectors = 0;
539
540 if (PARTTYPE_IS_EXTENDED(p[4]))
541 {
542 if (uExtended == (unsigned)-1)
543 uExtended = pCP - pPart->aPartitions;
544 else
545 {
546 RTPrintf("More than one extended partition. Aborting\n");
547 return VERR_INVALID_PARAMETER;
548 }
549 }
550 }
551
552 if (uExtended != (unsigned)-1)
553 {
554 unsigned uIndex = 5;
555 uint64_t uStart = pPart->aPartitions[uExtended].uStart;
556 uint64_t uOffset = 0;
557 if (!uStart)
558 {
559 RTPrintf("Inconsistency for logical partition start. Aborting\n");
560 return VERR_INVALID_PARAMETER;
561 }
562
563 do
564 {
565 rc = RTFileReadAt(File, (uStart + uOffset) * 512, &aBuffer, sizeof(aBuffer), NULL);
566 if (RT_FAILURE(rc))
567 return rc;
568
569 if (aBuffer[510] != 0x55 || aBuffer[511] != 0xaa)
570 {
571 RTPrintf("Logical partition without magic. Aborting\n");
572 return VERR_INVALID_PARAMETER;
573 }
574 uint8_t *p = &aBuffer[0x1be];
575
576 if (p[4] == 0)
577 {
578 RTPrintf("Logical partition with type 0 encountered. Aborting\n");
579 return VERR_INVALID_PARAMETER;
580 }
581
582 PHOSTPARTITION pCP = &pPart->aPartitions[pPart->cPartitions++];
583 pCP->uIndex = uIndex;
584 pCP->uType = p[4];
585 pCP->uStartCylinder = (uint32_t)p[3] + ((uint32_t)(p[2] & 0xc0) << 2);
586 pCP->uStartHead = p[1];
587 pCP->uStartSector = p[2] & 0x3f;
588 pCP->uEndCylinder = (uint32_t)p[7] + ((uint32_t)(p[6] & 0xc0) << 2);
589 pCP->uEndHead = p[5];
590 pCP->uEndSector = p[6] & 0x3f;
591 uint32_t uStartOffset = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
592 if (!uStartOffset)
593 {
594 RTPrintf("Invalid partition start offset. Aborting\n");
595 return VERR_INVALID_PARAMETER;
596 }
597 pCP->uStart = uStart + uOffset + uStartOffset;
598 pCP->uSize = RT_MAKE_U32_FROM_U8(p[12], p[13], p[14], p[15]);
599 /* Fill out partitioning location info for EBR. */
600 pCP->uPartDataStart = uStart + uOffset;
601 pCP->cPartDataSectors = uStartOffset;
602 p += 16;
603 if (p[4] == 0)
604 uExtended = (unsigned)-1;
605 else if (PARTTYPE_IS_EXTENDED(p[4]))
606 {
607 uExtended = uIndex++;
608 uOffset = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
609 }
610 else
611 {
612 RTPrintf("Logical partition chain broken. Aborting\n");
613 return VERR_INVALID_PARAMETER;
614 }
615 } while (uExtended != (unsigned)-1);
616 }
617
618 /* Sort partitions in ascending order of start sector, plus a trivial
619 * bit of consistency checking. */
620 for (unsigned i = 0; i < pPart->cPartitions-1; i++)
621 {
622 unsigned uMinIdx = i;
623 uint64_t uMinVal = pPart->aPartitions[i].uStart;
624 for (unsigned j = i + 1; j < pPart->cPartitions; j++)
625 {
626 if (pPart->aPartitions[j].uStart < uMinVal)
627 {
628 uMinIdx = j;
629 uMinVal = pPart->aPartitions[j].uStart;
630 }
631 else if (pPart->aPartitions[j].uStart == uMinVal)
632 {
633 RTPrintf("Two partitions start at the same place. Aborting\n");
634 return VERR_INVALID_PARAMETER;
635 } else if (pPart->aPartitions[j].uStart == 0)
636 {
637 RTPrintf("Partition starts at sector 0. Aborting\n");
638 return VERR_INVALID_PARAMETER;
639 }
640 }
641 if (uMinIdx != i)
642 {
643 /* Swap entries at index i and uMinIdx. */
644 memcpy(&pPart->aPartitions[pPart->cPartitions],
645 &pPart->aPartitions[i], sizeof(HOSTPARTITION));
646 memcpy(&pPart->aPartitions[i],
647 &pPart->aPartitions[uMinIdx], sizeof(HOSTPARTITION));
648 memcpy(&pPart->aPartitions[uMinIdx],
649 &pPart->aPartitions[pPart->cPartitions], sizeof(HOSTPARTITION));
650 }
651 }
652
653 /* Now do a lot of consistency checking. */
654 uint64_t uPrevEnd = 0;
655 for (unsigned i = 0; i < pPart->cPartitions-1; i++)
656 {
657 if (pPart->aPartitions[i].cPartDataSectors)
658 {
659 if (pPart->aPartitions[i].uPartDataStart < uPrevEnd)
660 {
661 RTPrintf("Overlapping partition description areas. Aborting\n");
662 return VERR_INVALID_PARAMETER;
663 }
664 uPrevEnd = pPart->aPartitions[i].uPartDataStart + pPart->aPartitions[i].cPartDataSectors;
665 }
666 if (pPart->aPartitions[i].uStart < uPrevEnd)
667 {
668 RTPrintf("Overlapping partitions. Aborting\n");
669 return VERR_INVALID_PARAMETER;
670 }
671 if (!PARTTYPE_IS_EXTENDED(pPart->aPartitions[i].uType))
672 uPrevEnd = pPart->aPartitions[i].uStart + pPart->aPartitions[i].uSize;
673 }
674
675 /* Fill out partitioning location info for MBR. */
676 pPart->aPartitions[0].uPartDataStart = 0;
677 pPart->aPartitions[0].cPartDataSectors = pPart->aPartitions[0].uStart;
678
679 return VINF_SUCCESS;
680}
681
682static int CmdListPartitions(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
683{
684 Utf8Str rawdisk;
685
686 /* let's have a closer look at the arguments */
687 for (int i = 0; i < argc; i++)
688 {
689 if (strcmp(argv[i], "-rawdisk") == 0)
690 {
691 if (argc <= i + 1)
692 {
693 return errorArgument("Missing argument to '%s'", argv[i]);
694 }
695 i++;
696 rawdisk = argv[i];
697 }
698 else
699 {
700 return errorSyntax(USAGE_LISTPARTITIONS, "Invalid parameter '%s'", Utf8Str(argv[i]).raw());
701 }
702 }
703
704 if (rawdisk.isEmpty())
705 return errorSyntax(USAGE_LISTPARTITIONS, "Mandatory parameter -rawdisk missing");
706
707 RTFILE RawFile;
708 int vrc = RTFileOpen(&RawFile, rawdisk.raw(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE);
709 if (RT_FAILURE(vrc))
710 {
711 RTPrintf("Error opening the raw disk: %Rrc\n", vrc);
712 return vrc;
713 }
714
715 HOSTPARTITIONS partitions;
716 vrc = partRead(RawFile, &partitions);
717 if (RT_FAILURE(vrc))
718 return vrc;
719
720 RTPrintf("Number Type StartCHS EndCHS Size (MiB) Start (Sect)\n");
721 for (unsigned i = 0; i < partitions.cPartitions; i++)
722 {
723 /* Suppress printing the extended partition. Otherwise people
724 * might add it to the list of partitions for raw partition
725 * access (which is not good). */
726 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
727 continue;
728
729 RTPrintf("%-7u %#04x %-4u/%-3u/%-2u %-4u/%-3u/%-2u %10llu %10llu\n",
730 partitions.aPartitions[i].uIndex,
731 partitions.aPartitions[i].uType,
732 partitions.aPartitions[i].uStartCylinder,
733 partitions.aPartitions[i].uStartHead,
734 partitions.aPartitions[i].uStartSector,
735 partitions.aPartitions[i].uEndCylinder,
736 partitions.aPartitions[i].uEndHead,
737 partitions.aPartitions[i].uEndSector,
738 partitions.aPartitions[i].uSize / 2048,
739 partitions.aPartitions[i].uStart);
740 }
741
742 return 0;
743}
744
745static int CmdCreateRawVMDK(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
746{
747 HRESULT rc = S_OK;
748 Bstr filename;
749 const char *pszMBRFilename = NULL;
750 Utf8Str rawdisk;
751 const char *pszPartitions = NULL;
752 bool fRegister = false;
753 bool fRelative = false;
754
755 uint64_t cbSize = 0;
756 PVBOXHDD pDisk = NULL;
757 VBOXHDDRAW RawDescriptor;
758 HOSTPARTITIONS partitions;
759 uint32_t uPartitions = 0;
760 PVDINTERFACE pVDIfs = NULL;
761
762 /* let's have a closer look at the arguments */
763 for (int i = 0; i < argc; i++)
764 {
765 if (strcmp(argv[i], "-filename") == 0)
766 {
767 if (argc <= i + 1)
768 {
769 return errorArgument("Missing argument to '%s'", argv[i]);
770 }
771 i++;
772 filename = argv[i];
773 }
774 else if (strcmp(argv[i], "-mbr") == 0)
775 {
776 if (argc <= i + 1)
777 {
778 return errorArgument("Missing argument to '%s'", argv[i]);
779 }
780 i++;
781 pszMBRFilename = argv[i];
782 }
783 else if (strcmp(argv[i], "-rawdisk") == 0)
784 {
785 if (argc <= i + 1)
786 {
787 return errorArgument("Missing argument to '%s'", argv[i]);
788 }
789 i++;
790 rawdisk = argv[i];
791 }
792 else if (strcmp(argv[i], "-partitions") == 0)
793 {
794 if (argc <= i + 1)
795 {
796 return errorArgument("Missing argument to '%s'", argv[i]);
797 }
798 i++;
799 pszPartitions = argv[i];
800 }
801 else if (strcmp(argv[i], "-register") == 0)
802 {
803 fRegister = true;
804 }
805#ifdef RT_OS_LINUX
806 else if (strcmp(argv[i], "-relative") == 0)
807 {
808 fRelative = true;
809 }
810#endif /* RT_OS_LINUX */
811 else
812 {
813 return errorSyntax(USAGE_CREATERAWVMDK, "Invalid parameter '%s'", Utf8Str(argv[i]).raw());
814 }
815 }
816
817 if (filename.isEmpty())
818 return errorSyntax(USAGE_CREATERAWVMDK, "Mandatory parameter -filename missing");
819 if (rawdisk.isEmpty())
820 return errorSyntax(USAGE_CREATERAWVMDK, "Mandatory parameter -rawdisk missing");
821 if (!pszPartitions && pszMBRFilename)
822 return errorSyntax(USAGE_CREATERAWVMDK, "The parameter -mbr is only valid when the parameter -partitions is also present");
823
824 RTFILE RawFile;
825 int vrc = RTFileOpen(&RawFile, rawdisk.raw(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE);
826 if (RT_FAILURE(vrc))
827 {
828 RTPrintf("Error opening the raw disk '%s': %Rrc\n", rawdisk.raw(), vrc);
829 goto out;
830 }
831
832#ifdef RT_OS_WINDOWS
833 /* Windows NT has no IOCTL_DISK_GET_LENGTH_INFORMATION ioctl. This was
834 * added to Windows XP, so we have to use the available info from DriveGeo.
835 * Note that we cannot simply use IOCTL_DISK_GET_DRIVE_GEOMETRY as it
836 * yields a slightly different result than IOCTL_DISK_GET_LENGTH_INFO.
837 * We call IOCTL_DISK_GET_DRIVE_GEOMETRY first as we need to check the media
838 * type anyway, and if IOCTL_DISK_GET_LENGTH_INFORMATION is supported
839 * we will later override cbSize.
840 */
841 DISK_GEOMETRY DriveGeo;
842 DWORD cbDriveGeo;
843 if (DeviceIoControl((HANDLE)RawFile,
844 IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,
845 &DriveGeo, sizeof(DriveGeo), &cbDriveGeo, NULL))
846 {
847 if ( DriveGeo.MediaType == FixedMedia
848 || DriveGeo.MediaType == RemovableMedia)
849 {
850 cbSize = DriveGeo.Cylinders.QuadPart
851 * DriveGeo.TracksPerCylinder
852 * DriveGeo.SectorsPerTrack
853 * DriveGeo.BytesPerSector;
854 }
855 else
856 {
857 RTPrintf("File '%s' is no fixed/removable medium device\n", rawdisk.raw());
858 vrc = VERR_INVALID_PARAMETER;
859 goto out;
860 }
861
862 GET_LENGTH_INFORMATION DiskLenInfo;
863 DWORD junk;
864 if (DeviceIoControl((HANDLE)RawFile,
865 IOCTL_DISK_GET_LENGTH_INFO, NULL, 0,
866 &DiskLenInfo, sizeof(DiskLenInfo), &junk, (LPOVERLAPPED)NULL))
867 {
868 /* IOCTL_DISK_GET_LENGTH_INFO is supported -- override cbSize. */
869 cbSize = DiskLenInfo.Length.QuadPart;
870 }
871 }
872 else
873 {
874 vrc = RTErrConvertFromWin32(GetLastError());
875 RTPrintf("Error getting the geometry of the raw disk '%s': %Rrc\n", rawdisk.raw(), vrc);
876 goto out;
877 }
878#elif defined(RT_OS_LINUX)
879 struct stat DevStat;
880 if (!fstat(RawFile, &DevStat) && S_ISBLK(DevStat.st_mode))
881 {
882#ifdef BLKGETSIZE64
883 /* BLKGETSIZE64 is broken up to 2.4.17 and in many 2.5.x. In 2.6.0
884 * it works without problems. */
885 struct utsname utsname;
886 if ( uname(&utsname) == 0
887 && ( (strncmp(utsname.release, "2.5.", 4) == 0 && atoi(&utsname.release[4]) >= 18)
888 || (strncmp(utsname.release, "2.", 2) == 0 && atoi(&utsname.release[2]) >= 6)))
889 {
890 uint64_t cbBlk;
891 if (!ioctl(RawFile, BLKGETSIZE64, &cbBlk))
892 cbSize = cbBlk;
893 }
894#endif /* BLKGETSIZE64 */
895 if (!cbSize)
896 {
897 long cBlocks;
898 if (!ioctl(RawFile, BLKGETSIZE, &cBlocks))
899 cbSize = (uint64_t)cBlocks << 9;
900 else
901 {
902 vrc = RTErrConvertFromErrno(errno);
903 RTPrintf("Error getting the size of the raw disk '%s': %Rrc\n", rawdisk.raw(), vrc);
904 goto out;
905 }
906 }
907 }
908 else
909 {
910 RTPrintf("File '%s' is no block device\n", rawdisk.raw());
911 vrc = VERR_INVALID_PARAMETER;
912 goto out;
913 }
914#elif defined(RT_OS_DARWIN)
915 struct stat DevStat;
916 if (!fstat(RawFile, &DevStat) && S_ISBLK(DevStat.st_mode))
917 {
918 uint64_t cBlocks;
919 uint32_t cbBlock;
920 if (!ioctl(RawFile, DKIOCGETBLOCKCOUNT, &cBlocks))
921 {
922 if (!ioctl(RawFile, DKIOCGETBLOCKSIZE, &cbBlock))
923 cbSize = cBlocks * cbBlock;
924 else
925 {
926 RTPrintf("Cannot get the block size for file '%s': %Rrc", rawdisk.raw(), vrc);
927 vrc = RTErrConvertFromErrno(errno);
928 goto out;
929 }
930 }
931 else
932 {
933 vrc = RTErrConvertFromErrno(errno);
934 RTPrintf("Cannot get the block count for file '%s': %Rrc", rawdisk.raw(), vrc);
935 goto out;
936 }
937 }
938 else
939 {
940 RTPrintf("File '%s' is no block device\n", rawdisk.raw());
941 vrc = VERR_INVALID_PARAMETER;
942 goto out;
943 }
944#elif defined(RT_OS_SOLARIS)
945 struct stat DevStat;
946 if (!fstat(RawFile, &DevStat) && ( S_ISBLK(DevStat.st_mode)
947 || S_ISCHR(DevStat.st_mode)))
948 {
949 struct dk_minfo mediainfo;
950 if (!ioctl(RawFile, DKIOCGMEDIAINFO, &mediainfo))
951 cbSize = mediainfo.dki_capacity * mediainfo.dki_lbsize;
952 else
953 {
954 vrc = RTErrConvertFromErrno(errno);
955 RTPrintf("Error getting the size of the raw disk '%s': %Rrc\n", rawdisk.raw(), vrc);
956 goto out;
957 }
958 }
959 else
960 {
961 RTPrintf("File '%s' is no block or char device\n", rawdisk.raw());
962 vrc = VERR_INVALID_PARAMETER;
963 goto out;
964 }
965#else /* all unrecognized OSes */
966 /* Hopefully this works on all other hosts. If it doesn't, it'll just fail
967 * creating the VMDK, so no real harm done. */
968 vrc = RTFileGetSize(RawFile, &cbSize);
969 if (RT_FAILURE(vrc))
970 {
971 RTPrintf("Error getting the size of the raw disk '%s': %Rrc\n", rawdisk.raw(), vrc);
972 goto out;
973 }
974#endif
975
976 /* Check whether cbSize is actually sensible. */
977 if (!cbSize || cbSize % 512)
978 {
979 RTPrintf("Detected size of raw disk '%s' is %s, an invalid value\n", rawdisk.raw(), cbSize);
980 vrc = VERR_INVALID_PARAMETER;
981 goto out;
982 }
983
984 RawDescriptor.szSignature[0] = 'R';
985 RawDescriptor.szSignature[1] = 'A';
986 RawDescriptor.szSignature[2] = 'W';
987 RawDescriptor.szSignature[3] = '\0';
988 if (!pszPartitions)
989 {
990 RawDescriptor.fRawDisk = true;
991 RawDescriptor.pszRawDisk = rawdisk.raw();
992 }
993 else
994 {
995 RawDescriptor.fRawDisk = false;
996 RawDescriptor.pszRawDisk = NULL;
997 RawDescriptor.cPartitions = 0;
998
999 const char *p = pszPartitions;
1000 char *pszNext;
1001 uint32_t u32;
1002 while (*p != '\0')
1003 {
1004 vrc = RTStrToUInt32Ex(p, &pszNext, 0, &u32);
1005 if (RT_FAILURE(vrc))
1006 {
1007 RTPrintf("Incorrect value in partitions parameter\n");
1008 goto out;
1009 }
1010 uPartitions |= RT_BIT(u32);
1011 p = pszNext;
1012 if (*p == ',')
1013 p++;
1014 else if (*p != '\0')
1015 {
1016 RTPrintf("Incorrect separator in partitions parameter\n");
1017 vrc = VERR_INVALID_PARAMETER;
1018 goto out;
1019 }
1020 }
1021
1022 vrc = partRead(RawFile, &partitions);
1023 if (RT_FAILURE(vrc))
1024 {
1025 RTPrintf("Error reading the partition information from '%s'\n", rawdisk.raw());
1026 goto out;
1027 }
1028
1029 for (unsigned i = 0; i < partitions.cPartitions; i++)
1030 {
1031 if ( uPartitions & RT_BIT(partitions.aPartitions[i].uIndex)
1032 && PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1033 {
1034 /* Some ignorant user specified an extended partition.
1035 * Bad idea, as this would trigger an overlapping
1036 * partitions error later during VMDK creation. So warn
1037 * here and ignore what the user requested. */
1038 RTPrintf("Warning: it is not possible (and necessary) to explicitly give access to the\n"
1039 " extended partition %u. If required, enable access to all logical\n"
1040 " partitions inside this extended partition.\n", partitions.aPartitions[i].uIndex);
1041 uPartitions &= ~RT_BIT(partitions.aPartitions[i].uIndex);
1042 }
1043 }
1044
1045 RawDescriptor.cPartitions = partitions.cPartitions;
1046 RawDescriptor.pPartitions = (PVBOXHDDRAWPART)RTMemAllocZ(partitions.cPartitions * sizeof(VBOXHDDRAWPART));
1047 if (!RawDescriptor.pPartitions)
1048 {
1049 RTPrintf("Out of memory allocating the partition list for '%s'\n", rawdisk.raw());
1050 vrc = VERR_NO_MEMORY;
1051 goto out;
1052 }
1053 for (unsigned i = 0; i < partitions.cPartitions; i++)
1054 {
1055 if (uPartitions & RT_BIT(partitions.aPartitions[i].uIndex))
1056 {
1057 if (fRelative)
1058 {
1059#ifdef RT_OS_LINUX
1060 /* Refer to the correct partition and use offset 0. */
1061 char *pszRawName;
1062 vrc = RTStrAPrintf(&pszRawName, "%s%u", rawdisk.raw(),
1063 partitions.aPartitions[i].uIndex);
1064 if (RT_FAILURE(vrc))
1065 {
1066 RTPrintf("Error creating reference to individual partition %u, rc=%Rrc\n",
1067 partitions.aPartitions[i].uIndex, vrc);
1068 goto out;
1069 }
1070 RawDescriptor.pPartitions[i].pszRawDevice = pszRawName;
1071 RawDescriptor.pPartitions[i].uPartitionStartOffset = 0;
1072 RawDescriptor.pPartitions[i].uPartitionStart = partitions.aPartitions[i].uStart * 512;
1073#else
1074 /** @todo not implemented yet for Windows host. Treat just
1075 * like not specified (this code is actually never reached). */
1076 RawDescriptor.pPartitions[i].pszRawDevice = rawdisk.raw();
1077 RawDescriptor.pPartitions[i].uPartitionStartOffset = partitions.aPartitions[i].uStart * 512;
1078 RawDescriptor.pPartitions[i].uPartitionStart = partitions.aPartitions[i].uStart * 512;
1079#endif
1080 }
1081 else
1082 {
1083 /* This is the "everything refers to the base raw device"
1084 * variant. This requires opening the base device in RW
1085 * mode even for creation. */
1086 RawDescriptor.pPartitions[i].pszRawDevice = rawdisk.raw();
1087 RawDescriptor.pPartitions[i].uPartitionStartOffset = partitions.aPartitions[i].uStart * 512;
1088 RawDescriptor.pPartitions[i].uPartitionStart = partitions.aPartitions[i].uStart * 512;
1089 }
1090 }
1091 else
1092 {
1093 /* Suppress access to this partition. */
1094 RawDescriptor.pPartitions[i].pszRawDevice = NULL;
1095 RawDescriptor.pPartitions[i].uPartitionStartOffset = 0;
1096 /* This is used in the plausibility check in the creation
1097 * code. In theory it's a dummy, but I don't want to make
1098 * the VMDK creatiion any more complicated than what it needs
1099 * to be. */
1100 RawDescriptor.pPartitions[i].uPartitionStart = partitions.aPartitions[i].uStart * 512;
1101 }
1102 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1103 {
1104 /* Suppress exporting the actual extended partition. Only
1105 * logical partitions should be processed. However completely
1106 * ignoring it leads to leaving out the MBR data. */
1107 RawDescriptor.pPartitions[i].cbPartition = 0;
1108 }
1109 else
1110 RawDescriptor.pPartitions[i].cbPartition = partitions.aPartitions[i].uSize * 512;
1111 RawDescriptor.pPartitions[i].uPartitionDataStart = partitions.aPartitions[i].uPartDataStart * 512;
1112 RawDescriptor.pPartitions[i].cbPartitionData = partitions.aPartitions[i].cPartDataSectors * 512;
1113 if (RawDescriptor.pPartitions[i].cbPartitionData)
1114 {
1115 Assert (RawDescriptor.pPartitions[i].cbPartitionData -
1116 (size_t)RawDescriptor.pPartitions[i].cbPartitionData == 0);
1117 void *pPartData = RTMemAlloc((size_t)RawDescriptor.pPartitions[i].cbPartitionData);
1118 if (!pPartData)
1119 {
1120 RTPrintf("Out of memory allocating the partition descriptor for '%s'\n", rawdisk.raw());
1121 vrc = VERR_NO_MEMORY;
1122 goto out;
1123 }
1124 vrc = RTFileReadAt(RawFile, partitions.aPartitions[i].uPartDataStart * 512, pPartData, (size_t)RawDescriptor.pPartitions[i].cbPartitionData, NULL);
1125 if (RT_FAILURE(vrc))
1126 {
1127 RTPrintf("Cannot read partition data from raw device '%s': %Rrc\n", rawdisk.raw(), vrc);
1128 goto out;
1129 }
1130 /* Splice in the replacement MBR code if specified. */
1131 if ( partitions.aPartitions[i].uPartDataStart == 0
1132 && pszMBRFilename)
1133 {
1134 RTFILE MBRFile;
1135 vrc = RTFileOpen(&MBRFile, pszMBRFilename, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE);
1136 if (RT_FAILURE(vrc))
1137 {
1138 RTPrintf("Cannot open replacement MBR file '%s' specified with -mbr: %Rrc\n", pszMBRFilename, vrc);
1139 goto out;
1140 }
1141 vrc = RTFileReadAt(MBRFile, 0, pPartData, 0x1be, NULL);
1142 RTFileClose(MBRFile);
1143 if (RT_FAILURE(vrc))
1144 {
1145 RTPrintf("Cannot read replacement MBR file '%s': %Rrc\n", pszMBRFilename, vrc);
1146 goto out;
1147 }
1148 }
1149 RawDescriptor.pPartitions[i].pvPartitionData = pPartData;
1150 }
1151 }
1152 }
1153
1154 RTFileClose(RawFile);
1155
1156 VDINTERFACE vdInterfaceError;
1157 VDINTERFACEERROR vdInterfaceErrorCallbacks;
1158 vdInterfaceErrorCallbacks.cbSize = sizeof(VDINTERFACEERROR);
1159 vdInterfaceErrorCallbacks.enmInterface = VDINTERFACETYPE_ERROR;
1160 vdInterfaceErrorCallbacks.pfnError = handleVDError;
1161
1162 vrc = VDInterfaceAdd(&vdInterfaceError, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1163 &vdInterfaceErrorCallbacks, NULL, &pVDIfs);
1164 AssertRC(vrc);
1165
1166 vrc = VDCreate(&vdInterfaceError, &pDisk);
1167 if (RT_FAILURE(vrc))
1168 {
1169 RTPrintf("Error while creating the virtual disk container: %Rrc\n", vrc);
1170 goto out;
1171 }
1172
1173 Assert(RT_MIN(cbSize / 512 / 16 / 63, 16383) -
1174 (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383) == 0);
1175 PDMMEDIAGEOMETRY PCHS, LCHS;
1176 PCHS.cCylinders = (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383);
1177 PCHS.cHeads = 16;
1178 PCHS.cSectors = 63;
1179 LCHS.cCylinders = 0;
1180 LCHS.cHeads = 0;
1181 LCHS.cSectors = 0;
1182 vrc = VDCreateBase(pDisk, "VMDK", Utf8Str(filename).raw(),
1183 VD_IMAGE_TYPE_FIXED, cbSize,
1184 VD_VMDK_IMAGE_FLAGS_RAWDISK, (char *)&RawDescriptor,
1185 &PCHS, &LCHS, NULL, VD_OPEN_FLAGS_NORMAL, NULL, NULL);
1186 if (RT_FAILURE(vrc))
1187 {
1188 RTPrintf("Error while creating the raw disk VMDK: %Rrc\n", vrc);
1189 goto out;
1190 }
1191 RTPrintf("RAW host disk access VMDK file %s created successfully.\n", Utf8Str(filename).raw());
1192
1193 VDCloseAll(pDisk);
1194
1195 /* Clean up allocated memory etc. */
1196 if (pszPartitions)
1197 {
1198 for (unsigned i = 0; i < partitions.cPartitions; i++)
1199 {
1200 if (uPartitions & RT_BIT(partitions.aPartitions[i].uIndex))
1201 {
1202 if (fRelative)
1203 {
1204#ifdef RT_OS_LINUX
1205 /* Free memory allocated above. */
1206 RTStrFree((char *)(void *)RawDescriptor.pPartitions[i].pszRawDevice);
1207#endif /* RT_OS_LINUX */
1208 }
1209 }
1210 }
1211 }
1212
1213 if (fRegister)
1214 {
1215 ComPtr<IHardDisk2> hardDisk;
1216 CHECK_ERROR(aVirtualBox, OpenHardDisk2(filename, hardDisk.asOutParam()));
1217 }
1218
1219 return SUCCEEDED(rc) ? 0 : 1;
1220
1221out:
1222 RTPrintf("The raw disk vmdk file was not created\n");
1223 return RT_SUCCESS(vrc) ? 0 : 1;
1224}
1225
1226static int CmdRenameVMDK(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1227{
1228 Bstr src;
1229 Bstr dst;
1230 /* Parse the arguments. */
1231 for (int i = 0; i < argc; i++)
1232 {
1233 if (strcmp(argv[i], "-from") == 0)
1234 {
1235 if (argc <= i + 1)
1236 {
1237 return errorArgument("Missing argument to '%s'", argv[i]);
1238 }
1239 i++;
1240 src = argv[i];
1241 }
1242 else if (strcmp(argv[i], "-to") == 0)
1243 {
1244 if (argc <= i + 1)
1245 {
1246 return errorArgument("Missing argument to '%s'", argv[i]);
1247 }
1248 i++;
1249 dst = argv[i];
1250 }
1251 else
1252 {
1253 return errorSyntax(USAGE_RENAMEVMDK, "Invalid parameter '%s'", Utf8Str(argv[i]).raw());
1254 }
1255 }
1256
1257 if (src.isEmpty())
1258 return errorSyntax(USAGE_RENAMEVMDK, "Mandatory parameter -from missing");
1259 if (dst.isEmpty())
1260 return errorSyntax(USAGE_RENAMEVMDK, "Mandatory parameter -to missing");
1261
1262 PVBOXHDD pDisk = NULL;
1263
1264 PVDINTERFACE pVDIfs = NULL;
1265 VDINTERFACE vdInterfaceError;
1266 VDINTERFACEERROR vdInterfaceErrorCallbacks;
1267 vdInterfaceErrorCallbacks.cbSize = sizeof(VDINTERFACEERROR);
1268 vdInterfaceErrorCallbacks.enmInterface = VDINTERFACETYPE_ERROR;
1269 vdInterfaceErrorCallbacks.pfnError = handleVDError;
1270
1271 int vrc = VDInterfaceAdd(&vdInterfaceError, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1272 &vdInterfaceErrorCallbacks, NULL, &pVDIfs);
1273 AssertRC(vrc);
1274
1275 vrc = VDCreate(&vdInterfaceError, &pDisk);
1276 if (RT_FAILURE(vrc))
1277 {
1278 RTPrintf("Error while creating the virtual disk container: %Rrc\n", vrc);
1279 return vrc;
1280 }
1281 else
1282 {
1283 vrc = VDOpen(pDisk, "VMDK", Utf8Str(src).raw(), VD_OPEN_FLAGS_NORMAL, NULL);
1284 if (RT_FAILURE(vrc))
1285 {
1286 RTPrintf("Error while opening the source image: %Rrc\n", vrc);
1287 }
1288 else
1289 {
1290 vrc = VDCopy(pDisk, 0, pDisk, "VMDK", Utf8Str(dst).raw(), true, 0, NULL, NULL, NULL);
1291 if (RT_FAILURE(vrc))
1292 {
1293 RTPrintf("Error while renaming the image: %Rrc\n", vrc);
1294 }
1295 }
1296 }
1297 VDCloseAll(pDisk);
1298 return vrc;
1299}
1300
1301static int CmdConvertToRaw(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1302{
1303 Bstr srcformat;
1304 Bstr src;
1305 Bstr dst;
1306 bool fWriteToStdOut = false;
1307
1308 /* Parse the arguments. */
1309 for (int i = 0; i < argc; i++)
1310 {
1311 if (strcmp(argv[i], "-format") == 0)
1312 {
1313 if (argc <= i + 1)
1314 {
1315 return errorArgument("Missing argument to '%s'", argv[i]);
1316 }
1317 i++;
1318 srcformat = argv[i];
1319 }
1320 else if (src.isEmpty())
1321 {
1322 src = argv[i];
1323 }
1324 else if (dst.isEmpty())
1325 {
1326 dst = argv[i];
1327#ifdef ENABLE_CONVERT_RAW_TO_STDOUT
1328 if (!strcmp(argv[i], "stdout"))
1329 fWriteToStdOut = true;
1330#endif /* ENABLE_CONVERT_RAW_TO_STDOUT */
1331 }
1332 else
1333 {
1334 return errorSyntax(USAGE_CONVERTTORAW, "Invalid parameter '%s'", Utf8Str(argv[i]).raw());
1335 }
1336 }
1337
1338 if (src.isEmpty())
1339 return errorSyntax(USAGE_CONVERTTORAW, "Mandatory filename parameter missing");
1340 if (dst.isEmpty())
1341 return errorSyntax(USAGE_CONVERTTORAW, "Mandatory outputfile parameter missing");
1342
1343 PVBOXHDD pDisk = NULL;
1344
1345 PVDINTERFACE pVDIfs = NULL;
1346 VDINTERFACE vdInterfaceError;
1347 VDINTERFACEERROR vdInterfaceErrorCallbacks;
1348 vdInterfaceErrorCallbacks.cbSize = sizeof(VDINTERFACEERROR);
1349 vdInterfaceErrorCallbacks.enmInterface = VDINTERFACETYPE_ERROR;
1350 vdInterfaceErrorCallbacks.pfnError = handleVDError;
1351
1352 int vrc = VDInterfaceAdd(&vdInterfaceError, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1353 &vdInterfaceErrorCallbacks, NULL, &pVDIfs);
1354 AssertRC(vrc);
1355
1356 vrc = VDCreate(&vdInterfaceError, &pDisk);
1357 if (RT_FAILURE(vrc))
1358 {
1359 RTPrintf("Error while creating the virtual disk container: %Rrc\n", vrc);
1360 return 1;
1361 }
1362
1363 /* Open raw output file. */
1364 RTFILE outFile;
1365 vrc = VINF_SUCCESS;
1366 if (fWriteToStdOut)
1367 outFile = 1;
1368 else
1369 vrc = RTFileOpen(&outFile, Utf8Str(dst).raw(), RTFILE_O_OPEN | RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_ALL);
1370 if (RT_FAILURE(vrc))
1371 {
1372 VDCloseAll(pDisk);
1373 RTPrintf("Error while creating destination file \"%s\": %Rrc\n", Utf8Str(dst).raw(), vrc);
1374 return 1;
1375 }
1376
1377 if (srcformat.isEmpty())
1378 {
1379 char *pszFormat = NULL;
1380 vrc = VDGetFormat(Utf8Str(src).raw(), &pszFormat);
1381 if (RT_FAILURE(vrc))
1382 {
1383 VDCloseAll(pDisk);
1384 if (!fWriteToStdOut)
1385 {
1386 RTFileClose(outFile);
1387 RTFileDelete(Utf8Str(dst).raw());
1388 }
1389 RTPrintf("No file format specified and autodetect failed - please specify format: %Rrc\n", vrc);
1390 return 1;
1391 }
1392 srcformat = pszFormat;
1393 RTStrFree(pszFormat);
1394 }
1395 vrc = VDOpen(pDisk, Utf8Str(srcformat).raw(), Utf8Str(src).raw(), VD_OPEN_FLAGS_READONLY, NULL);
1396 if (RT_FAILURE(vrc))
1397 {
1398 VDCloseAll(pDisk);
1399 if (!fWriteToStdOut)
1400 {
1401 RTFileClose(outFile);
1402 RTFileDelete(Utf8Str(dst).raw());
1403 }
1404 RTPrintf("Error while opening the source image: %Rrc\n", vrc);
1405 return 1;
1406 }
1407
1408 uint64_t cbSize = VDGetSize(pDisk, VD_LAST_IMAGE);
1409 uint64_t offFile = 0;
1410#define RAW_BUFFER_SIZE _128K
1411 uint64_t cbBuf = RAW_BUFFER_SIZE;
1412 void *pvBuf = RTMemAlloc(cbBuf);
1413 if (pvBuf)
1414 {
1415 RTPrintf("Converting image \"%s\" with size %RU64 bytes (%RU64MB) to raw...\n", Utf8Str(src).raw(), cbSize, (cbSize + _1M - 1) / _1M);
1416 while (offFile < cbSize)
1417 {
1418 size_t cb = cbSize - offFile >= (uint64_t)cbBuf ? cbBuf : (size_t)(cbSize - offFile);
1419 vrc = VDRead(pDisk, offFile, pvBuf, cb);
1420 if (RT_FAILURE(vrc))
1421 break;
1422 vrc = RTFileWrite(outFile, pvBuf, cb, NULL);
1423 if (RT_FAILURE(vrc))
1424 break;
1425 offFile += cb;
1426 }
1427 if (RT_FAILURE(vrc))
1428 {
1429 VDCloseAll(pDisk);
1430 if (!fWriteToStdOut)
1431 {
1432 RTFileClose(outFile);
1433 RTFileDelete(Utf8Str(dst).raw());
1434 }
1435 RTPrintf("Error copying image data: %Rrc\n", vrc);
1436 return 1;
1437 }
1438 }
1439 else
1440 {
1441 vrc = VERR_NO_MEMORY;
1442 VDCloseAll(pDisk);
1443 if (!fWriteToStdOut)
1444 {
1445 RTFileClose(outFile);
1446 RTFileDelete(Utf8Str(dst).raw());
1447 }
1448 RTPrintf("Error allocating read buffer: %Rrc\n", vrc);
1449 return 1;
1450 }
1451
1452 if (!fWriteToStdOut)
1453 RTFileClose(outFile);
1454 VDCloseAll(pDisk);
1455 return 0;
1456}
1457
1458static int CmdConvertDisk(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1459{
1460 Bstr srcformat;
1461 Bstr dstformat;
1462 Bstr src;
1463 Bstr dst;
1464 int vrc;
1465 PVBOXHDD pSrcDisk = NULL;
1466 PVBOXHDD pDstDisk = NULL;
1467
1468 /* Parse the arguments. */
1469 for (int i = 0; i < argc; i++)
1470 {
1471 if (strcmp(argv[i], "-srcformat") == 0)
1472 {
1473 if (argc <= i + 1)
1474 {
1475 return errorArgument("Missing argument to '%s'", argv[i]);
1476 }
1477 i++;
1478 srcformat = argv[i];
1479 }
1480 else if (strcmp(argv[i], "-dstformat") == 0)
1481 {
1482 if (argc <= i + 1)
1483 {
1484 return errorArgument("Missing argument to '%s'", argv[i]);
1485 }
1486 i++;
1487 dstformat = argv[i];
1488 }
1489 else if (src.isEmpty())
1490 {
1491 src = argv[i];
1492 }
1493 else if (dst.isEmpty())
1494 {
1495 dst = argv[i];
1496 }
1497 else
1498 {
1499 return errorSyntax(USAGE_CONVERTDISK, "Invalid parameter '%s'", Utf8Str(argv[i]).raw());
1500 }
1501 }
1502
1503 if (src.isEmpty())
1504 return errorSyntax(USAGE_CONVERTDISK, "Mandatory input image parameter missing");
1505 if (dst.isEmpty())
1506 return errorSyntax(USAGE_CONVERTDISK, "Mandatory output image parameter missing");
1507
1508
1509 PVDINTERFACE pVDIfs = NULL;
1510 VDINTERFACE vdInterfaceError;
1511 VDINTERFACEERROR vdInterfaceErrorCallbacks;
1512 vdInterfaceErrorCallbacks.cbSize = sizeof(VDINTERFACEERROR);
1513 vdInterfaceErrorCallbacks.enmInterface = VDINTERFACETYPE_ERROR;
1514 vdInterfaceErrorCallbacks.pfnError = handleVDError;
1515
1516 vrc = VDInterfaceAdd(&vdInterfaceError, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1517 &vdInterfaceErrorCallbacks, NULL, &pVDIfs);
1518 AssertRC(vrc);
1519
1520 do
1521 {
1522 /* Try to determine input image format */
1523 if (srcformat.isEmpty())
1524 {
1525 char *pszFormat = NULL;
1526 vrc = VDGetFormat(Utf8Str(src).raw(), &pszFormat);
1527 if (RT_FAILURE(vrc))
1528 {
1529 RTPrintf("No file format specified and autodetect failed - please specify format: %Rrc\n", vrc);
1530 break;
1531 }
1532 srcformat = pszFormat;
1533 RTStrFree(pszFormat);
1534 }
1535
1536 vrc = VDCreate(&vdInterfaceError, &pSrcDisk);
1537 if (RT_FAILURE(vrc))
1538 {
1539 RTPrintf("Error while creating the source virtual disk container: %Rrc\n", vrc);
1540 break;
1541 }
1542
1543 /* Open the input image */
1544 vrc = VDOpen(pSrcDisk, Utf8Str(srcformat).raw(), Utf8Str(src).raw(), VD_OPEN_FLAGS_READONLY, NULL);
1545 if (RT_FAILURE(vrc))
1546 {
1547 RTPrintf("Error while opening the source image: %Rrc\n", vrc);
1548 break;
1549 }
1550
1551 /* Output format defaults to VDI */
1552 if (dstformat.isEmpty())
1553 dstformat = "VDI";
1554
1555 vrc = VDCreate(&vdInterfaceError, &pDstDisk);
1556 if (RT_FAILURE(vrc))
1557 {
1558 RTPrintf("Error while creating the destination virtual disk container: %Rrc\n", vrc);
1559 break;
1560 }
1561
1562 uint64_t cbSize = VDGetSize(pSrcDisk, VD_LAST_IMAGE);
1563 RTPrintf("Converting image \"%s\" with size %RU64 bytes (%RU64MB)...\n", Utf8Str(src).raw(), cbSize, (cbSize + _1M - 1) / _1M);
1564
1565 /* Create the output image */
1566 vrc = VDCopy(pSrcDisk, VD_LAST_IMAGE, pDstDisk, Utf8Str(dstformat).raw(),
1567 Utf8Str(dst).raw(), false, 0, NULL, NULL, NULL);
1568 if (RT_FAILURE(vrc))
1569 {
1570 RTPrintf("Error while copying the image: %Rrc\n", vrc);
1571 break;
1572 }
1573 }
1574 while (0);
1575
1576 if (pDstDisk)
1577 VDCloseAll(pDstDisk);
1578 if (pSrcDisk)
1579 VDCloseAll(pSrcDisk);
1580
1581 return RT_SUCCESS(vrc) ? 0 : 1;
1582}
1583
1584/**
1585 * Unloads the neccessary driver.
1586 *
1587 * @returns VBox status code
1588 */
1589int CmdModUninstall(void)
1590{
1591 int rc;
1592
1593 rc = SUPUninstall();
1594 if (RT_SUCCESS(rc))
1595 return 0;
1596 if (rc == VERR_NOT_IMPLEMENTED)
1597 return 0;
1598 return E_FAIL;
1599}
1600
1601/**
1602 * Loads the neccessary driver.
1603 *
1604 * @returns VBox status code
1605 */
1606int CmdModInstall(void)
1607{
1608 int rc;
1609
1610 rc = SUPInstall();
1611 if (RT_SUCCESS(rc))
1612 return 0;
1613 if (rc == VERR_NOT_IMPLEMENTED)
1614 return 0;
1615 return E_FAIL;
1616}
1617
1618/**
1619 * Wrapper for handling internal commands
1620 */
1621int handleInternalCommands(int argc, char *argv[],
1622 ComPtr <IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1623{
1624 g_fInternalMode = true;
1625
1626 /* at least a command is required */
1627 if (argc < 1)
1628 return errorSyntax(USAGE_ALL, "Command missing");
1629
1630 /*
1631 * The 'string switch' on command name.
1632 */
1633 const char *pszCmd = argv[0];
1634 if (!strcmp(pszCmd, "loadsyms"))
1635 return CmdLoadSyms(argc - 1, &argv[1], aVirtualBox, aSession);
1636 //if (!strcmp(pszCmd, "unloadsyms"))
1637 // return CmdUnloadSyms(argc - 1 , &argv[1]);
1638 if (!strcmp(pszCmd, "setvdiuuid"))
1639 return handleSetVDIUUID(argc - 1, &argv[1], aVirtualBox, aSession);
1640 if (!strcmp(pszCmd, "listpartitions"))
1641 return CmdListPartitions(argc - 1, &argv[1], aVirtualBox, aSession);
1642 if (!strcmp(pszCmd, "createrawvmdk"))
1643 return CmdCreateRawVMDK(argc - 1, &argv[1], aVirtualBox, aSession);
1644 if (!strcmp(pszCmd, "renamevmdk"))
1645 return CmdRenameVMDK(argc - 1, &argv[1], aVirtualBox, aSession);
1646 if (!strcmp(pszCmd, "converttoraw"))
1647 return CmdConvertToRaw(argc - 1, &argv[1], aVirtualBox, aSession);
1648 if (!strcmp(pszCmd, "convertdisk"))
1649 return CmdConvertDisk(argc - 1, &argv[1], aVirtualBox, aSession);
1650
1651 if (!strcmp(pszCmd, "modinstall"))
1652 return CmdModInstall();
1653 if (!strcmp(pszCmd, "moduninstall"))
1654 return CmdModUninstall();
1655
1656 /* default: */
1657 return errorSyntax(USAGE_ALL, "Invalid command '%s'", Utf8Str(argv[0]).raw());
1658}
1659
Note: See TracBrowser for help on using the repository browser.

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