summaryrefslogtreecommitdiffstats
path: root/Source/cmXCOFF.cxx
blob: 890636e06fe83f8a991acbca1b2e0e68956adb64 (plain)
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
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
#include "cmXCOFF.h"

#include <algorithm>
#include <cstddef>

#include <cm/memory>

#include "cmsys/FStream.hxx"

#include "cmStringAlgorithms.h"

// Include the XCOFF format information system header.
#ifdef _AIX
#  define __XCOFF32__
#  define __XCOFF64__
#  include <xcoff.h>
#else
#  error "This source may be compiled only on AIX."
#endif

class cmXCOFFInternal
{
public:
  // Construct and take ownership of the file stream object.
  cmXCOFFInternal(cmXCOFF* external, std::unique_ptr<std::iostream> fin,
                  cmXCOFF::Mode mode)
    : External(external)
    , Stream(std::move(fin))
    , Mode(mode)
  {
  }

  // Destruct and delete the file stream object.
  virtual ~cmXCOFFInternal() = default;

  cmXCOFF::Mode GetMode() const { return this->Mode; }

  virtual cm::optional<cm::string_view> GetLibPath() = 0;

  virtual bool SetLibPath(cm::string_view libPath) = 0;
  virtual bool RemoveLibPath() = 0;

protected:
  // Data common to all ELF class implementations.

  // The external cmXCOFF object.
  cmXCOFF* External;

  // The stream from which to read.
  std::unique_ptr<std::iostream> Stream;

  cmXCOFF::Mode Mode;

  // Helper methods for subclasses.
  void SetErrorMessage(const char* msg) { this->External->ErrorMessage = msg; }
};

namespace {

struct XCOFF32
{
  typedef struct filehdr filehdr;
  typedef struct aouthdr aouthdr;
  typedef struct scnhdr scnhdr;
  typedef struct ldhdr ldhdr;
  static const std::size_t aouthdr_size = _AOUTHSZ_EXEC;
};
const unsigned char xcoff32_magic[] = { 0x01, 0xDF };

struct XCOFF64
{
  typedef struct filehdr_64 filehdr;
  typedef struct aouthdr_64 aouthdr;
  typedef struct scnhdr_64 scnhdr;
  typedef struct ldhdr_64 ldhdr;
  static const std::size_t aouthdr_size = _AOUTHSZ_EXEC_64;
};
const unsigned char xcoff64_magic[] = { 0x01, 0xF7 };

template <typename XCOFF>
class Impl : public cmXCOFFInternal
{
  static_assert(sizeof(typename XCOFF::aouthdr) == XCOFF::aouthdr_size,
                "aouthdr structure size matches _AOUTHSZ_EXEC macro");

  typename XCOFF::filehdr FileHeader;
  typename XCOFF::aouthdr AuxHeader;
  typename XCOFF::scnhdr LoaderSectionHeader;
  typename XCOFF::ldhdr LoaderHeader;

  std::streamoff LoaderImportFileTablePos = 0;
  std::vector<char> LoaderImportFileTable;

  bool Read(typename XCOFF::filehdr& x)
  {
    // FIXME: Add byte swapping if needed.
    return static_cast<bool>(
      this->Stream->read(reinterpret_cast<char*>(&x), sizeof(x)));
  }

  bool Read(typename XCOFF::aouthdr& x)
  {
    // FIXME: Add byte swapping if needed.
    return static_cast<bool>(
      this->Stream->read(reinterpret_cast<char*>(&x), sizeof(x)));
  }

  bool Read(typename XCOFF::scnhdr& x)
  {
    // FIXME: Add byte swapping if needed.
    return static_cast<bool>(
      this->Stream->read(reinterpret_cast<char*>(&x), sizeof(x)));
  }

  bool Read(typename XCOFF::ldhdr& x)
  {
    // FIXME: Add byte swapping if needed.
    return static_cast<bool>(
      this->Stream->read(reinterpret_cast<char*>(&x), sizeof(x)));
  }

  bool WriteLoaderImportFileTableLength(decltype(XCOFF::ldhdr::l_istlen) x)
  {
    // FIXME: Add byte swapping if needed.
    return static_cast<bool>(
      this->Stream->write(reinterpret_cast<char const*>(&x), sizeof(x)));
  }

public:
  Impl(cmXCOFF* external, std::unique_ptr<std::iostream> fin,
       cmXCOFF::Mode mode);

