VirtualBox

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

Last change on this file since 20928 was 20928, checked in by vboxsync, 15 years ago

API/others: Renamed IConsole::discardSavedState to IConsole::forgetSavedState, added parameter. Deleted old IConsole::powerDown, renamed IConsole::powerDownAsync to IConsole::powerDown (as promised for 2.1). Implemented perl sample code for registering a hard disk. Cleaned up constant formatting in the API docs. Updated SDK changelog. Renamed com/errorprint2.h to com/errorprint.h, added a few assertion variants. Eliminated com/errorprint_legacy.h. Adjusted all files using the affected headers and APIs. Renamed tstHeadless2 to tstHeadless.

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