VirtualBox

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

Last change on this file since 12288 was 11444, checked in by vboxsync, 16 years ago

Storage/VBoxHDD-new: introduced VD interfaces per image and per operation, completely unifying callback handling.

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