  cm::optional<cm::string_view> GetLibPath() override;
  bool SetLibPath(cm::string_view libPath) override;
  bool RemoveLibPath() override;
};

template <typename XCOFF>
Impl<XCOFF>::Impl(cmXCOFF* external, std::unique_ptr<std::iostream> fin,
                  cmXCOFF::Mode mode)
  : cmXCOFFInternal(external, std::move(fin), mode)
{
  if (!this->Read(this->FileHeader)) {
    this->SetErrorMessage("Failed to read XCOFF file header.");
    return;
  }
  if (this->FileHeader.f_opthdr != XCOFF::aouthdr_size) {
    this->SetErrorMessage("XCOFF auxiliary header missing.");
    return;
  }
  if (!this->Read(this->AuxHeader)) {
    this->SetErrorMessage("Failed to read XCOFF auxiliary header.");
    return;
  }
  if (this->AuxHeader.o_snloader == 0) {
    this->SetErrorMessage("XCOFF loader section missing.");
    return;
  }
  if (!this->Stream->seekg((this->AuxHeader.o_snloader - 1) *
                             sizeof(typename XCOFF::scnhdr),
                           std::ios::cur)) {
    this->SetErrorMessage("Failed to seek to XCOFF loader section header.");
    return;
  }
  if (!this->Read(this->LoaderSectionHeader)) {
    this->SetErrorMessage("Failed to read XCOFF loader section header.");
    return;
  }
  if ((this->LoaderSectionHeader.s_flags & STYP_LOADER) == 0) {
    this->SetErrorMessage("XCOFF loader section header missing STYP_LOADER.");
    return;
  }
  if (!this->Stream->seekg(this->LoaderSectionHeader.s_scnptr,
                           std::ios::beg)) {
    this->SetErrorMessage("Failed to seek to XCOFF loader header.");
    return;
  }
  if (!this->Read(this->LoaderHeader)) {
    this->SetErrorMessage("Failed to read XCOFF loader header.");
    return;
  }
  this->LoaderImportFileTablePos =
    this->LoaderSectionHeader.s_scnptr + this->LoaderHeader.l_impoff;
  if (!this->Stream->seekg(this->LoaderImportFileTablePos)) {
    this->SetErrorMessage(
      "Failed to seek to XCOFF loader import file id table.");
    return;
  }
  this->LoaderImportFileTable.resize(this->LoaderHeader.l_istlen);
  if (!this->Stream->read(this->LoaderImportFileTable.data(),
                          this->LoaderImportFileTable.size())) {
    this->SetErrorMessage("Failed to read XCOFF loader import file id table.");
    return;
  }
}

template <typename XCOFF>
cm::optional<cm::string_view> Impl<XCOFF>::GetLibPath()
{
  cm::optional<cm::string_view> result;
  auto end = std::find(this->LoaderImportFileTable.begin(),
                       this->LoaderImportFileTable.end(), '\0');
  if (end != this->LoaderImportFileTable.end()) {
    result = cm::string_view(this->LoaderImportFileTable.data(),
                             end - this->LoaderImportFileTable.begin());
  }
  return result;
}

template <typename XCOFF>
bool Impl<XCOFF>::SetLibPath(cm::string_view libPath)
{
  // The new LIBPATH must end in the standard AIX LIBPATH.
#define CM_AIX_LIBPATH "/usr/lib:/lib"
  std::string libPathBuf;
  if (libPath != CM_AIX_LIBPATH &&
      !cmHasLiteralSuffix(libPath, ":" CM_AIX_LIBPATH)) {
    libPathBuf = std::string(libPath);
    if (!libPathBuf.empty() && libPathBuf.back() != ':') {
      libPathBuf.push_back(':');
    }
    libPathBuf += CM_AIX_LIBPATH;
    libPath = libPathBuf;
  }
#undef CM_AIX_LIBPATH

  auto oldEnd = std::find(this->LoaderImportFileTable.begin(),
                          this->LoaderImportFileTable.end(), '\0');
  if (oldEnd == this->LoaderImportFileTable.end()) {
    this->SetErrorMessage("XCOFF loader import file id table is invalid.");
    return false;
  }
  if ((this->LoaderImportFileTable.begin() + libPath.size()) > oldEnd) {
    this->SetErrorMessage("XCOFF loader import file id table is too small.");
    return false;
  }

  {
    std::vector<char> ift;
    ift.reserve(this->LoaderImportFileTable.size());
    // Start with the new LIBPATH.
    ift.insert(ift.end(), libPath.begin(), libPath.end());
    // Add the rest of the original table.
    ift.insert(ift.end(), oldEnd, this->LoaderImportFileTable.end());
    // If the new table is shorter, zero out the leftover space.
    ift.resize(this->LoaderImportFileTable.size(), 0);
    this->LoaderHeader.l_istlen =
      static_cast<decltype(XCOFF::ldhdr::l_istlen)>(ift.size());
    this->LoaderImportFileTable = std::move(ift);
  }

  if (!this->Stream->seekp(this->LoaderSectionHeader.s_scnptr +
                             offsetof(typename XCOFF::ldhdr, l_istlen),
                           std::ios::beg)) {
    this->SetErrorMessage(
      "Failed to seek to XCOFF loader header import file id table length.");
    return false;
  }
  if (!this->WriteLoaderImportFileTableLength(this->LoaderHeader.l_istlen)) {
    this->SetErrorMessage(
      "Failed to write XCOFF loader header import file id table length.");
    return false;
  }
  if (!this->Stream->seekp(this->LoaderImportFileTablePos, std::ios::beg)) {
    this->SetErrorMessage(
      "Failed to seek to XCOFF loader import file id table.");
    return false;
  }
  if (!this->Stream->write(this->LoaderImportFileTable.data(),
                           this->LoaderImportFileTable.size())) {
    this->SetErrorMessage(
      "Failed to write XCOFF loader import file id table.");
    return false;
  }

  return true;
}

template <typename XCOFF>
bool Impl<XCOFF>::RemoveLibPath()
{
  return this->SetLibPath({});
}
}

