VirtualBox

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

Last change on this file since 16840 was 16530, checked in by vboxsync, 16 years ago

Main: rework error macros everywhere; make error messages much more readable (esp. with VBoxManage); use shared function to actually print message; reduces size of VBoxManage debug build from 3.4 to 2.3 MB

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