#include "gold.h"
#ifdef HAVE_ZLIB_H
#include <zlib.h>
#endif
#include "parameters.h"
#include "options.h"
#include "compressed_output.h"
namespace gold
{
#ifdef HAVE_ZLIB_H
static bool
zlib_compress(const unsigned char* uncompressed_data,
unsigned long uncompressed_size,
unsigned char** compressed_data,
unsigned long* compressed_size)
{
const int header_size = 12;
*compressed_size = uncompressed_size + uncompressed_size / 1000 + 128;
*compressed_data = new unsigned char[*compressed_size + header_size];
int compress_level;
if (parameters->options().optimize() >= 1)
compress_level = 9;
else
compress_level = 1;
int rc = compress2(reinterpret_cast<Bytef*>(*compressed_data) + header_size,
compressed_size,
reinterpret_cast<const Bytef*>(uncompressed_data),
uncompressed_size,
compress_level);
if (rc == Z_OK)
{
memcpy(*compressed_data, "ZLIB", 4);
elfcpp::Swap_unaligned<64, true>::writeval(*compressed_data + 4,
uncompressed_size);
*compressed_size += header_size;
return true;
}
else
{
delete[] *compressed_data;
*compressed_data = NULL;
return false;
}
}
#else
static bool
zlib_compress(const unsigned char*, unsigned long,
unsigned char**, unsigned long*)
{
return false;
}
#endif
void
Output_compressed_section::set_final_data_size()
{
off_t uncompressed_size = this->postprocessing_buffer_size();
unsigned long compressed_size;
unsigned char* uncompressed_data = this->postprocessing_buffer();
this->write_to_postprocessing_buffer();
bool success = false;
if (strcmp(this->options_->compress_debug_sections(), "zlib") == 0)
success = zlib_compress(uncompressed_data, uncompressed_size,
&this->data_, &compressed_size);
if (success)
{
this->new_section_name_ = std::string(".z") + (this->name() + 1);
this->set_name(this->new_section_name_.c_str());
this->set_data_size(compressed_size);
}
else
{
gold_warning(_("not compressing section data: zlib error"));
gold_assert(this->data_ == NULL);
this->set_data_size(uncompressed_size);
}
}
void
Output_compressed_section::do_write(Output_file* of)
{
off_t offset = this->offset();
off_t data_size = this->data_size();
unsigned char* view = of->get_output_view(offset, data_size);
if (this->data_ == NULL)
memcpy(view, this->postprocessing_buffer(), data_size);
else
memcpy(view, this->data_, data_size);
of->write_output_view(offset, data_size, view);
}
}