//============================================================================
// External class implementation.

cmXCOFF::cmXCOFF(const char* fname, Mode mode)
{
  // Try to open the file.
  std::ios::openmode fmode = std::ios::in | std::ios::binary;
  if (mode == Mode::ReadWrite) {
    fmode |= std::ios::out;
  }
  auto f = cm::make_unique<cmsys::fstream>(fname, fmode);

  // Quit now if the file could not be opened.
  if (!f || !*f) {
    this->ErrorMessage = "Error opening input file.";
    return;
  }

  // Read the XCOFF magic number.
  unsigned char magic[2];
  if (!f->read(reinterpret_cast<char*>(magic), sizeof(magic))) {
    this->ErrorMessage = "Error reading XCOFF magic number.";
    return;
  }
  if (!f->seekg(0)) {
    this->ErrorMessage = "Error seeking to beginning of file.";
    return;
  }

  // Check the XCOFF type.
  if (magic[0] == xcoff32_magic[0] && magic[1] == xcoff32_magic[1]) {
    this->Internal = cm::make_unique<Impl<XCOFF32>>(this, std::move(f), mode);
  } else if (magic[0] == xcoff64_magic[0] && magic[1] == xcoff64_magic[1]) {
    this->Internal = cm::make_unique<Impl<XCOFF64>>(this, std::move(f), mode);
  } else {
    this->ErrorMessage = "File is not a XCOFF32 or XCOFF64 binary.";
  }
}

cmXCOFF::~cmXCOFF() = default;

cmXCOFF::cmXCOFF(cmXCOFF&&) = default;
cmXCOFF& cmXCOFF::operator=(cmXCOFF&&) = default;

bool cmXCOFF::Valid() const
{
  return this->Internal && this->ErrorMessage.empty();
}

cm::optional<cm::string_view> cmXCOFF::GetLibPath() const
{
  cm::optional<cm::string_view> result;
  if (this->Valid()) {
    result = this->Internal->GetLibPath();
  }
  return result;
}

bool cmXCOFF::SetLibPath(cm::string_view libPath)
{
  return this->Valid() && this->Internal->GetMode() == Mode::ReadWrite &&
    this->Internal->SetLibPath(libPath);
}

bool cmXCOFF::RemoveLibPath()
{
  return this->Valid() && this->Internal->GetMode() == Mode::ReadWrite &&
    this->Internal->RemoveLibPath();
}