VirtualBox

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

Last change on this file since 18180 was 18177, checked in by vboxsync, 16 years ago

Main: turn read/write param in OpenHardDisk into an enum

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

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