VirtualBox

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

Last change on this file since 21649 was 21556, checked in by vboxsync, 16 years ago

VBoxManage/createrawvmdk: force use of devices giving access to the correct partition, and implement this for OSX. thi fixes public bug#1461

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 58.4 KB
Line 
1/* $Id: VBoxInternalManage.cpp 21556 2009-07-13 17:14:42Z 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-2009 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/errorprint.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(Bstr(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 = (unsigned)(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 p += 16;
650 if (p[4] == 0)
651 uExtended = (unsigned)-1;
652 else if (PARTTYPE_IS_EXTENDED(p[4]))
653 {
654 uExtended = uIndex++;
655 uOffset = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
656 }
657 else
658 {
659 RTPrintf("Logical partition chain broken. Aborting\n");
660 return VERR_INVALID_PARAMETER;
661 }
662 } while (uExtended != (unsigned)-1);
663 }
664
665 /* Sort partitions in ascending order of start sector, plus a trivial
666 * bit of consistency checking. */
667 for (unsigned i = 0; i < pPart->cPartitions-1; i++)
668 {
669 unsigned uMinIdx = i;
670 uint64_t uMinVal = pPart->aPartitions[i].uStart;
671 for (unsigned j = i + 1; j < pPart->cPartitions; j++)
672 {
673 if (pPart->aPartitions[j].uStart < uMinVal)
674 {
675 uMinIdx = j;
676 uMinVal = pPart->aPartitions[j].uStart;
677 }
678 else if (pPart->aPartitions[j].uStart == uMinVal)
679 {
680 RTPrintf("Two partitions start at the same place. Aborting\n");
681 return VERR_INVALID_PARAMETER;
682 }
683 else if (pPart->aPartitions[j].uStart == 0)
684 {
685 RTPrintf("Partition starts at sector 0. Aborting\n");
686 return VERR_INVALID_PARAMETER;
687 }
688 }
689 if (uMinIdx != i)
690 {
691 /* Swap entries at index i and uMinIdx. */
692 memcpy(&pPart->aPartitions[pPart->cPartitions],
693 &pPart->aPartitions[i], sizeof(HOSTPARTITION));
694 memcpy(&pPart->aPartitions[i],
695 &pPart->aPartitions[uMinIdx], sizeof(HOSTPARTITION));
696 memcpy(&pPart->aPartitions[uMinIdx],
697 &pPart->aPartitions[pPart->cPartitions], sizeof(HOSTPARTITION));
698 }
699 }
700
701 /* Now do a lot of consistency checking. */
702 uint64_t uPrevEnd = 0;
703 for (unsigned i = 0; i < pPart->cPartitions-1; i++)
704 {
705 if (pPart->aPartitions[i].cPartDataSectors)
706 {
707 if (pPart->aPartitions[i].uPartDataStart < uPrevEnd)
708 {
709 RTPrintf("Overlapping partition description areas. Aborting\n");
710 return VERR_INVALID_PARAMETER;
711 }
712 uPrevEnd = pPart->aPartitions[i].uPartDataStart + pPart->aPartitions[i].cPartDataSectors;
713 }
714 if (pPart->aPartitions[i].uStart < uPrevEnd)
715 {
716 RTPrintf("Overlapping partitions. Aborting\n");
717 return VERR_INVALID_PARAMETER;
718 }
719 if (!PARTTYPE_IS_EXTENDED(pPart->aPartitions[i].uType))
720 uPrevEnd = pPart->aPartitions[i].uStart + pPart->aPartitions[i].uSize;
721 }
722
723 /* Fill out partitioning location info for MBR. */
724 pPart->aPartitions[0].uPartDataStart = 0;
725 pPart->aPartitions[0].cPartDataSectors = pPart->aPartitions[0].uStart;
726
727 return VINF_SUCCESS;
728}
729
730static int CmdListPartitions(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
731{
732 Utf8Str rawdisk;
733
734 /* let's have a closer look at the arguments */
735 for (int i = 0; i < argc; i++)
736 {
737 if (strcmp(argv[i], "-rawdisk") == 0)
738 {
739 if (argc <= i + 1)
740 {
741 return errorArgument("Missing argument to '%s'", argv[i]);
742 }
743 i++;
744 rawdisk = argv[i];
745 }
746 else
747 {
748 return errorSyntax(USAGE_LISTPARTITIONS, "Invalid parameter '%s'", Utf8Str(argv[i]).raw());
749 }
750 }
751
752 if (rawdisk.isEmpty())
753 return errorSyntax(USAGE_LISTPARTITIONS, "Mandatory parameter -rawdisk missing");
754
755 RTFILE RawFile;
756 int vrc = RTFileOpen(&RawFile, rawdisk.raw(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE);
757 if (RT_FAILURE(vrc))
758 {
759 RTPrintf("Error opening the raw disk: %Rrc\n", vrc);
760 return vrc;
761 }
762
763 HOSTPARTITIONS partitions;
764 vrc = partRead(RawFile, &partitions);
765 if (RT_FAILURE(vrc))
766 return vrc;
767
768 RTPrintf("Number Type StartCHS EndCHS Size (MiB) Start (Sect)\n");
769 for (unsigned i = 0; i < partitions.cPartitions; i++)
770 {
771 /* Suppress printing the extended partition. Otherwise people
772 * might add it to the list of partitions for raw partition
773 * access (which is not good). */
774 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
775 continue;
776
777 RTPrintf("%-7u %#04x %-4u/%-3u/%-2u %-4u/%-3u/%-2u %10llu %10llu\n",
778 partitions.aPartitions[i].uIndex,
779 partitions.aPartitions[i].uType,
780 partitions.aPartitions[i].uStartCylinder,
781 partitions.aPartitions[i].uStartHead,
782 partitions.aPartitions[i].uStartSector,
783 partitions.aPartitions[i].uEndCylinder,
784 partitions.aPartitions[i].uEndHead,
785 partitions.aPartitions[i].uEndSector,
786 partitions.aPartitions[i].uSize / 2048,
787 partitions.aPartitions[i].uStart);
788 }
789
790 return 0;
791}
792
793static int CmdCreateRawVMDK(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
794{
795 HRESULT rc = S_OK;
796 Bstr filename;
797 const char *pszMBRFilename = NULL;
798 Utf8Str rawdisk;
799 const char *pszPartitions = NULL;
800 bool fRegister = false;
801 bool fRelative = false;
802
803 uint64_t cbSize = 0;
804 PVBOXHDD pDisk = NULL;
805 VBOXHDDRAW RawDescriptor;
806 HOSTPARTITIONS partitions;
807 uint32_t uPartitions = 0;
808 PVDINTERFACE pVDIfs = NULL;
809
810 /* let's have a closer look at the arguments */
811 for (int i = 0; i < argc; i++)
812 {
813 if (strcmp(argv[i], "-filename") == 0)
814 {
815 if (argc <= i + 1)
816 {
817 return errorArgument("Missing argument to '%s'", argv[i]);
818 }
819 i++;
820 filename = argv[i];
821 }
822 else if (strcmp(argv[i], "-mbr") == 0)
823 {
824 if (argc <= i + 1)
825 {
826 return errorArgument("Missing argument to '%s'", argv[i]);
827 }
828 i++;
829 pszMBRFilename = argv[i];
830 }
831 else if (strcmp(argv[i], "-rawdisk") == 0)
832 {
833 if (argc <= i + 1)
834 {
835 return errorArgument("Missing argument to '%s'", argv[i]);
836 }
837 i++;
838 rawdisk = argv[i];
839 }
840 else if (strcmp(argv[i], "-partitions") == 0)
841 {
842 if (argc <= i + 1)
843 {
844 return errorArgument("Missing argument to '%s'", argv[i]);
845 }
846 i++;
847 pszPartitions = argv[i];
848 }
849 else if (strcmp(argv[i], "-register") == 0)
850 {
851 fRegister = true;
852 }
853#ifdef RT_OS_LINUX
854 else if (strcmp(argv[i], "-relative") == 0)
855 {
856 fRelative = true;
857 }
858#endif /* RT_OS_LINUX */
859 else
860 {
861 return errorSyntax(USAGE_CREATERAWVMDK, "Invalid parameter '%s'", Utf8Str(argv[i]).raw());
862 }
863 }
864
865 if (filename.isEmpty())
866 return errorSyntax(USAGE_CREATERAWVMDK, "Mandatory parameter -filename missing");
867 if (rawdisk.isEmpty())
868 return errorSyntax(USAGE_CREATERAWVMDK, "Mandatory parameter -rawdisk missing");
869 if (!pszPartitions && pszMBRFilename)
870 return errorSyntax(USAGE_CREATERAWVMDK, "The parameter -mbr is only valid when the parameter -partitions is also present");
871
872#ifdef RT_OS_DARWIN
873 fRelative = true;
874#endif /* RT_OS_DARWIN */
875 RTFILE RawFile;
876 int vrc = RTFileOpen(&RawFile, rawdisk.raw(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE);
877 if (RT_FAILURE(vrc))
878 {
879 RTPrintf("Error opening the raw disk '%s': %Rrc\n", rawdisk.raw(), vrc);
880 goto out;
881 }
882
883#ifdef RT_OS_WINDOWS
884 /* Windows NT has no IOCTL_DISK_GET_LENGTH_INFORMATION ioctl. This was
885 * added to Windows XP, so we have to use the available info from DriveGeo.
886 * Note that we cannot simply use IOCTL_DISK_GET_DRIVE_GEOMETRY as it
887 * yields a slightly different result than IOCTL_DISK_GET_LENGTH_INFO.
888 * We call IOCTL_DISK_GET_DRIVE_GEOMETRY first as we need to check the media
889 * type anyway, and if IOCTL_DISK_GET_LENGTH_INFORMATION is supported
890 * we will later override cbSize.
891 */
892 DISK_GEOMETRY DriveGeo;
893 DWORD cbDriveGeo;
894 if (DeviceIoControl((HANDLE)RawFile,
895 IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,
896 &DriveGeo, sizeof(DriveGeo), &cbDriveGeo, NULL))
897 {
898 if ( DriveGeo.MediaType == FixedMedia
899 || DriveGeo.MediaType == RemovableMedia)
900 {
901 cbSize = DriveGeo.Cylinders.QuadPart
902 * DriveGeo.TracksPerCylinder
903 * DriveGeo.SectorsPerTrack
904 * DriveGeo.BytesPerSector;
905 }
906 else
907 {
908 RTPrintf("File '%s' is no fixed/removable medium device\n", rawdisk.raw());
909 vrc = VERR_INVALID_PARAMETER;
910 goto out;
911 }
912
913 GET_LENGTH_INFORMATION DiskLenInfo;
914 DWORD junk;
915 if (DeviceIoControl((HANDLE)RawFile,
916 IOCTL_DISK_GET_LENGTH_INFO, NULL, 0,
917 &DiskLenInfo, sizeof(DiskLenInfo), &junk, (LPOVERLAPPED)NULL))
918 {
919 /* IOCTL_DISK_GET_LENGTH_INFO is supported -- override cbSize. */
920 cbSize = DiskLenInfo.Length.QuadPart;
921 }
922 }
923 else
924 {
925 vrc = RTErrConvertFromWin32(GetLastError());
926 RTPrintf("Error getting the geometry of the raw disk '%s': %Rrc\n", rawdisk.raw(), vrc);
927 goto out;
928 }
929#elif defined(RT_OS_LINUX)
930 struct stat DevStat;
931 if (!fstat(RawFile, &DevStat) && S_ISBLK(DevStat.st_mode))
932 {
933#ifdef BLKGETSIZE64
934 /* BLKGETSIZE64 is broken up to 2.4.17 and in many 2.5.x. In 2.6.0
935 * it works without problems. */
936 struct utsname utsname;
937 if ( uname(&utsname) == 0
938 && ( (strncmp(utsname.release, "2.5.", 4) == 0 && atoi(&utsname.release[4]) >= 18)
939 || (strncmp(utsname.release, "2.", 2) == 0 && atoi(&utsname.release[2]) >= 6)))
940 {
941 uint64_t cbBlk;
942 if (!ioctl(RawFile, BLKGETSIZE64, &cbBlk))
943 cbSize = cbBlk;
944 }
945#endif /* BLKGETSIZE64 */
946 if (!cbSize)
947 {
948 long cBlocks;
949 if (!ioctl(RawFile, BLKGETSIZE, &cBlocks))
950 cbSize = (uint64_t)cBlocks << 9;
951 else
952 {
953 vrc = RTErrConvertFromErrno(errno);
954 RTPrintf("Error getting the size of the raw disk '%s': %Rrc\n", rawdisk.raw(), vrc);
955 goto out;
956 }
957 }
958 }
959 else
960 {
961 RTPrintf("File '%s' is no block device\n", rawdisk.raw());
962 vrc = VERR_INVALID_PARAMETER;
963 goto out;
964 }
965#elif defined(RT_OS_DARWIN)
966 struct stat DevStat;
967 if (!fstat(RawFile, &DevStat) && S_ISBLK(DevStat.st_mode))
968 {
969 uint64_t cBlocks;
970 uint32_t cbBlock;
971 if (!ioctl(RawFile, DKIOCGETBLOCKCOUNT, &cBlocks))
972 {
973 if (!ioctl(RawFile, DKIOCGETBLOCKSIZE, &cbBlock))
974 cbSize = cBlocks * cbBlock;
975 else
976 {
977 RTPrintf("Cannot get the block size for file '%s': %Rrc", rawdisk.raw(), vrc);
978 vrc = RTErrConvertFromErrno(errno);
979 goto out;
980 }
981 }
982 else
983 {
984 vrc = RTErrConvertFromErrno(errno);
985 RTPrintf("Cannot get the block count for file '%s': %Rrc", rawdisk.raw(), vrc);
986 goto out;
987 }
988 }
989 else
990 {
991 RTPrintf("File '%s' is no block device\n", rawdisk.raw());
992 vrc = VERR_INVALID_PARAMETER;
993 goto out;
994 }
995#elif defined(RT_OS_SOLARIS)
996 struct stat DevStat;
997 if (!fstat(RawFile, &DevStat) && ( S_ISBLK(DevStat.st_mode)
998 || S_ISCHR(DevStat.st_mode)))
999 {
1000 struct dk_minfo mediainfo;
1001 if (!ioctl(RawFile, DKIOCGMEDIAINFO, &mediainfo))
1002 cbSize = mediainfo.dki_capacity * mediainfo.dki_lbsize;
1003 else
1004 {
1005 vrc = RTErrConvertFromErrno(errno);
1006 RTPrintf("Error getting the size of the raw disk '%s': %Rrc\n", rawdisk.raw(), vrc);
1007 goto out;
1008 }
1009 }
1010 else
1011 {
1012 RTPrintf("File '%s' is no block or char device\n", rawdisk.raw());
1013 vrc = VERR_INVALID_PARAMETER;
1014 goto out;
1015 }
1016#else /* all unrecognized OSes */
1017 /* Hopefully this works on all other hosts. If it doesn't, it'll just fail
1018 * creating the VMDK, so no real harm done. */
1019 vrc = RTFileGetSize(RawFile, &cbSize);
1020 if (RT_FAILURE(vrc))
1021 {
1022 RTPrintf("Error getting the size of the raw disk '%s': %Rrc\n", rawdisk.raw(), vrc);
1023 goto out;
1024 }
1025#endif
1026
1027 /* Check whether cbSize is actually sensible. */
1028 if (!cbSize || cbSize % 512)
1029 {
1030 RTPrintf("Detected size of raw disk '%s' is %s, an invalid value\n", rawdisk.raw(), cbSize);
1031 vrc = VERR_INVALID_PARAMETER;
1032 goto out;
1033 }
1034
1035 RawDescriptor.szSignature[0] = 'R';
1036 RawDescriptor.szSignature[1] = 'A';
1037 RawDescriptor.szSignature[2] = 'W';
1038 RawDescriptor.szSignature[3] = '\0';
1039 if (!pszPartitions)
1040 {
1041 RawDescriptor.fRawDisk = true;
1042 RawDescriptor.pszRawDisk = rawdisk.raw();
1043 }
1044 else
1045 {
1046 RawDescriptor.fRawDisk = false;
1047 RawDescriptor.pszRawDisk = NULL;
1048 RawDescriptor.cPartitions = 0;
1049
1050 const char *p = pszPartitions;
1051 char *pszNext;
1052 uint32_t u32;
1053 while (*p != '\0')
1054 {
1055 vrc = RTStrToUInt32Ex(p, &pszNext, 0, &u32);
1056 if (RT_FAILURE(vrc))
1057 {
1058 RTPrintf("Incorrect value in partitions parameter\n");
1059 goto out;
1060 }
1061 uPartitions |= RT_BIT(u32);
1062 p = pszNext;
1063 if (*p == ',')
1064 p++;
1065 else if (*p != '\0')
1066 {
1067 RTPrintf("Incorrect separator in partitions parameter\n");
1068 vrc = VERR_INVALID_PARAMETER;
1069 goto out;
1070 }
1071 }
1072
1073 vrc = partRead(RawFile, &partitions);
1074 if (RT_FAILURE(vrc))
1075 {
1076 RTPrintf("Error reading the partition information from '%s'\n", rawdisk.raw());
1077 goto out;
1078 }
1079
1080 for (unsigned i = 0; i < partitions.cPartitions; i++)
1081 {
1082 if ( uPartitions & RT_BIT(partitions.aPartitions[i].uIndex)
1083 && PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1084 {
1085 /* Some ignorant user specified an extended partition.
1086 * Bad idea, as this would trigger an overlapping
1087 * partitions error later during VMDK creation. So warn
1088 * here and ignore what the user requested. */
1089 RTPrintf("Warning: it is not possible (and necessary) to explicitly give access to the\n"
1090 " extended partition %u. If required, enable access to all logical\n"
1091 " partitions inside this extended partition.\n", partitions.aPartitions[i].uIndex);
1092 uPartitions &= ~RT_BIT(partitions.aPartitions[i].uIndex);
1093 }
1094 }
1095
1096 RawDescriptor.cPartitions = partitions.cPartitions;
1097 RawDescriptor.pPartitions = (PVBOXHDDRAWPART)RTMemAllocZ(partitions.cPartitions * sizeof(VBOXHDDRAWPART));
1098 if (!RawDescriptor.pPartitions)
1099 {
1100 RTPrintf("Out of memory allocating the partition list for '%s'\n", rawdisk.raw());
1101 vrc = VERR_NO_MEMORY;
1102 goto out;
1103 }
1104 for (unsigned i = 0; i < partitions.cPartitions; i++)
1105 {
1106 if (uPartitions & RT_BIT(partitions.aPartitions[i].uIndex))
1107 {
1108 if (fRelative)
1109 {
1110#ifdef RT_OS_LINUX
1111 /* Refer to the correct partition and use offset 0. */
1112 char *pszRawName;
1113 vrc = RTStrAPrintf(&pszRawName, "%s%u", rawdisk.raw(),
1114 partitions.aPartitions[i].uIndex);
1115 if (RT_FAILURE(vrc))
1116 {
1117 RTPrintf("Error creating reference to individual partition %u, rc=%Rrc\n",
1118 partitions.aPartitions[i].uIndex, vrc);
1119 goto out;
1120 }
1121 RawDescriptor.pPartitions[i].pszRawDevice = pszRawName;
1122 RawDescriptor.pPartitions[i].uPartitionStartOffset = 0;
1123 RawDescriptor.pPartitions[i].uPartitionStart = partitions.aPartitions[i].uStart * 512;
1124#elif defined(RT_OS_DARWIN)
1125 /* Refer to the correct partition and use offset 0. */
1126 char *pszRawName;
1127 vrc = RTStrAPrintf(&pszRawName, "%ss%u", rawdisk.raw(),
1128 partitions.aPartitions[i].uIndex);
1129 if (RT_FAILURE(vrc))
1130 {
1131 RTPrintf("Error creating reference to individual partition %u, rc=%Rrc\n",
1132 partitions.aPartitions[i].uIndex, vrc);
1133 goto out;
1134 }
1135 RawDescriptor.pPartitions[i].pszRawDevice = pszRawName;
1136 RawDescriptor.pPartitions[i].uPartitionStartOffset = 0;
1137 RawDescriptor.pPartitions[i].uPartitionStart = partitions.aPartitions[i].uStart * 512;
1138#else
1139 /** @todo not implemented yet for Windows host. Treat just
1140 * like not specified (this code is actually never reached). */
1141 RawDescriptor.pPartitions[i].pszRawDevice = rawdisk.raw();
1142 RawDescriptor.pPartitions[i].uPartitionStartOffset = partitions.aPartitions[i].uStart * 512;
1143 RawDescriptor.pPartitions[i].uPartitionStart = partitions.aPartitions[i].uStart * 512;
1144#endif
1145 }
1146 else
1147 {
1148 /* This is the "everything refers to the base raw device"
1149 * variant. This requires opening the base device in RW
1150 * mode even for creation. */
1151 RawDescriptor.pPartitions[i].pszRawDevice = rawdisk.raw();
1152 RawDescriptor.pPartitions[i].uPartitionStartOffset = partitions.aPartitions[i].uStart * 512;
1153 RawDescriptor.pPartitions[i].uPartitionStart = partitions.aPartitions[i].uStart * 512;
1154 }
1155 }
1156 else
1157 {
1158 /* Suppress access to this partition. */
1159 RawDescriptor.pPartitions[i].pszRawDevice = NULL;
1160 RawDescriptor.pPartitions[i].uPartitionStartOffset = 0;
1161 /* This is used in the plausibility check in the creation
1162 * code. In theory it's a dummy, but I don't want to make
1163 * the VMDK creatiion any more complicated than what it needs
1164 * to be. */
1165 RawDescriptor.pPartitions[i].uPartitionStart = partitions.aPartitions[i].uStart * 512;
1166 }
1167 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1168 {
1169 /* Suppress exporting the actual extended partition. Only
1170 * logical partitions should be processed. However completely
1171 * ignoring it leads to leaving out the MBR data. */
1172 RawDescriptor.pPartitions[i].cbPartition = 0;
1173 }
1174 else
1175 RawDescriptor.pPartitions[i].cbPartition = partitions.aPartitions[i].uSize * 512;
1176 RawDescriptor.pPartitions[i].uPartitionDataStart = partitions.aPartitions[i].uPartDataStart * 512;
1177 /** @todo the clipping below isn't 100% accurate, as it should
1178 * actually clip to the track size. However that's easier said
1179 * than done as figuring out the track size is heuristics. */
1180 RawDescriptor.pPartitions[i].cbPartitionData = RT_MIN(partitions.aPartitions[i].cPartDataSectors, 63) * 512;
1181 if (RawDescriptor.pPartitions[i].cbPartitionData)
1182 {
1183 Assert (RawDescriptor.pPartitions[i].cbPartitionData -
1184 (size_t)RawDescriptor.pPartitions[i].cbPartitionData == 0);
1185 void *pPartData = RTMemAlloc((size_t)RawDescriptor.pPartitions[i].cbPartitionData);
1186 if (!pPartData)
1187 {
1188 RTPrintf("Out of memory allocating the partition descriptor for '%s'\n", rawdisk.raw());
1189 vrc = VERR_NO_MEMORY;
1190 goto out;
1191 }
1192 vrc = RTFileReadAt(RawFile, partitions.aPartitions[i].uPartDataStart * 512, pPartData, (size_t)RawDescriptor.pPartitions[i].cbPartitionData, NULL);
1193 if (RT_FAILURE(vrc))
1194 {
1195 RTPrintf("Cannot read partition data from raw device '%s': %Rrc\n", rawdisk.raw(), vrc);
1196 goto out;
1197 }
1198 /* Splice in the replacement MBR code if specified. */
1199 if ( partitions.aPartitions[i].uPartDataStart == 0
1200 && pszMBRFilename)
1201 {
1202 RTFILE MBRFile;
1203 vrc = RTFileOpen(&MBRFile, pszMBRFilename, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE);
1204 if (RT_FAILURE(vrc))
1205 {
1206 RTPrintf("Cannot open replacement MBR file '%s' specified with -mbr: %Rrc\n", pszMBRFilename, vrc);
1207 goto out;
1208 }
1209 vrc = RTFileReadAt(MBRFile, 0, pPartData, 0x1be, NULL);
1210 RTFileClose(MBRFile);
1211 if (RT_FAILURE(vrc))
1212 {
1213 RTPrintf("Cannot read replacement MBR file '%s': %Rrc\n", pszMBRFilename, vrc);
1214 goto out;
1215 }
1216 }
1217 RawDescriptor.pPartitions[i].pvPartitionData = pPartData;
1218 }
1219 }
1220 }
1221
1222 RTFileClose(RawFile);
1223
1224 VDINTERFACE vdInterfaceError;
1225 VDINTERFACEERROR vdInterfaceErrorCallbacks;
1226 vdInterfaceErrorCallbacks.cbSize = sizeof(VDINTERFACEERROR);
1227 vdInterfaceErrorCallbacks.enmInterface = VDINTERFACETYPE_ERROR;
1228 vdInterfaceErrorCallbacks.pfnError = handleVDError;
1229
1230 vrc = VDInterfaceAdd(&vdInterfaceError, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1231 &vdInterfaceErrorCallbacks, NULL, &pVDIfs);
1232 AssertRC(vrc);
1233
1234 vrc = VDCreate(pVDIfs, &pDisk);
1235 if (RT_FAILURE(vrc))
1236 {
1237 RTPrintf("Error while creating the virtual disk container: %Rrc\n", vrc);
1238 goto out;
1239 }
1240
1241 Assert(RT_MIN(cbSize / 512 / 16 / 63, 16383) -
1242 (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383) == 0);
1243 PDMMEDIAGEOMETRY PCHS, LCHS;
1244 PCHS.cCylinders = (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383);
1245 PCHS.cHeads = 16;
1246 PCHS.cSectors = 63;
1247 LCHS.cCylinders = 0;
1248 LCHS.cHeads = 0;
1249 LCHS.cSectors = 0;
1250 vrc = VDCreateBase(pDisk, "VMDK", Utf8Str(filename).raw(), cbSize,
1251 VD_IMAGE_FLAGS_FIXED | VD_VMDK_IMAGE_FLAGS_RAWDISK,
1252 (char *)&RawDescriptor, &PCHS, &LCHS, NULL,
1253 VD_OPEN_FLAGS_NORMAL, NULL, NULL);
1254 if (RT_FAILURE(vrc))
1255 {
1256 RTPrintf("Error while creating the raw disk VMDK: %Rrc\n", vrc);
1257 goto out;
1258 }
1259 RTPrintf("RAW host disk access VMDK file %s created successfully.\n", Utf8Str(filename).raw());
1260
1261 VDCloseAll(pDisk);
1262
1263 /* Clean up allocated memory etc. */
1264 if (pszPartitions)
1265 {
1266 for (unsigned i = 0; i < partitions.cPartitions; i++)
1267 {
1268 if (uPartitions & RT_BIT(partitions.aPartitions[i].uIndex))
1269 {
1270 if (fRelative)
1271 {
1272#ifdef RT_OS_LINUX
1273 /* Free memory allocated above. */
1274 RTStrFree((char *)(void *)RawDescriptor.pPartitions[i].pszRawDevice);
1275#endif /* RT_OS_LINUX */
1276 }
1277 }
1278 }
1279 }
1280
1281 if (fRegister)
1282 {
1283 ComPtr<IHardDisk> hardDisk;
1284 CHECK_ERROR(aVirtualBox, OpenHardDisk(filename, AccessMode_ReadWrite, false, Bstr(""), false, Bstr(""), hardDisk.asOutParam()));
1285 }
1286
1287 return SUCCEEDED(rc) ? 0 : 1;
1288
1289out:
1290 RTPrintf("The raw disk vmdk file was not created\n");
1291 return RT_SUCCESS(vrc) ? 0 : 1;
1292}
1293
1294static int CmdRenameVMDK(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1295{
1296 Bstr src;
1297 Bstr dst;
1298 /* Parse the arguments. */
1299 for (int i = 0; i < argc; i++)
1300 {
1301 if (strcmp(argv[i], "-from") == 0)
1302 {
1303 if (argc <= i + 1)
1304 {
1305 return errorArgument("Missing argument to '%s'", argv[i]);
1306 }
1307 i++;
1308 src = argv[i];
1309 }
1310 else if (strcmp(argv[i], "-to") == 0)
1311 {
1312 if (argc <= i + 1)
1313 {
1314 return errorArgument("Missing argument to '%s'", argv[i]);
1315 }
1316 i++;
1317 dst = argv[i];
1318 }
1319 else
1320 {
1321 return errorSyntax(USAGE_RENAMEVMDK, "Invalid parameter '%s'", Utf8Str(argv[i]).raw());
1322 }
1323 }
1324
1325 if (src.isEmpty())
1326 return errorSyntax(USAGE_RENAMEVMDK, "Mandatory parameter -from missing");
1327 if (dst.isEmpty())
1328 return errorSyntax(USAGE_RENAMEVMDK, "Mandatory parameter -to missing");
1329
1330 PVBOXHDD pDisk = NULL;
1331
1332 PVDINTERFACE pVDIfs = NULL;
1333 VDINTERFACE vdInterfaceError;
1334 VDINTERFACEERROR vdInterfaceErrorCallbacks;
1335 vdInterfaceErrorCallbacks.cbSize = sizeof(VDINTERFACEERROR);
1336 vdInterfaceErrorCallbacks.enmInterface = VDINTERFACETYPE_ERROR;
1337 vdInterfaceErrorCallbacks.pfnError = handleVDError;
1338
1339 int vrc = VDInterfaceAdd(&vdInterfaceError, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1340 &vdInterfaceErrorCallbacks, NULL, &pVDIfs);
1341 AssertRC(vrc);
1342
1343 vrc = VDCreate(pVDIfs, &pDisk);
1344 if (RT_FAILURE(vrc))
1345 {
1346 RTPrintf("Error while creating the virtual disk container: %Rrc\n", vrc);
1347 return vrc;
1348 }
1349 else
1350 {
1351 vrc = VDOpen(pDisk, "VMDK", Utf8Str(src).raw(), VD_OPEN_FLAGS_NORMAL, NULL);
1352 if (RT_FAILURE(vrc))
1353 {
1354 RTPrintf("Error while opening the source image: %Rrc\n", vrc);
1355 }
1356 else
1357 {
1358 vrc = VDCopy(pDisk, 0, pDisk, "VMDK", Utf8Str(dst).raw(), true, 0, VD_IMAGE_FLAGS_NONE, NULL, NULL, NULL, NULL);
1359 if (RT_FAILURE(vrc))
1360 {
1361 RTPrintf("Error while renaming the image: %Rrc\n", vrc);
1362 }
1363 }
1364 }
1365 VDCloseAll(pDisk);
1366 return vrc;
1367}
1368
1369static int CmdConvertToRaw(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1370{
1371 Bstr srcformat;
1372 Bstr src;
1373 Bstr dst;
1374 bool fWriteToStdOut = false;
1375
1376 /* Parse the arguments. */
1377 for (int i = 0; i < argc; i++)
1378 {
1379 if (strcmp(argv[i], "-format") == 0)
1380 {
1381 if (argc <= i + 1)
1382 {
1383 return errorArgument("Missing argument to '%s'", argv[i]);
1384 }
1385 i++;
1386 srcformat = argv[i];
1387 }
1388 else if (src.isEmpty())
1389 {
1390 src = argv[i];
1391 }
1392 else if (dst.isEmpty())
1393 {
1394 dst = argv[i];
1395#ifdef ENABLE_CONVERT_RAW_TO_STDOUT
1396 if (!strcmp(argv[i], "stdout"))
1397 fWriteToStdOut = true;
1398#endif /* ENABLE_CONVERT_RAW_TO_STDOUT */
1399 }
1400 else
1401 {
1402 return errorSyntax(USAGE_CONVERTTORAW, "Invalid parameter '%s'", Utf8Str(argv[i]).raw());
1403 }
1404 }
1405
1406 if (src.isEmpty())
1407 return errorSyntax(USAGE_CONVERTTORAW, "Mandatory filename parameter missing");
1408 if (dst.isEmpty())
1409 return errorSyntax(USAGE_CONVERTTORAW, "Mandatory outputfile parameter missing");
1410
1411 PVBOXHDD pDisk = NULL;
1412
1413 PVDINTERFACE pVDIfs = NULL;
1414 VDINTERFACE vdInterfaceError;
1415 VDINTERFACEERROR vdInterfaceErrorCallbacks;
1416 vdInterfaceErrorCallbacks.cbSize = sizeof(VDINTERFACEERROR);
1417 vdInterfaceErrorCallbacks.enmInterface = VDINTERFACETYPE_ERROR;
1418 vdInterfaceErrorCallbacks.pfnError = handleVDError;
1419
1420 int vrc = VDInterfaceAdd(&vdInterfaceError, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1421 &vdInterfaceErrorCallbacks, NULL, &pVDIfs);
1422 AssertRC(vrc);
1423
1424 vrc = VDCreate(pVDIfs, &pDisk);
1425 if (RT_FAILURE(vrc))
1426 {
1427 RTPrintf("Error while creating the virtual disk container: %Rrc\n", vrc);
1428 return 1;
1429 }
1430
1431 /* Open raw output file. */
1432 RTFILE outFile;
1433 vrc = VINF_SUCCESS;
1434 if (fWriteToStdOut)
1435 outFile = 1;
1436 else
1437 vrc = RTFileOpen(&outFile, Utf8Str(dst).raw(), RTFILE_O_OPEN | RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_ALL);
1438 if (RT_FAILURE(vrc))
1439 {
1440 VDCloseAll(pDisk);
1441 RTPrintf("Error while creating destination file \"%s\": %Rrc\n", Utf8Str(dst).raw(), vrc);
1442 return 1;
1443 }
1444
1445 if (srcformat.isEmpty())
1446 {
1447 char *pszFormat = NULL;
1448 vrc = VDGetFormat(Utf8Str(src).raw(), &pszFormat);
1449 if (RT_FAILURE(vrc))
1450 {
1451 VDCloseAll(pDisk);
1452 if (!fWriteToStdOut)
1453 {
1454 RTFileClose(outFile);
1455 RTFileDelete(Utf8Str(dst).raw());
1456 }
1457 RTPrintf("No file format specified and autodetect failed - please specify format: %Rrc\n", vrc);
1458 return 1;
1459 }
1460 srcformat = pszFormat;
1461 RTStrFree(pszFormat);
1462 }
1463 vrc = VDOpen(pDisk, Utf8Str(srcformat).raw(), Utf8Str(src).raw(), VD_OPEN_FLAGS_READONLY, NULL);
1464 if (RT_FAILURE(vrc))
1465 {
1466 VDCloseAll(pDisk);
1467 if (!fWriteToStdOut)
1468 {
1469 RTFileClose(outFile);
1470 RTFileDelete(Utf8Str(dst).raw());
1471 }
1472 RTPrintf("Error while opening the source image: %Rrc\n", vrc);
1473 return 1;
1474 }
1475
1476 uint64_t cbSize = VDGetSize(pDisk, VD_LAST_IMAGE);
1477 uint64_t offFile = 0;
1478#define RAW_BUFFER_SIZE _128K
1479 uint64_t cbBuf = RAW_BUFFER_SIZE;
1480 void *pvBuf = RTMemAlloc(cbBuf);
1481 if (pvBuf)
1482 {
1483 RTPrintf("Converting image \"%s\" with size %RU64 bytes (%RU64MB) to raw...\n", Utf8Str(src).raw(), cbSize, (cbSize + _1M - 1) / _1M);
1484 while (offFile < cbSize)
1485 {
1486 size_t cb = cbSize - offFile >= (uint64_t)cbBuf ? cbBuf : (size_t)(cbSize - offFile);
1487 vrc = VDRead(pDisk, offFile, pvBuf, cb);
1488 if (RT_FAILURE(vrc))
1489 break;
1490 vrc = RTFileWrite(outFile, pvBuf, cb, NULL);
1491 if (RT_FAILURE(vrc))
1492 break;
1493 offFile += cb;
1494 }
1495 if (RT_FAILURE(vrc))
1496 {
1497 VDCloseAll(pDisk);
1498 if (!fWriteToStdOut)
1499 {
1500 RTFileClose(outFile);
1501 RTFileDelete(Utf8Str(dst).raw());
1502 }
1503 RTPrintf("Error copying image data: %Rrc\n", vrc);
1504 return 1;
1505 }
1506 }
1507 else
1508 {
1509 vrc = VERR_NO_MEMORY;
1510 VDCloseAll(pDisk);
1511 if (!fWriteToStdOut)
1512 {
1513 RTFileClose(outFile);
1514 RTFileDelete(Utf8Str(dst).raw());
1515 }
1516 RTPrintf("Error allocating read buffer: %Rrc\n", vrc);
1517 return 1;
1518 }
1519
1520 if (!fWriteToStdOut)
1521 RTFileClose(outFile);
1522 VDCloseAll(pDisk);
1523 return 0;
1524}
1525
1526static int CmdConvertHardDisk(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1527{
1528 Bstr srcformat;
1529 Bstr dstformat;
1530 Bstr src;
1531 Bstr dst;
1532 int vrc;
1533 PVBOXHDD pSrcDisk = NULL;
1534 PVBOXHDD pDstDisk = NULL;
1535
1536 /* Parse the arguments. */
1537 for (int i = 0; i < argc; i++)
1538 {
1539 if (strcmp(argv[i], "-srcformat") == 0)
1540 {
1541 if (argc <= i + 1)
1542 {
1543 return errorArgument("Missing argument to '%s'", argv[i]);
1544 }
1545 i++;
1546 srcformat = argv[i];
1547 }
1548 else if (strcmp(argv[i], "-dstformat") == 0)
1549 {
1550 if (argc <= i + 1)
1551 {
1552 return errorArgument("Missing argument to '%s'", argv[i]);
1553 }
1554 i++;
1555 dstformat = argv[i];
1556 }
1557 else if (src.isEmpty())
1558 {
1559 src = argv[i];
1560 }
1561 else if (dst.isEmpty())
1562 {
1563 dst = argv[i];
1564 }
1565 else
1566 {
1567 return errorSyntax(USAGE_CONVERTHD, "Invalid parameter '%s'", Utf8Str(argv[i]).raw());
1568 }
1569 }
1570
1571 if (src.isEmpty())
1572 return errorSyntax(USAGE_CONVERTHD, "Mandatory input image parameter missing");
1573 if (dst.isEmpty())
1574 return errorSyntax(USAGE_CONVERTHD, "Mandatory output image parameter missing");
1575
1576
1577 PVDINTERFACE pVDIfs = NULL;
1578 VDINTERFACE vdInterfaceError;
1579 VDINTERFACEERROR vdInterfaceErrorCallbacks;
1580 vdInterfaceErrorCallbacks.cbSize = sizeof(VDINTERFACEERROR);
1581 vdInterfaceErrorCallbacks.enmInterface = VDINTERFACETYPE_ERROR;
1582 vdInterfaceErrorCallbacks.pfnError = handleVDError;
1583
1584 vrc = VDInterfaceAdd(&vdInterfaceError, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1585 &vdInterfaceErrorCallbacks, NULL, &pVDIfs);
1586 AssertRC(vrc);
1587
1588 do
1589 {
1590 /* Try to determine input image format */
1591 if (srcformat.isEmpty())
1592 {
1593 char *pszFormat = NULL;
1594 vrc = VDGetFormat(Utf8Str(src).raw(), &pszFormat);
1595 if (RT_FAILURE(vrc))
1596 {
1597 RTPrintf("No file format specified and autodetect failed - please specify format: %Rrc\n", vrc);
1598 break;
1599 }
1600 srcformat = pszFormat;
1601 RTStrFree(pszFormat);
1602 }
1603
1604 vrc = VDCreate(pVDIfs, &pSrcDisk);
1605 if (RT_FAILURE(vrc))
1606 {
1607 RTPrintf("Error while creating the source virtual disk container: %Rrc\n", vrc);
1608 break;
1609 }
1610
1611 /* Open the input image */
1612 vrc = VDOpen(pSrcDisk, Utf8Str(srcformat).raw(), Utf8Str(src).raw(), VD_OPEN_FLAGS_READONLY, NULL);
1613 if (RT_FAILURE(vrc))
1614 {
1615 RTPrintf("Error while opening the source image: %Rrc\n", vrc);
1616 break;
1617 }
1618
1619 /* Output format defaults to VDI */
1620 if (dstformat.isEmpty())
1621 dstformat = "VDI";
1622
1623 vrc = VDCreate(pVDIfs, &pDstDisk);
1624 if (RT_FAILURE(vrc))
1625 {
1626 RTPrintf("Error while creating the destination virtual disk container: %Rrc\n", vrc);
1627 break;
1628 }
1629
1630 uint64_t cbSize = VDGetSize(pSrcDisk, VD_LAST_IMAGE);
1631 RTPrintf("Converting image \"%s\" with size %RU64 bytes (%RU64MB)...\n", Utf8Str(src).raw(), cbSize, (cbSize + _1M - 1) / _1M);
1632
1633 /* Create the output image */
1634 vrc = VDCopy(pSrcDisk, VD_LAST_IMAGE, pDstDisk, Utf8Str(dstformat).raw(),
1635 Utf8Str(dst).raw(), false, 0, VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED, NULL, NULL, NULL, NULL);
1636 if (RT_FAILURE(vrc))
1637 {
1638 RTPrintf("Error while copying the image: %Rrc\n", vrc);
1639 break;
1640 }
1641 }
1642 while (0);
1643 if (pDstDisk)
1644 VDCloseAll(pDstDisk);
1645 if (pSrcDisk)
1646 VDCloseAll(pSrcDisk);
1647
1648 return RT_SUCCESS(vrc) ? 0 : 1;
1649}
1650
1651/**
1652 * Unloads the neccessary driver.
1653 *
1654 * @returns VBox status code
1655 */
1656int CmdModUninstall(void)
1657{
1658 int rc;
1659
1660 rc = SUPR3Uninstall();
1661 if (RT_SUCCESS(rc))
1662 return 0;
1663 if (rc == VERR_NOT_IMPLEMENTED)
1664 return 0;
1665 return E_FAIL;
1666}
1667
1668/**
1669 * Loads the neccessary driver.
1670 *
1671 * @returns VBox status code
1672 */
1673int CmdModInstall(void)
1674{
1675 int rc;
1676
1677 rc = SUPR3Install();
1678 if (RT_SUCCESS(rc))
1679 return 0;
1680 if (rc == VERR_NOT_IMPLEMENTED)
1681 return 0;
1682 return E_FAIL;
1683}
1684
1685/**
1686 * Wrapper for handling internal commands
1687 */
1688int handleInternalCommands(HandlerArg *a)
1689{
1690 g_fInternalMode = true;
1691
1692 /* at least a command is required */
1693 if (a->argc < 1)
1694 return errorSyntax(USAGE_ALL, "Command missing");
1695
1696 /*
1697 * The 'string switch' on command name.
1698 */
1699 const char *pszCmd = a->argv[0];
1700 if (!strcmp(pszCmd, "loadsyms"))
1701 return CmdLoadSyms(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
1702 //if (!strcmp(pszCmd, "unloadsyms"))
1703 // return CmdUnloadSyms(argc - 1 , &a->argv[1]);
1704 if (!strcmp(pszCmd, "sethduuid") || !strcmp(pszCmd, "setvdiuuid"))
1705 return handleSetHDUUID(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
1706 if (!strcmp(pszCmd, "listpartitions"))
1707 return CmdListPartitions(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
1708 if (!strcmp(pszCmd, "createrawvmdk"))
1709 return CmdCreateRawVMDK(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
1710 if (!strcmp(pszCmd, "renamevmdk"))
1711 return CmdRenameVMDK(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
1712 if (!strcmp(pszCmd, "converttoraw"))
1713 return CmdConvertToRaw(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
1714 if (!strcmp(pszCmd, "converthd"))
1715 return CmdConvertHardDisk(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
1716
1717 if (!strcmp(pszCmd, "modinstall"))
1718 return CmdModInstall();
1719 if (!strcmp(pszCmd, "moduninstall"))
1720 return CmdModUninstall();
1721
1722 /* default: */
1723 return errorSyntax(USAGE_ALL, "Invalid command '%s'", Utf8Str(a->argv[0]).raw());
1724}
1725
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