VirtualBox

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

Last change on this file since 8662 was 8516, checked in by vboxsync, 17 years ago

Add todo, supporting bigger raw disks.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 38.6 KB
Line 
1/** @file
2 *
3 * VBox frontends: VBoxManage (command-line interface):
4 * VBoxInternalManage
5 *
6 * VBoxInternalManage used to be a second CLI for doing special tricks,
7 * not intended for general usage, only for assisting VBox developers.
8 * It is now integrated into VBoxManage.
9 */
10
11/*
12 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
13 *
14 * This file is part of VirtualBox Open Source Edition (OSE), as
15 * available from http://www.virtualbox.org. This file is free software;
16 * you can redistribute it and/or modify it under the terms of the GNU
17 * General Public License (GPL) as published by the Free Software
18 * Foundation, in version 2 as it comes in the "COPYING" file of the
19 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
20 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
21 *
22 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
23 * Clara, CA 95054 USA or visit http://www.sun.com if you need
24 * additional information or have any questions.
25 */
26
27
28
29/*******************************************************************************
30* Header Files *
31*******************************************************************************/
32#include <VBox/com/com.h>
33#include <VBox/com/string.h>
34#include <VBox/com/Guid.h>
35#include <VBox/com/ErrorInfo.h>
36
37#include <VBox/com/VirtualBox.h>
38
39#include <iprt/runtime.h>
40#include <iprt/stream.h>
41#include <iprt/string.h>
42#include <iprt/uuid.h>
43#include <VBox/err.h>
44
45#include <VBox/VBoxHDD.h>
46#include <VBox/VBoxHDD-new.h>
47#include <VBox/sup.h>
48
49#include "VBoxManage.h"
50
51/* Includes for the raw disk stuff. */
52#ifdef RT_OS_WINDOWS
53#include <windows.h>
54#include <winioctl.h>
55#elif RT_OS_LINUX
56#include <errno.h>
57#include <sys/ioctl.h>
58#include <sys/types.h>
59#include <sys/stat.h>
60#include <unistd.h>
61#include <linux/hdreg.h>
62#include <linux/fs.h>
63#endif /* !RT_OS_WINDOWS && !RT_OS_LINUX */
64
65using namespace com;
66
67
68/** Macro for checking whether a partition is of extended type or not. */
69#define PARTTYPE_IS_EXTENDED(x) ((x) == 0x05 || (x) == 0x0f || (x) == 0x85)
70
71/* Maximum number of partitions we can deal with. Ridiculously large number,
72 * but the memory consumption is rather low so who cares about never using
73 * most entries. */
74#define HOSTPARTITION_MAX 100
75
76
77typedef struct HOSTPARTITION
78{
79 unsigned uIndex;
80 unsigned uType;
81 unsigned uStartCylinder;
82 unsigned uStartHead;
83 unsigned uStartSector;
84 unsigned uEndCylinder;
85 unsigned uEndHead;
86 unsigned uEndSector;
87 uint64_t uStart;
88 uint64_t uSize;
89 uint64_t uPartDataStart;
90 uint64_t cPartDataSectors;
91} HOSTPARTITION, *PHOSTPARTITION;
92
93typedef struct HOSTPARTITIONS
94{
95 unsigned cPartitions;
96 HOSTPARTITION aPartitions[HOSTPARTITION_MAX];
97} HOSTPARTITIONS, *PHOSTPARTITIONS;
98
99/** flag whether we're in internal mode */
100bool g_fInternalMode;
101
102/**
103 * Print the usage info.
104 */
105void printUsageInternal(USAGECATEGORY u64Cmd)
106{
107 RTPrintf("Usage: VBoxManage internalcommands <command> [command arguments]\n"
108 "\n"
109 "Commands:\n"
110 "\n"
111 "%s%s%s%s%s%s%s"
112 "WARNING: This is a development tool and shall only be used to analyse\n"
113 " problems. It is completely unsupported and will change in\n"
114 " incompatible ways without warning.\n",
115 (u64Cmd & USAGE_LOADSYMS) ?
116 " loadsyms <vmname>|<uuid> <symfile> [delta] [module] [module address]\n"
117 " This will instruct DBGF to load the given symbolfile\n"
118 " during initialization.\n"
119 "\n"
120 : "",
121 (u64Cmd & USAGE_UNLOADSYMS) ?
122 " unloadsyms <vmname>|<uuid> <symfile>\n"
123 " Removes <symfile> from the list of symbol files that\n"
124 " should be loaded during DBF initialization.\n"
125 "\n"
126 : "",
127 (u64Cmd & USAGE_SETVDIUUID) ?
128 " setvdiuuid <filepath>\n"
129 " Assigns a new UUID to the given VDI file. This way, multiple copies\n"
130 " of VDI containers can be registered.\n"
131 "\n"
132 : "",
133 (u64Cmd & USAGE_LISTPARTITIONS) ?
134 " listpartitions -rawdisk <diskname>\n"
135 " Lists all partitions on <diskname>.\n"
136 "\n"
137 : "",
138 (u64Cmd & USAGE_CREATERAWVMDK) ?
139 " createrawvmdk -filename <filename> -rawdisk <diskname>\n"
140 " [-partitions <list of partition numbers> [-mbr <filename>] ]\n"
141 " [-register] [-relative]\n"
142 " Creates a new VMDK image which gives access to an entite host disk (if\n"
143 " the parameter -partitions is not specified) or some partitions of a\n"
144 " host disk. If access to individual partitions is granted, then the\n"
145 " parameter -mbr can be used to specify an alternative MBR to be used\n"
146 " (the partitioning information in the MBR file is ignored).\n"
147 " The diskname is on Linux e.g. /dev/sda, and on Windows e.g.\n"
148 " \\\\.\\PhysicalDisk0).\n"
149 " On Linux host the parameter -relative causes a VMDK file to be created\n"
150 " which refers to individual partitions instead to the entire disk.\n"
151 " Optionally the created image can be immediately registered.\n"
152 " The necessary partition numbers can be queried with\n"
153 " VBoxManage internalcommands listpartitions\n"
154 "\n"
155 : "",
156#ifdef RT_OS_WINDOWS
157 (u64Cmd & USAGE_MODINSTALL) ?
158 " modinstall\n"
159 " Installs the neccessary driver for the host OS\n"
160 "\n"
161 : "",
162 (u64Cmd & USAGE_MODUNINSTALL) ?
163 " moduninstall\n"
164 " Deinstalls the driver\n"
165 "\n"
166 : ""
167#else
168 "",
169 ""
170#endif
171 );
172}
173
174/** @todo this is no longer necessary, we can enumerate extra data */
175/**
176 * Finds a new unique key name.
177 *
178 * I don't think this is 100% race condition proof, but we assumes
179 * the user is not trying to push this point.
180 *
181 * @returns Result from the insert.
182 * @param pMachine The Machine object.
183 * @param pszKeyBase The base key.
184 * @param rKey Reference to the string object in which we will return the key.
185 */
186static HRESULT NewUniqueKey(ComPtr<IMachine> pMachine, const char *pszKeyBase, Utf8Str &rKey)
187{
188 Bstr Keys;
189 HRESULT hrc = pMachine->GetExtraData(Bstr(pszKeyBase), Keys.asOutParam());
190 if (FAILED(hrc))
191 return hrc;
192
193 /* if there are no keys, it's simple. */
194 if (Keys.isEmpty())
195 {
196 rKey = "1";
197 return pMachine->SetExtraData(Bstr(pszKeyBase), Bstr("1"));
198 }
199
200 /* find a unique number - brute force rulez. */
201 Utf8Str KeysUtf8(Keys);
202 const char *pszKeys = RTStrStripL(KeysUtf8.raw());
203 for (unsigned i = 1; i < 1000000; i++)
204 {
205 char szKey[32];
206 size_t cchKey = RTStrPrintf(szKey, sizeof(szKey), "%#x", i);
207 const char *psz = strstr(pszKeys, szKey);
208 while (psz)
209 {
210 if ( ( psz == pszKeys
211 || psz[-1] == ' ')
212 && ( psz[cchKey] == ' '
213 || !psz[cchKey])
214 )
215 break;
216 psz = strstr(psz + cchKey, szKey);
217 }
218 if (!psz)
219 {
220 rKey = szKey;
221 Utf8StrFmt NewKeysUtf8("%s %s", pszKeys, szKey);
222 return pMachine->SetExtraData(Bstr(pszKeyBase), Bstr(NewKeysUtf8));
223 }
224 }
225 RTPrintf("Error: Cannot find unique key for '%s'!\n", pszKeyBase);
226 return E_FAIL;
227}
228
229
230#if 0
231/**
232 * Remove a key.
233 *
234 * I don't think this isn't 100% race condition proof, but we assumes
235 * the user is not trying to push this point.
236 *
237 * @returns Result from the insert.
238 * @param pMachine The machine object.
239 * @param pszKeyBase The base key.
240 * @param pszKey The key to remove.
241 */
242static HRESULT RemoveKey(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey)
243{
244 Bstr Keys;
245 HRESULT hrc = pMachine->GetExtraData(Bstr(pszKeyBase), Keys.asOutParam());
246 if (FAILED(hrc))
247 return hrc;
248
249 /* if there are no keys, it's simple. */
250 if (Keys.isEmpty())
251 return S_OK;
252
253 char *pszKeys;
254 int rc = RTUtf16ToUtf8(Keys.raw(), &pszKeys);
255 if (RT_SUCCESS(rc))
256 {
257 /* locate it */
258 size_t cchKey = strlen(pszKey);
259 char *psz = strstr(pszKeys, pszKey);
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, pszKey);
269 }
270 if (psz)
271 {
272 /* remove it */
273 char *pszNext = RTStrStripL(psz + cchKey);
274 if (*pszNext)
275 memmove(psz, pszNext, strlen(pszNext) + 1);
276 else
277 *psz = '\0';
278 psz = RTStrStrip(pszKeys);
279
280 /* update */
281 hrc = pMachine->SetExtraData(Bstr(pszKeyBase), Bstr(psz));
282 }
283
284 RTStrFree(pszKeys);
285 return hrc;
286 }
287 else
288 RTPrintf("error: failed to delete key '%s' from '%s', string conversion error %Vrc!\n",
289 pszKey, pszKeyBase, rc);
290
291 return E_FAIL;
292}
293#endif
294
295
296/**
297 * Sets a key value, does necessary error bitching.
298 *
299 * @returns COM status code.
300 * @param pMachine The Machine object.
301 * @param pszKeyBase The key base.
302 * @param pszKey The key.
303 * @param pszAttribute The attribute name.
304 * @param pszValue The string value.
305 */
306static HRESULT SetString(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey, const char *pszAttribute, const char *pszValue)
307{
308 HRESULT hrc = pMachine->SetExtraData(Bstr(Utf8StrFmt("%s/%s/%s", pszKeyBase, pszKey, pszAttribute)), Bstr(pszValue));
309 if (FAILED(hrc))
310 RTPrintf("error: Failed to set '%s/%s/%s' to '%s'! hrc=%#x\n",
311 pszKeyBase, pszKey, pszAttribute, pszValue, hrc);
312 return hrc;
313}
314
315
316/**
317 * Sets a key value, does necessary error bitching.
318 *
319 * @returns COM status code.
320 * @param pMachine The Machine object.
321 * @param pszKeyBase The key base.
322 * @param pszKey The key.
323 * @param pszAttribute The attribute name.
324 * @param u64Value The value.
325 */
326static HRESULT SetUInt64(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey, const char *pszAttribute, uint64_t u64Value)
327{
328 char szValue[64];
329 RTStrPrintf(szValue, sizeof(szValue), "%#RX64", u64Value);
330 return SetString(pMachine, pszKeyBase, pszKey, pszAttribute, szValue);
331}
332
333
334/**
335 * Sets a key value, does necessary error bitching.
336 *
337 * @returns COM status code.
338 * @param pMachine The Machine object.
339 * @param pszKeyBase The key base.
340 * @param pszKey The key.
341 * @param pszAttribute The attribute name.
342 * @param i64Value The value.
343 */
344static HRESULT SetInt64(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey, const char *pszAttribute, int64_t i64Value)
345{
346 char szValue[64];
347 RTStrPrintf(szValue, sizeof(szValue), "%RI64", i64Value);
348 return SetString(pMachine, pszKeyBase, pszKey, pszAttribute, szValue);
349}
350
351
352/**
353 * Identical to the 'loadsyms' command.
354 */
355static int CmdLoadSyms(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
356{
357 HRESULT rc;
358
359 /*
360 * Get the VM
361 */
362 ComPtr<IMachine> machine;
363 /* assume it's a UUID */
364 rc = aVirtualBox->GetMachine(Guid(argv[0]), machine.asOutParam());
365 if (FAILED(rc) || !machine)
366 {
367 /* must be a name */
368 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]), machine.asOutParam()), 1);
369 }
370
371 /*
372 * Parse the command.
373 */
374 const char *pszFilename;
375 int64_t offDelta = 0;
376 const char *pszModule = NULL;
377 uint64_t ModuleAddress = ~0;
378 uint64_t ModuleSize = 0;
379
380 /* filename */
381 if (argc < 2)
382 return errorArgument("Missing the filename argument!\n");
383 pszFilename = argv[1];
384
385 /* offDelta */
386 if (argc >= 3)
387 {
388 int rc = RTStrToInt64Ex(argv[2], NULL, 0, &offDelta);
389 if (VBOX_FAILURE(rc))
390 return errorArgument(argv[0], "Failed to read delta '%s', rc=%Vrc\n", argv[2], rc);
391 }
392
393 /* pszModule */
394 if (argc >= 4)
395 pszModule = argv[3];
396
397 /* ModuleAddress */
398 if (argc >= 5)
399 {
400 int rc = RTStrToUInt64Ex(argv[4], NULL, 0, &ModuleAddress);
401 if (VBOX_FAILURE(rc))
402 return errorArgument(argv[0], "Failed to read module address '%s', rc=%Vrc\n", argv[4], rc);
403 }
404
405 /* ModuleSize */
406 if (argc >= 6)
407 {
408 int rc = RTStrToUInt64Ex(argv[5], NULL, 0, &ModuleSize);
409 if (VBOX_FAILURE(rc))
410 return errorArgument(argv[0], "Failed to read module size '%s', rc=%Vrc\n", argv[5], rc);
411 }
412
413 /*
414 * Add extra data.
415 */
416 Utf8Str KeyStr;
417 HRESULT hrc = NewUniqueKey(machine, "VBoxInternal/DBGF/loadsyms", KeyStr);
418 if (SUCCEEDED(hrc))
419 hrc = SetString(machine, "VBoxInternal/DBGF/loadsyms", KeyStr, "Filename", pszFilename);
420 if (SUCCEEDED(hrc) && argc >= 3)
421 hrc = SetInt64(machine, "VBoxInternal/DBGF/loadsyms", KeyStr, "Delta", offDelta);
422 if (SUCCEEDED(hrc) && argc >= 4)
423 hrc = SetString(machine, "VBoxInternal/DBGF/loadsyms", KeyStr, "Module", pszModule);
424 if (SUCCEEDED(hrc) && argc >= 5)
425 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadsyms", KeyStr, "ModuleAddress", ModuleAddress);
426 if (SUCCEEDED(hrc) && argc >= 6)
427 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadsyms", KeyStr, "ModuleSize", ModuleSize);
428
429 return FAILED(hrc);
430}
431
432static int handleSetVDIUUID(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
433{
434 /* we need exactly one parameter: the vdi file */
435 if (argc != 1)
436 {
437 return errorSyntax(USAGE_SETVDIUUID, "Not enough parameters");
438 }
439
440 /* generate a new UUID */
441 Guid uuid;
442 uuid.create();
443
444 /* just try it */
445 int rc = VDISetImageUUIDs(argv[0], uuid.raw(), NULL, NULL, NULL);
446 if (VBOX_FAILURE(rc))
447 {
448 RTPrintf("Error while setting a new UUID: %Vrc (%d)\n", rc, rc);
449 }
450 else
451 {
452 RTPrintf("UUID changed to: %s\n", uuid.toString().raw());
453 }
454
455 return 0;
456}
457
458
459static DECLCALLBACK(void) handleVDError(void *pvUser, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list va)
460{
461 RTPrintf("ERROR: ");
462 RTPrintfV(pszFormat, va);
463 RTPrintf("\n");
464 RTPrintf("Error code %Vrc at %s(%u) in function %s\n", rc, RT_SRC_POS_ARGS);
465}
466
467static int partRead(RTFILE File, PHOSTPARTITIONS pPart)
468{
469 uint8_t aBuffer[512];
470 int rc;
471
472 pPart->cPartitions = 0;
473 memset(pPart->aPartitions, '\0', sizeof(pPart->aPartitions));
474 rc = RTFileReadAt(File, 0, &aBuffer, sizeof(aBuffer), NULL);
475 if (VBOX_FAILURE(rc))
476 return rc;
477 if (aBuffer[510] != 0x55 || aBuffer[511] != 0xaa)
478 return VERR_INVALID_PARAMETER;
479
480 unsigned uExtended = (unsigned)-1;
481
482 for (unsigned i = 0; i < 4; i++)
483 {
484 uint8_t *p = &aBuffer[0x1be + i * 16];
485 if (p[4] == 0)
486 continue;
487 PHOSTPARTITION pCP = &pPart->aPartitions[pPart->cPartitions++];
488 pCP->uIndex = i + 1;
489 pCP->uType = p[4];
490 pCP->uStartCylinder = (uint32_t)p[3] + ((uint32_t)(p[2] & 0xc0) << 2);
491 pCP->uStartHead = p[1];
492 pCP->uStartSector = p[2] & 0x3f;
493 pCP->uEndCylinder = (uint32_t)p[7] + ((uint32_t)(p[6] & 0xc0) << 2);
494 pCP->uEndHead = p[5];
495 pCP->uEndSector = p[6] & 0x3f;
496 pCP->uStart = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
497 pCP->uSize = RT_MAKE_U32_FROM_U8(p[12], p[13], p[14], p[15]);
498 pCP->uPartDataStart = 0; /* will be filled out later properly. */
499 pCP->cPartDataSectors = 0;
500
501 if (PARTTYPE_IS_EXTENDED(p[4]))
502 {
503 if (uExtended == (unsigned)-1)
504 uExtended = pCP - pPart->aPartitions;
505 else
506 {
507 RTPrintf("More than one extended partition. Aborting\n");
508 return VERR_INVALID_PARAMETER;
509 }
510 }
511 }
512
513 if (uExtended != (unsigned)-1)
514 {
515 unsigned uIndex = 5;
516 uint64_t uStart = pPart->aPartitions[uExtended].uStart;
517 uint64_t uOffset = 0;
518 if (!uStart)
519 {
520 RTPrintf("Inconsistency for logical partition start. Aborting\n");
521 return VERR_INVALID_PARAMETER;
522 }
523
524 do
525 {
526 rc = RTFileReadAt(File, (uStart + uOffset) * 512, &aBuffer, sizeof(aBuffer), NULL);
527 if (VBOX_FAILURE(rc))
528 return rc;
529
530 if (aBuffer[510] != 0x55 || aBuffer[511] != 0xaa)
531 {
532 RTPrintf("Logical partition without magic. Aborting\n");
533 return VERR_INVALID_PARAMETER;
534 }
535 uint8_t *p = &aBuffer[0x1be];
536
537 if (p[4] == 0)
538 {
539 RTPrintf("Logical partition with type 0 encountered. Aborting\n");
540 return VERR_INVALID_PARAMETER;
541 }
542
543 PHOSTPARTITION pCP = &pPart->aPartitions[pPart->cPartitions++];
544 pCP->uIndex = uIndex;
545 pCP->uType = p[4];
546 pCP->uStartCylinder = (uint32_t)p[3] + ((uint32_t)(p[2] & 0xc0) << 2);
547 pCP->uStartHead = p[1];
548 pCP->uStartSector = p[2] & 0x3f;
549 pCP->uEndCylinder = (uint32_t)p[7] + ((uint32_t)(p[6] & 0xc0) << 2);
550 pCP->uEndHead = p[5];
551 pCP->uEndSector = p[6] & 0x3f;
552 uint32_t uStartOffset = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
553 pCP->uStart = uStart + uOffset + uStartOffset;
554 pCP->uSize = RT_MAKE_U32_FROM_U8(p[12], p[13], p[14], p[15]);
555 /* Fill out partitioning location info for EBR. */
556 pCP->uPartDataStart = uStart + uOffset;
557 pCP->cPartDataSectors = RT_MIN(uStartOffset, 63);
558 p += 16;
559 if (p[4] == 0)
560 uExtended = (unsigned)-1;
561 else if (PARTTYPE_IS_EXTENDED(p[4]))
562 {
563 uExtended = uIndex++;
564 uOffset = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
565 }
566 else
567 {
568 RTPrintf("Logical partition chain broken. Aborting\n");
569 return VERR_INVALID_PARAMETER;
570 }
571 } while (uExtended != (unsigned)-1);
572 }
573
574 /* Sort partitions in ascending order of start sector. Also do a lot of
575 * consistency checking. */
576 uint64_t uPrevEnd = 0;
577 for (unsigned i = 0; i < pPart->cPartitions-1; i++)
578 {
579 unsigned uMinIdx = i;
580 uint64_t uMinVal = pPart->aPartitions[i].uStart;
581 for (unsigned j = i + 1; j < pPart->cPartitions; j++)
582 {
583 if (pPart->aPartitions[j].uStart < uMinVal)
584 {
585 uMinIdx = j;
586 uMinVal = pPart->aPartitions[j].uStart;
587 }
588 else if (pPart->aPartitions[j].uStart == uMinVal)
589 {
590 RTPrintf("Two partitions start at the same place. Aborting\n");
591 return VERR_INVALID_PARAMETER;
592 } else if (pPart->aPartitions[j].uStart == 0)
593 {
594 RTPrintf("Partition starts at sector 0. Aborting\n");
595 return VERR_INVALID_PARAMETER;
596 }
597 }
598 if (uMinIdx != i)
599 {
600 /* Swap entries at index i and uMinIdx. */
601 memcpy(&pPart->aPartitions[pPart->cPartitions],
602 &pPart->aPartitions[i], sizeof(HOSTPARTITION));
603 memcpy(&pPart->aPartitions[i],
604 &pPart->aPartitions[uMinIdx], sizeof(HOSTPARTITION));
605 memcpy(&pPart->aPartitions[uMinIdx],
606 &pPart->aPartitions[pPart->cPartitions], sizeof(HOSTPARTITION));
607 }
608 if (pPart->aPartitions[i].cPartDataSectors)
609 {
610 if (pPart->aPartitions[i].uPartDataStart < uPrevEnd)
611 {
612 RTPrintf("Overlapping partition description areas. Aborting\n");
613 return VERR_INVALID_PARAMETER;
614 }
615 uPrevEnd = pPart->aPartitions[i].uPartDataStart + pPart->aPartitions[i].cPartDataSectors;
616 }
617 if (pPart->aPartitions[i].uStart < uPrevEnd)
618 {
619 RTPrintf("Overlapping partitions. Aborting\n");
620 return VERR_INVALID_PARAMETER;
621 }
622 if (!PARTTYPE_IS_EXTENDED(pPart->aPartitions[i].uType))
623 uPrevEnd = pPart->aPartitions[i].uStart + pPart->aPartitions[i].uSize;
624 }
625
626 /* Fill out partitioning location info for MBR. */
627 pPart->aPartitions[0].uPartDataStart = 0;
628 pPart->aPartitions[0].cPartDataSectors = RT_MIN(pPart->aPartitions[0].uStart, 63);
629
630 return VINF_SUCCESS;
631}
632
633HRESULT CmdListPartitions(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
634{
635 Utf8Str rawdisk;
636
637 /* let's have a closer look at the arguments */
638 for (int i = 0; i < argc; i++)
639 {
640 if (strcmp(argv[i], "-rawdisk") == 0)
641 {
642 if (argc <= i + 1)
643 {
644 return errorArgument("Missing argument to '%s'", argv[i]);
645 }
646 i++;
647 rawdisk = argv[i];
648 }
649 else
650 {
651 return errorSyntax(USAGE_LISTPARTITIONS, "Invalid parameter '%s'", Utf8Str(argv[i]).raw());
652 }
653 }
654
655 if (rawdisk.isEmpty())
656 return errorSyntax(USAGE_LISTPARTITIONS, "Mandatory parameter -rawdisk missing");
657
658 RTFILE RawFile;
659 int vrc = RTFileOpen(&RawFile, rawdisk.raw(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE);
660 if (VBOX_FAILURE(vrc))
661 {
662 RTPrintf("Error opening the raw disk: %Vrc\n", vrc);
663 return vrc;
664 }
665
666 HOSTPARTITIONS partitions;
667 vrc = partRead(RawFile, &partitions);
668 if (VBOX_FAILURE(vrc))
669 return vrc;
670
671 RTPrintf("Number Type StartCHS EndCHS Size (MiB) Start (Sect)\n");
672 for (unsigned i = 0; i < partitions.cPartitions; i++)
673 {
674 /* Suppress printing the extended partition. Otherwise people
675 * might add it to the list of partitions for raw partition
676 * access (which is not good). */
677 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
678 continue;
679
680 RTPrintf("%-7u %#04x %-4u/%-3u/%-2u %-4u/%-3u/%-2u %10llu %10llu\n",
681 partitions.aPartitions[i].uIndex,
682 partitions.aPartitions[i].uType,
683 partitions.aPartitions[i].uStartCylinder,
684 partitions.aPartitions[i].uStartHead,
685 partitions.aPartitions[i].uStartSector,
686 partitions.aPartitions[i].uEndCylinder,
687 partitions.aPartitions[i].uEndHead,
688 partitions.aPartitions[i].uEndSector,
689 partitions.aPartitions[i].uSize / 2048,
690 partitions.aPartitions[i].uStart);
691 }
692
693 return 0;
694}
695
696HRESULT CmdCreateRawVMDK(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
697{
698 HRESULT rc = S_OK;
699 Bstr filename;
700 const char *pszMBRFilename = NULL;
701 Utf8Str rawdisk;
702 const char *pszPartitions = NULL;
703 bool fRegister = false;
704 bool fRelative = false;
705
706 /* let's have a closer look at the arguments */
707 for (int i = 0; i < argc; i++)
708 {
709 if (strcmp(argv[i], "-filename") == 0)
710 {
711 if (argc <= i + 1)
712 {
713 return errorArgument("Missing argument to '%s'", argv[i]);
714 }
715 i++;
716 filename = argv[i];
717 }
718 else if (strcmp(argv[i], "-mbr") == 0)
719 {
720 if (argc <= i + 1)
721 {
722 return errorArgument("Missing argument to '%s'", argv[i]);
723 }
724 i++;
725 pszMBRFilename = argv[i];
726 }
727 else if (strcmp(argv[i], "-rawdisk") == 0)
728 {
729 if (argc <= i + 1)
730 {
731 return errorArgument("Missing argument to '%s'", argv[i]);
732 }
733 i++;
734 rawdisk = argv[i];
735 }
736 else if (strcmp(argv[i], "-partitions") == 0)
737 {
738 if (argc <= i + 1)
739 {
740 return errorArgument("Missing argument to '%s'", argv[i]);
741 }
742 i++;
743 pszPartitions = argv[i];
744 }
745 else if (strcmp(argv[i], "-register") == 0)
746 {
747 fRegister = true;
748 }
749#ifdef RT_OS_LINUX
750 else if (strcmp(argv[i], "-relative") == 0)
751 {
752 fRelative = true;
753 }
754#endif /* RT_OS_LINUX */
755 else
756 {
757 return errorSyntax(USAGE_CREATERAWVMDK, "Invalid parameter '%s'", Utf8Str(argv[i]).raw());
758 }
759 }
760
761 if (filename.isEmpty())
762 return errorSyntax(USAGE_CREATERAWVMDK, "Mandatory parameter -filename missing");
763 if (rawdisk.isEmpty())
764 return errorSyntax(USAGE_CREATERAWVMDK, "Mandatory parameter -rawdisk missing");
765 if (!pszPartitions && pszMBRFilename)
766 return errorSyntax(USAGE_CREATERAWVMDK, "The parameter -mbr is only valid when the parameter -partitions is also present");
767
768 RTFILE RawFile;
769 int vrc = RTFileOpen(&RawFile, rawdisk.raw(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE);
770 if (VBOX_FAILURE(vrc))
771 {
772 RTPrintf("Error opening the raw disk: %Vrc\n", vrc);
773 return vrc;
774 }
775
776 uint64_t cbSize = 0;
777#ifdef RT_OS_WINDOWS
778 DISK_GEOMETRY DriveGeo;
779 DWORD cbDriveGeo;
780 /* Windows NT has no IOCTL_DISK_GET_LENGTH_INFORMATION ioctl. This was
781 * added to Windows XP, so use the available info from DriveGeo. */
782 if (DeviceIoControl((HANDLE)RawFile,
783 IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,
784 &DriveGeo, sizeof(DriveGeo), &cbDriveGeo, NULL))
785 {
786 if (DriveGeo.MediaType == FixedMedia)
787 {
788 cbSize = DriveGeo.Cylinders.QuadPart
789 * DriveGeo.TracksPerCylinder
790 * DriveGeo.SectorsPerTrack
791 * DriveGeo.BytesPerSector;
792 }
793 else
794 return VERR_MEDIA_NOT_RECOGNIZED;
795 }
796 else
797 rc = RTErrConvertFromWin32(GetLastError());
798#elif defined(RT_OS_LINUX)
799 struct stat DevStat;
800 if (!fstat(RawFile, &DevStat) && S_ISBLK(DevStat.st_mode))
801 {
802 /** @todo add a BLKGETSIZE64 ioctl here, as it eliminates the 2 TByte
803 * limit. But be careful, Linux 2.4.18 is the first revision with
804 * working BLKGETSIZE64, and in 2.5.x it's pretty random. 2.6.0 works. */
805 long cBlocks;
806 if (!ioctl(RawFile, BLKGETSIZE, &cBlocks))
807 cbSize = (uint64_t)cBlocks * 512;
808 else
809 return RTErrConvertFromErrno(errno);
810 }
811 else
812 {
813 RTPrintf("File '%s' is no disk\n", rawdisk.raw());
814 return VERR_INVALID_PARAMETER;
815 }
816#else /* !RT_OS_WINDOWS && !RT_OS_LINUX */
817 /* Hopefully this works on all other hosts. If it doesn't, it'll just fail
818 * creating the VMDK, so no real harm done. */
819 vrc = RTFileGetSize(RawFile, &cbSize);
820 if (VBOX_FAILURE(vrc))
821 {
822 RTPrintf("Error getting the size of the raw disk: %Vrc\n", vrc);
823 return vrc;
824 }
825#endif /* !RT_OS_WINDOWS && !RT_OS_LINUX */
826
827 PVBOXHDD pDisk = NULL;
828 VBOXHDDRAW RawDescriptor;
829 HOSTPARTITIONS partitions;
830 uint32_t uPartitions = 0;
831
832 RawDescriptor.szSignature[0] = 'R';
833 RawDescriptor.szSignature[1] = 'A';
834 RawDescriptor.szSignature[2] = 'W';
835 RawDescriptor.szSignature[3] = '\0';
836 if (!pszPartitions)
837 {
838 RawDescriptor.fRawDisk = true;
839 RawDescriptor.pszRawDisk = rawdisk.raw();
840 }
841 else
842 {
843 RawDescriptor.fRawDisk = false;
844 RawDescriptor.pszRawDisk = NULL;
845 RawDescriptor.cPartitions = 0;
846
847 const char *p = pszPartitions;
848 char *pszNext;
849 uint32_t u32;
850 while (*p != '\0')
851 {
852 vrc = RTStrToUInt32Ex(p, &pszNext, 0, &u32);
853 if (VBOX_FAILURE(vrc))
854 {
855 RTPrintf("Incorrect value in partitions parameter\n");
856 return vrc;
857 }
858 uPartitions |= RT_BIT(u32);
859 p = pszNext;
860 if (*p == ',')
861 p++;
862 else if (*p != '\0')
863 {
864 RTPrintf("Incorrect separator in partitions parameter\n");
865 return VERR_INVALID_PARAMETER;
866 }
867 }
868
869 vrc = partRead(RawFile, &partitions);
870 if (VBOX_FAILURE(vrc))
871 {
872 RTPrintf("Error reading the partition information from '%s'\n", rawdisk.raw());
873 return vrc;
874 }
875
876 for (unsigned i = 0; i < partitions.cPartitions; i++)
877 {
878 if ( uPartitions & RT_BIT(partitions.aPartitions[i].uIndex)
879 && PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
880 {
881 /* Some ignorant user specified an extended partition.
882 * Bad idea, as this would trigger an overlapping
883 * partitions error later during VMDK creation. So warn
884 * here and ignore what the user requested. */
885 RTPrintf("Warning: it is not possible (and necessary) to explicitly give access to the\n"
886 " extended partition %u. If required, enable access to all logical\n"
887 " partitions inside this extended partition.\n", partitions.aPartitions[i].uIndex);
888 uPartitions &= ~RT_BIT(partitions.aPartitions[i].uIndex);
889 }
890 }
891
892 RawDescriptor.cPartitions = partitions.cPartitions;
893 RawDescriptor.pPartitions = (PVBOXHDDRAWPART)RTMemAllocZ(partitions.cPartitions * sizeof(VBOXHDDRAWPART));
894 if (!RawDescriptor.pPartitions)
895 return VERR_NO_MEMORY;
896 for (unsigned i = 0; i < partitions.cPartitions; i++)
897 {
898 if (uPartitions & RT_BIT(partitions.aPartitions[i].uIndex))
899 {
900 if (fRelative)
901 {
902#ifdef RT_OS_LINUX
903 /* Refer to the correct partition and use offset 0. */
904 char *pszRawName;
905 vrc = RTStrAPrintf(&pszRawName, "%s%u", rawdisk.raw(),
906 partitions.aPartitions[i].uIndex);
907 if (VBOX_FAILURE(vrc))
908 {
909 RTPrintf("Error creating reference to individual partition %u, rc=%Vrc\n",
910 partitions.aPartitions[i].uIndex, vrc);
911 return vrc;
912 }
913 RawDescriptor.pPartitions[i].pszRawDevice = pszRawName;
914 RawDescriptor.pPartitions[i].uPartitionStartOffset = 0;
915 RawDescriptor.pPartitions[i].uPartitionStart = partitions.aPartitions[i].uStart * 512;
916#else
917 /** @todo not implemented yet for Windows host. Treat just
918 * like not specified (this code is actually never reached). */
919 RawDescriptor.pPartitions[i].pszRawDevice = rawdisk.raw();
920 RawDescriptor.pPartitions[i].uPartitionStartOffset = partitions.aPartitions[i].uStart * 512;
921 RawDescriptor.pPartitions[i].uPartitionStart = partitions.aPartitions[i].uStart * 512;
922#endif
923 }
924 else
925 {
926 /* This is the "everything refers to the base raw device"
927 * variant. This requires opening the base device in RW
928 * mode even for creation. */
929 RawDescriptor.pPartitions[i].pszRawDevice = rawdisk.raw();
930 RawDescriptor.pPartitions[i].uPartitionStartOffset = partitions.aPartitions[i].uStart * 512;
931 RawDescriptor.pPartitions[i].uPartitionStart = partitions.aPartitions[i].uStart * 512;
932 }
933 }
934 else
935 {
936 /* Suppress access to this partition. */
937 RawDescriptor.pPartitions[i].pszRawDevice = NULL;
938 RawDescriptor.pPartitions[i].uPartitionStartOffset = 0;
939 /* This is used in the plausibility check in the creation
940 * code. In theory it's a dummy, but I don't want to make
941 * the VMDK creatiion any more complicated than what it needs
942 * to be. */
943 RawDescriptor.pPartitions[i].uPartitionStart = partitions.aPartitions[i].uStart * 512;
944 }
945 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
946 {
947 /* Suppress exporting the actual extended partition. Only
948 * logical partitions should be processed. However completely
949 * ignoring it leads to leaving out the MBR data. */
950 RawDescriptor.pPartitions[i].cbPartition = 0;
951 }
952 else
953 RawDescriptor.pPartitions[i].cbPartition = partitions.aPartitions[i].uSize * 512;
954 RawDescriptor.pPartitions[i].uPartitionDataStart = partitions.aPartitions[i].uPartDataStart * 512;
955 RawDescriptor.pPartitions[i].cbPartitionData = partitions.aPartitions[i].cPartDataSectors * 512;
956 if (RawDescriptor.pPartitions[i].cbPartitionData)
957 {
958 Assert (RawDescriptor.pPartitions[i].cbPartitionData -
959 (size_t)RawDescriptor.pPartitions[i].cbPartitionData == 0);
960 void *pPartData = RTMemAlloc((size_t)RawDescriptor.pPartitions[i].cbPartitionData);
961 if (!pPartData)
962 return VERR_NO_MEMORY;
963 vrc = RTFileReadAt(RawFile, partitions.aPartitions[i].uPartDataStart * 512, pPartData, (size_t)RawDescriptor.pPartitions[i].cbPartitionData, NULL);
964 if (VBOX_FAILURE(vrc))
965 {
966 RTPrintf("Cannot read partition data from raw device '%s': %Vrc\n", rawdisk.raw(), vrc);
967 return vrc;
968 }
969 /* Splice in the replacement MBR code if specified. */
970 if ( partitions.aPartitions[i].uPartDataStart == 0
971 && pszMBRFilename)
972 {
973 RTFILE MBRFile;
974 vrc = RTFileOpen(&MBRFile, pszMBRFilename, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE);
975 if (VBOX_FAILURE(vrc))
976 {
977 RTPrintf("Cannot open replacement MBR file '%s' specified with -mbr: %Vrc\n", pszMBRFilename, vrc);
978 return vrc;
979 }
980 vrc = RTFileReadAt(MBRFile, 0, pPartData, 0x1be, NULL);
981 RTFileClose(MBRFile);
982 if (VBOX_FAILURE(vrc))
983 {
984 RTPrintf("Cannot read replacement MBR file '%s': %Vrc\n", pszMBRFilename, vrc);
985 return vrc;
986 }
987 }
988 RawDescriptor.pPartitions[i].pvPartitionData = pPartData;
989 }
990 }
991 }
992
993 RTFileClose(RawFile);
994
995 vrc = VDCreate(handleVDError, NULL, &pDisk);
996 if (VBOX_FAILURE(vrc))
997 {
998 RTPrintf("Error while creating the virtual disk container: %Vrc\n", vrc);
999 return vrc;
1000 }
1001
1002 Assert(RT_MIN(cbSize / 512 / 16 / 63, 16383) -
1003 (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383) == 0);
1004 PDMMEDIAGEOMETRY PCHS, LCHS;
1005 PCHS.cCylinders = (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383);
1006 PCHS.cHeads = 16;
1007 PCHS.cSectors = 63;
1008 LCHS.cCylinders = 0;
1009 LCHS.cHeads = 0;
1010 LCHS.cSectors = 0;
1011 vrc = VDCreateBase(pDisk, "VMDK", Utf8Str(filename).raw(),
1012 VD_IMAGE_TYPE_FIXED, cbSize,
1013 VD_VMDK_IMAGE_FLAGS_RAWDISK, (char *)&RawDescriptor,
1014 &PCHS, &LCHS, VD_OPEN_FLAGS_NORMAL, NULL, NULL);
1015 if (VBOX_FAILURE(vrc))
1016 {
1017 RTPrintf("Error while creating the raw disk VMDK: %Vrc\n", vrc);
1018 return vrc;
1019 }
1020 RTPrintf("RAW host disk access VMDK file %s created successfully.\n", Utf8Str(filename).raw());
1021
1022 VDCloseAll(pDisk);
1023
1024 /* Clean up allocated memory etc. */
1025 if (pszPartitions)
1026 {
1027 for (unsigned i = 0; i < partitions.cPartitions; i++)
1028 {
1029 if (uPartitions & RT_BIT(partitions.aPartitions[i].uIndex))
1030 {
1031 if (fRelative)
1032 {
1033#ifdef RT_OS_LINUX
1034 /* Free memory allocated above. */
1035 RTStrFree((char *)(void *)RawDescriptor.pPartitions[i].pszRawDevice);
1036#endif /* RT_OS_LINUX */
1037 }
1038 }
1039 }
1040 }
1041
1042 if (fRegister)
1043 {
1044 ComPtr<IHardDisk> hardDisk;
1045 CHECK_ERROR(aVirtualBox, OpenHardDisk(filename, hardDisk.asOutParam()));
1046
1047 if (SUCCEEDED(rc) && hardDisk)
1048 {
1049 CHECK_ERROR(aVirtualBox, RegisterHardDisk(hardDisk));
1050 }
1051 }
1052
1053 return SUCCEEDED(rc) ? 0 : 1;
1054}
1055
1056/**
1057 * Unloads the neccessary driver.
1058 *
1059 * @returns VBox status code
1060 */
1061int CmdModUninstall(void)
1062{
1063 int rc;
1064
1065 rc = SUPUninstall();
1066 if (RT_SUCCESS(rc))
1067 return 0;
1068 if (rc == VERR_NOT_IMPLEMENTED)
1069 return 0;
1070 return E_FAIL;
1071}
1072
1073/**
1074 * Loads the neccessary driver.
1075 *
1076 * @returns VBox status code
1077 */
1078int CmdModInstall(void)
1079{
1080 int rc;
1081
1082 rc = SUPInstall();
1083 if (RT_SUCCESS(rc))
1084 return 0;
1085 if (rc == VERR_NOT_IMPLEMENTED)
1086 return 0;
1087 return E_FAIL;
1088}
1089
1090/**
1091 * Wrapper for handling internal commands
1092 */
1093int handleInternalCommands(int argc, char *argv[],
1094 ComPtr <IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1095{
1096 g_fInternalMode = true;
1097
1098 /* at least a command is required */
1099 if (argc < 1)
1100 return errorSyntax(USAGE_ALL, "Command missing");
1101
1102 /*
1103 * The 'string switch' on command name.
1104 */
1105 const char *pszCmd = argv[0];
1106 if (!strcmp(pszCmd, "loadsyms"))
1107 return CmdLoadSyms(argc - 1, &argv[1], aVirtualBox, aSession);
1108 //if (!strcmp(pszCmd, "unloadsyms"))
1109 // return CmdUnloadSyms(argc - 1 , &argv[1]);
1110 if (!strcmp(pszCmd, "setvdiuuid"))
1111 return handleSetVDIUUID(argc - 1, &argv[1], aVirtualBox, aSession);
1112 if (!strcmp(pszCmd, "listpartitions"))
1113 return CmdListPartitions(argc - 1, &argv[1], aVirtualBox, aSession);
1114 if (!strcmp(pszCmd, "createrawvmdk"))
1115 return CmdCreateRawVMDK(argc - 1, &argv[1], aVirtualBox, aSession);
1116
1117 if (!strcmp(pszCmd, "modinstall"))
1118 return CmdModInstall();
1119 if (!strcmp(pszCmd, "moduninstall"))
1120 return CmdModUninstall();
1121
1122 /* default: */
1123 return errorSyntax(USAGE_ALL, "Invalid command '%s'", Utf8Str(argv[0]).raw());
1124}
Note: See TracBrowser for help on using the repository browser.

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