#include <stdint.h>
#include <math.h>
#include <unistd.h>
#include <dlfcn.h>
#include <mach/machine.h>
#include <vector>
#include "ld.hpp"
#include "huge.h"
namespace ld {
namespace passes {
namespace huge {
class NullAtom
{
public:
bool operator()(const ld::Atom* atom) const {
return (atom == NULL);
}
};
void doPass(const Options& opts, ld::Internal& state)
{
const bool log = false;
if ( opts.outputKind() == Options::kObjectFile )
return;
if ( opts.architecture() != CPU_TYPE_X86_64 )
return;
state.usingHugeSections = false;
uint64_t address = 0;
for (std::vector<ld::Internal::FinalSection*>::iterator sit=state.sections.begin(); sit != state.sections.end(); ++sit) {
ld::Internal::FinalSection* sect = *sit;
if ( sect->type() == ld::Section::typePageZero )
continue;
if ( sect->type() == ld::Section::typeStack )
continue;
for (std::vector<const ld::Atom*>::iterator ait=sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
const ld::Atom* atom = *ait;
if ( (address > 0x7FFFFFFFLL) && !sect->isSectionHidden() ) {
state.usingHugeSections = true;
if (log) fprintf(stderr, "atom: %s is >2GB (0x%09llX), so enabling huge mode\n", atom->name(), address);
break;
}
address += atom->size();
}
if ( state.usingHugeSections )
break;
}
if ( !state.usingHugeSections )
return;
ld::Internal::FinalSection* hugeSection = state.getFinalSection(ld::Section("__DATA", "__huge", ld::Section::typeZeroFill));
for (std::vector<ld::Internal::FinalSection*>::iterator sit=state.sections.begin(); sit != state.sections.end(); ++sit) {
ld::Internal::FinalSection* sect = *sit;
if ( sect == hugeSection )
continue;
if ( sect->type() == ld::Section::typeZeroFill ) {
bool movedSome = false;
for (std::vector<const ld::Atom*>::iterator ait=sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
const ld::Atom* atom = *ait;
if ( atom->size() > 1024*1024 ) {
hugeSection->atoms.push_back(atom);
if (log) fprintf(stderr, "moved to __huge: %s, size=%llu\n", atom->name(), atom->size());
*ait = NULL; movedSome = true;
}
}
if ( movedSome )
sect->atoms.erase(std::remove_if(sect->atoms.begin(), sect->atoms.end(), NullAtom()), sect->atoms.end());
}
}
}
} } }