1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
|
/*
Title: exporter.cpp - Export a function as an object or C file
Copyright (c) 2006-7 David C.J. Matthews
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef WIN32
#include "winconfig.h"
#else
#include "config.h"
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x)
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#include "exporter.h"
#include "save_vec.h"
#include "polystring.h"
#include "run_time.h"
#include "osmem.h"
#include "scanaddrs.h"
#include "gc.h"
#include "machine_dep.h"
#include "diagnostics.h"
#include "memmgr.h"
#include "processes.h" // For IO_SPACING
#include "pexport.h"
#ifdef HAVE_PECOFF
#include "pecoffexport.h"
#elif defined(HAVE_ELF_H)
#include "elfexport.h"
#elif defined(HAVE_MACH_O_RELOC_H)
#include "machoexport.h"
#endif
#if(!defined(MAXPATHLEN) && defined(MAX_PATH))
#define MAXPATHLEN MAX_PATH
#endif
/*
To export the function and everything reachable from it we need to copy
all the objects into a new area. We leave tombstones in the original
objects by overwriting the length word. That prevents us from copying an
object twice and breaks loops. Once we've copied the objects we then
have to go back over the memory and turn the tombstones back into length
words.
*/
CopyScan::CopyScan(unsigned h): hierarchy(h)
{
ASSERT(gMem.neSpaces == 0);
// Set the space sizes to a quarter the space currently in use. Making
// the spaces too large may be a problem if we're very close to the maximum
// address space. Making them too small may increase the cost of linking.
defaultImmSize = defaultMutSize = 0;
defaultNoOverSize = 4096; // This can be small.
unsigned i;
for (i = 0; i < gMem.npSpaces; i++)
{
MemSpace *space = gMem.pSpaces[i];
POLYUNSIGNED size = (space->top-space->bottom)/4;
if (space->isMutable)
defaultMutSize += size;
else
defaultImmSize += size;
}
for (i = 0; i < gMem.nlSpaces; i++)
{
LocalMemSpace *space = gMem.lSpaces[i];
POLYUNSIGNED size = (space->top-space->pointer)/4;
if (space->isMutable)
defaultMutSize += size;
else
defaultImmSize += size;
}
if (defaultMutSize < 1024*1024)
defaultMutSize = 1024*1024;
if (defaultImmSize < 1024*1024)
defaultImmSize = 1024*1024;
}
CopyScan::~CopyScan()
{
gMem.DeleteExportSpaces();
}
// This function is called for each address in an object
// once it has been copied to its new location. We copy first
// then scan to update the addresses.
POLYUNSIGNED CopyScan::ScanAddressAt(PolyWord *pt)
{
PolyWord val = *pt;
// Ignore integers.
if (IS_INT(val) || val == PolyWord::FromUnsigned(0))
return 0;
// Ignore pointers to the IO area. They will be relocated
// when we write out the memory
MemSpace *space = gMem.SpaceForAddress(val.AsAddress());
ASSERT(space != 0);
if (space->spaceType == ST_IO)
return 0;
// We may sometimes get addresses that have already been updated
// to point to the new area. e.g. (only?) in the case of constants
// that have been updated in ScanConstantsWithinCode.
if (space->spaceType == ST_EXPORT)
return 0;
// If this is at a lower level than the hierarchy we are saving
// then leave it untouched.
if (space->spaceType == ST_PERMANENT)
{
PermanentMemSpace *pmSpace = (PermanentMemSpace*)space;
if (pmSpace->hierarchy < hierarchy)
return 0;
}
if (val.IsCodePtr())
{
// Find the start of the code segment
PolyObject *oldObject = ObjCodePtrToPtr(val.AsCodePtr());
// Calculate the byte offset of this value within the code object.
POLYUNSIGNED offset = val.AsCodePtr() - (byte*)oldObject;
PolyObject *newObject = ScanObjectAddress(oldObject);
*pt = PolyWord::FromCodePtr((byte*)newObject + offset);
return 0;
}
ASSERT(OBJ_IS_DATAPTR(val));
// Have we already scanned this?
PolyObject *obj = val.AsObjPtr();
if (obj->ContainsForwardingPtr())
{
// Update the address to the new value.
PolyObject *newAddr = obj->GetForwardingPtr();
*pt = newAddr;
return 0; // No need to scan it again.
}
// No, we need to copy it.
ASSERT(space->spaceType == ST_LOCAL || space->spaceType == ST_PERMANENT);
POLYUNSIGNED lengthWord = obj->LengthWord();
POLYUNSIGNED words = OBJ_OBJECT_LENGTH(lengthWord);
PolyObject *newObj = 0;
bool isMutableObj = obj->IsMutable();
bool isNoOverwrite = false;
if (isMutableObj) isNoOverwrite = obj->IsNoOverwriteObject();
// Allocate a new address for the object.
for (unsigned i = 0; i < gMem.neSpaces; i++)
{
PermanentMemSpace *space = gMem.eSpaces[i];
if (isMutableObj == space->isMutable && isNoOverwrite == space->noOverwrite)
{
ASSERT(space->topPointer <= space->top && space->topPointer >= space->bottom);
POLYUNSIGNED spaceLeft = space->top - space->topPointer;
if (spaceLeft > words)
{
newObj = (PolyObject*)(space->topPointer+1);
space->topPointer += words+1;
break;
}
}
}
if (newObj == 0)
{
// Didn't find room in the existing spaces. Create a new space.
POLYUNSIGNED spaceWords;
if (!isMutableObj) spaceWords = defaultImmSize;
else if (isNoOverwrite) spaceWords = defaultNoOverSize;
else spaceWords = defaultMutSize;
if (spaceWords <= words)
spaceWords = words+1; // Make sure there's space for this object.
PermanentMemSpace *space = gMem.NewExportSpace(spaceWords, isMutableObj, isNoOverwrite);
if (space == 0)
{
// Unable to allocate this.
throw MemoryException();
}
newObj = (PolyObject*)(space->topPointer+1);
space->topPointer += words+1;
ASSERT(space->topPointer <= space->top && space->topPointer >= space->bottom);
}
newObj->SetLengthWord(lengthWord); // copy length word
if (OBJ_IS_STACK_OBJECT(lengthWord))
CopyStackFrame ((StackObject *)obj,(StackObject *)newObj);
else
memcpy(newObj, obj, words*sizeof(PolyWord));
obj->SetForwardingPtr(newObj); // Put forwarding pointer in old object.
if (OBJ_IS_CODE_OBJECT(lengthWord))
{
// We don't need to worry about flushing the instruction cache
// since we're not going to execute this code here.
// We do have to update any relative addresses within the code
// to take account of its new position. We have to do that now
// even though ScanAddressesInObject will do it again because this
// is the only point where we have both the old and the new addresses.
machineDependent->ScanConstantsWithinCode(newObj, obj, words, this);
}
*pt = newObj; // Update it to the newly copied object.
return lengthWord; // This new object needs to be scanned.
}
PolyObject *CopyScan::ScanObjectAddress(PolyObject *base)
{
PolyWord val = base;
// Scan this as an address.
POLYUNSIGNED lengthWord = CopyScan::ScanAddressAt(&val);
if (lengthWord)
ScanAddressesInObject(val.AsObjPtr(), lengthWord);
return val.AsObjPtr();
}
#define MAX_EXTENSION 4 // The longest extension we may need to add is ".obj"
// Convert the forwarding pointers in a region back into length words.
// Generally if this object has a forwarding pointer that's
// because we've moved it into the export region. We can,
// though, get multiple levels of forwarding if there is an object
// that has been shifted up by a garbage collection, leaving a forwarding
// pointer and then that object has been moved to the export region.
// We mustn't turn locally forwarded values back into ordinary objects
// because they could contain addresses that are no longer valid.
static POLYUNSIGNED GetObjLength(PolyObject *obj)
{
if (obj->ContainsForwardingPtr())
{
PolyObject *forwardedTo = obj->GetForwardingPtr();
POLYUNSIGNED length = GetObjLength(forwardedTo);
MemSpace *space = gMem.SpaceForAddress(forwardedTo);
if (space->spaceType == ST_EXPORT)
obj->SetLengthWord(length);
return length;
}
else return obj->LengthWord();
}
static void FixForwarding(PolyWord *pt, POLYUNSIGNED space)
{
while (space)
{
pt++;
PolyObject *obj = (PolyObject*)pt;
POLYUNSIGNED length = OBJ_OBJECT_LENGTH(GetObjLength(obj));
pt += length;
space -= length+1;
}
}
class ExportRequest: public MainThreadRequest
{
public:
ExportRequest(Handle root, Exporter *exp): exportRoot(root), exporter(exp) {}
virtual void Perform() { exporter->RunExport(exportRoot->WordP()); }
Handle exportRoot;
Exporter *exporter;
};
static void exporter(TaskData *taskData, Handle args, const char *extension, Exporter *exports)
{
char fileNameBuff[MAXPATHLEN+MAX_EXTENSION];
POLYUNSIGNED length =
Poly_string_to_C(DEREFHANDLE(args)->Get(0), fileNameBuff, MAXPATHLEN);
if (length > MAXPATHLEN)
raise_syscall(taskData, "File name too long", ENAMETOOLONG);
// Does it already have the extension? If not add it on.
if (length < strlen(extension) || strcmp(fileNameBuff + length - strlen(extension), extension) != 0)
strcat(fileNameBuff, extension);
exports->exportFile = fopen(fileNameBuff, "wb");
if (exports->exportFile == NULL)
raise_syscall(taskData, "Cannot open export file", errno);
Handle root = taskData->saveVec.push(args->WordP()->Get(1));
// Request a full GC to reduce the size of fix-ups.
FullGC(taskData);
// Request the main thread to do the export.
ExportRequest request(root, exports);
processes->MakeRootRequest(taskData, &request);
if (exports->errorMessage)
raise_fail(taskData, exports->errorMessage);
}
// This is called by the initial thread to actually do the export.
void Exporter::RunExport(PolyObject *rootFunction)
{
Exporter *exports = this;
// Copy the root and everything reachable from it into the temporary area.
CopyScan copyScan;
PolyObject *copiedRoot = 0;
try {
copiedRoot = copyScan.ScanObjectAddress(rootFunction);
}
catch (MemoryException)
{
// If we ran out of memory.
copiedRoot = 0;
}
// Fix the forwarding pointers.
unsigned j;
for (j = 0; j < gMem.nlSpaces; j++)
{
LocalMemSpace *space = gMem.lSpaces[j];
// Local areas only have objects from the allocation pointer to the top.
FixForwarding(space->pointer, space->top - space->pointer);
}
for (j = 0; j < gMem.npSpaces; j++)
{
MemSpace *space = gMem.pSpaces[j];
// Permanent areas are filled with objects from the bottom.
FixForwarding(space->bottom, space->top - space->bottom);
}
// Reraise the exception after cleaning up the forwarding pointers.
if (copiedRoot == 0)
{
exports->errorMessage = "Insufficient Memory";
return;
}
// Copy the areas into the export object.
exports->memTable = new memoryTableEntry[gMem.neSpaces+1];
exports->ioMemEntry = 0;
// The IO vector. Should we actually create a blank area? This needs to be
// writable by the RTS but not normally by ML.
MemSpace *ioSpace = gMem.IoSpace();
exports->memTable[0].mtAddr = ioSpace->bottom;
exports->memTable[0].mtLength = (char*)ioSpace->top - (char*)ioSpace->bottom;
exports->memTable[0].mtFlags = 0;
exports->memTable[0].mtIndex = 0;
for (unsigned i = 0; i < gMem.neSpaces; i++)
{
memoryTableEntry *entry = &exports->memTable[i+1];
PermanentMemSpace *space = gMem.eSpaces[i];
entry->mtAddr = space->bottom;
entry->mtLength = (space->topPointer-space->bottom)*sizeof(PolyWord);
entry->mtIndex = i+1;
if (space->isMutable)
{
entry->mtFlags = MTF_WRITEABLE;
if (space->noOverwrite) entry->mtFlags |= MTF_NO_OVERWRITE;
}
else
entry->mtFlags = MTF_EXECUTABLE;
}
exports->memTableEntries = gMem.neSpaces+1;
exports->ioSpacing = IO_SPACING;
exports->rootFunction = copiedRoot;
exports->exportStore();
return;
}
// Functions called via the RTS call.
Handle exportNative(TaskData *taskData, Handle args)
{
#ifdef HAVE_PECOFF
// Windows including Cygwin
#ifdef WINDOWS_PC
const char *extension = ".obj"; // Windows
#else
const char *extension = ".o"; // Cygwin
#endif
PECOFFExport exports;
exporter(taskData, args, extension, &exports);
#elif defined(HAVE_ELF_H)
// Most Unix including Linux, FreeBSD and Solaris.
const char *extension = ".o";
ELFExport exports;
exporter(taskData, args, extension, &exports);
#elif defined(HAVE_MACH_O_RELOC_H)
// Mac OS-X
const char *extension = ".o";
MachoExport exports;
exporter(taskData, args, extension, &exports);
#else
raise_exception_string (taskData, EXC_Fail, "Native export not available for this platform");
#endif
return taskData->saveVec.push(TAGGED(0));
}
Handle exportPortable(TaskData *taskData, Handle args)
{
PExport exports;
exporter(taskData, args, ".txt", &exports);
return taskData->saveVec.push(TAGGED(0));
}
// Helper functions for exporting. We need to produce relocation information
// and this code is common to every method.
Exporter::Exporter(): exportFile(NULL), errorMessage(0), memTable(0)
{
}
Exporter::~Exporter()
{
delete[](memTable);
if (exportFile)
fclose(exportFile);
}
void Exporter::relocateValue(PolyWord *pt)
{
PolyWord q = *pt;
if (IS_INT(q) || q == PolyWord::FromUnsigned(0)) {}
else createRelocation(pt);
}
// Check through the areas to see where the address is. It must be
// in one of them.
unsigned Exporter::findArea(void *p)
{
for (unsigned i = 0; i < memTableEntries; i++)
{
if (p > memTable[i].mtAddr &&
p <= (char*)memTable[i].mtAddr + memTable[i].mtLength)
return i;
}
{ ASSERT(0); }
return 0;
}
void Exporter::relocateObject(PolyObject *p)
{
if (p->IsByteObject())
{
}
else if (p->IsCodeObject())
{
POLYUNSIGNED constCount;
PolyWord *cp;
ASSERT(! p->IsMutable() );
p->GetConstSegmentForCode(cp, constCount);
/* Now the constants. */
for (POLYUNSIGNED i = 0; i < constCount; i++) relocateValue(&(cp[i]));
}
else if (p->IsStackObject())
{
StackObject *s = (StackObject*)p;
POLYUNSIGNED length = p->Length();
ASSERT(! p->IsMutable()); // Should have been frozen
/* First the standard registers, space, pc, sp, hr. */
// pc may be TAGGED(0) indicating a retry.
PolyWord pc = PolyWord::FromCodePtr(s->p_pc);
if (pc != TAGGED(0))
s->p_pc = createRelocation(pc, &s->p_pc).AsCodePtr();
PolyWord *stackPtr = s->p_sp; // Save this before we change it.
s->p_sp = createRelocation(PolyWord::FromStackAddr(s->p_sp), &s->p_sp).AsStackAddr();
s->p_hr = createRelocation(PolyWord::FromStackAddr(s->p_hr), &s->p_hr).AsStackAddr();
/* Checked registers. */
PolyWord *stackStart = (PolyWord*)p;
PolyWord *stackEnd = stackStart+length;
for (POLYUNSIGNED i = 0; i < s->p_nreg; i++)
{
PolyWord r = s->p_reg[i];
if (r.AsStackAddr() >= stackStart && r.AsStackAddr() < stackEnd)
createRelocation(&s->p_reg[i]);
/* It seems we can have zeros in the registers, at least on the i386. */
else if (r == PolyWord::FromUnsigned(0)) {}
else relocateValue(&(s->p_reg[i]));
}
/* Now the values on the stack. */
for (PolyWord *q = stackPtr; q < stackEnd; q++)
{
/* A stack may contain a value which is an offset. */
if ((*q).AsStackAddr() >= stackStart && (*q).AsStackAddr() < stackEnd)
createRelocation(q);
else relocateValue(q);
}
}
else /* Ordinary objects, essentially tuples. */
{
POLYUNSIGNED length = p->Length();
for (POLYUNSIGNED i = 0; i < length; i++) relocateValue(p->Offset(i));
}
}
ExportStringTable::ExportStringTable(): strings(0), stringSize(0), stringAvailable(0)
{
}
ExportStringTable::~ExportStringTable()
{
free(strings);
}
// Add a string to the string table, growing it if necessary.
unsigned long ExportStringTable::makeEntry(const char *str)
{
int len = strlen(str);
unsigned long entry = stringSize;
if (stringSize + len + 1 > stringAvailable)
{
stringAvailable = stringAvailable+stringAvailable/2;
if (stringAvailable < stringSize + len + 1)
stringAvailable = stringSize + len + 1 + 500;
strings = (char*)realloc(strings, stringAvailable);
if (strings == 0)
throw MemoryException();
}
strcpy(strings + stringSize, str);
stringSize += len + 1;
return entry;
}
|