aboutsummaryrefslogtreecommitdiff
path: root/llvm/lib/ObjectYAML/GOFFEmitter.cpp
blob: 345904407e1d24d6e571c28f84d5a1fd66d4094d (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
//===- yaml2goff - Convert YAML to a GOFF object file ---------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// The GOFF component of yaml2obj.
///
//===----------------------------------------------------------------------===//

#include "llvm/ADT/IndexedMap.h"
#include "llvm/ObjectYAML/ObjectYAML.h"
#include "llvm/ObjectYAML/yaml2obj.h"
#include "llvm/Support/ConvertEBCDIC.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

namespace {

// Common flag values on records.
enum {
  // Flag: This record is continued.
  Rec_Continued = 1,

  // Flag: This record is a continuation.
  Rec_Continuation = 1 << (8 - 6 - 1),
};

template <typename ValueType> struct BinaryBeImpl {
  ValueType Value;
  BinaryBeImpl(ValueType V) : Value(V) {}
};

template <typename ValueType>
raw_ostream &operator<<(raw_ostream &OS, const BinaryBeImpl<ValueType> &BBE) {
  char Buffer[sizeof(BBE.Value)];
  support::endian::write<ValueType, llvm::endianness::big, support::unaligned>(
      Buffer, BBE.Value);
  OS.write(Buffer, sizeof(BBE.Value));
  return OS;
}

template <typename ValueType> BinaryBeImpl<ValueType> binaryBe(ValueType V) {
  return BinaryBeImpl<ValueType>(V);
}

struct ZerosImpl {
  size_t NumBytes;
};

raw_ostream &operator<<(raw_ostream &OS, const ZerosImpl &Z) {
  OS.write_zeros(Z.NumBytes);
  return OS;
}

ZerosImpl zeros(const size_t NumBytes) { return ZerosImpl{NumBytes}; }

// The GOFFOstream is responsible to write the data into the fixed physical
// records of the format. A user of this class announces the start of a new
// logical record and the size of its payload. While writing the payload, the
// physical records are created for the data. Possible fill bytes at the end of
// a physical record are written automatically.
class GOFFOstream : public raw_ostream {
public:
  explicit GOFFOstream(raw_ostream &OS)
      : OS(OS), LogicalRecords(0), RemainingSize(0), NewLogicalRecord(false) {
    SetBufferSize(GOFF::PayloadLength);
  }

  ~GOFFOstream() { finalize(); }

  void makeNewRecord(GOFF::RecordType Type, size_t Size) {
    fillRecord();
    CurrentType = Type;
    RemainingSize = Size;
    if (size_t Gap = (RemainingSize % GOFF::PayloadLength))
      RemainingSize += GOFF::PayloadLength - Gap;
    NewLogicalRecord = true;
    ++LogicalRecords;
  }

  void finalize() { fillRecord(); }

  uint32_t logicalRecords() { return LogicalRecords; }

private:
  // The underlying raw_ostream.
  raw_ostream &OS;

  // The number of logical records emitted so far.
  uint32_t LogicalRecords;

  // The remaining size of this logical record, including fill bytes.
  size_t RemainingSize;

  // The type of the current (logical) record.
  GOFF::RecordType CurrentType;

  // Signals start of new record.
  bool NewLogicalRecord;

  // Return the number of bytes left to write until next physical record.
  // Please note that we maintain the total number of bytes left, not the
  // written size.
  size_t bytesToNextPhysicalRecord() {
    size_t Bytes = RemainingSize % GOFF::PayloadLength;
    return Bytes ? Bytes : GOFF::PayloadLength;
  }

  // Write the record prefix of a physical record, using the current record
  // type.
  static void writeRecordPrefix(raw_ostream &OS, GOFF::RecordType Type,
                                size_t RemainingSize,
                                uint8_t Flags = Rec_Continuation) {
    uint8_t TypeAndFlags = Flags | (Type << 4);
    if (RemainingSize > GOFF::RecordLength)
      TypeAndFlags |= Rec_Continued;
    OS << binaryBe(static_cast<unsigned char>(GOFF::PTVPrefix))
       << binaryBe(static_cast<unsigned char>(TypeAndFlags))
       << binaryBe(static_cast<unsigned char>(0));
  }

  // Fill the last physical record of a logical record with zero bytes.
  void fillRecord() {
    assert((GetNumBytesInBuffer() <= RemainingSize) &&
           "More bytes in buffer than expected");
    size_t Remains = RemainingSize - GetNumBytesInBuffer();
    if (Remains) {
      assert((Remains < GOFF::RecordLength) &&
             "Attempting to fill more than one physical record");
      raw_ostream::write_zeros(Remains);
    }
    flush();
    assert(RemainingSize == 0 && "Not fully flushed");
    assert(GetNumBytesInBuffer() == 0 && "Buffer not fully empty");
  }

  // See raw_ostream::write_impl.
  void write_impl(const char *Ptr, size_t Size) override {
    assert((RemainingSize >= Size) && "Attempt to write too much data");
    assert(RemainingSize && "Logical record overflow");
    if (!(RemainingSize % GOFF::PayloadLength)) {
      writeRecordPrefix(OS, CurrentType, RemainingSize,
                        NewLogicalRecord ? 0 : Rec_Continuation);
      NewLogicalRecord = false;
    }
    assert(!NewLogicalRecord &&
           "New logical record not on physical record boundary");

    size_t Idx = 0;
    while (Size > 0) {
      size_t BytesToWrite = bytesToNextPhysicalRecord();
      if (BytesToWrite > Size)
        BytesToWrite = Size;
      OS.write(Ptr + Idx, BytesToWrite);
      Idx += BytesToWrite;
      Size -= BytesToWrite;
      RemainingSize -= BytesToWrite;
      if (Size) {
        writeRecordPrefix(OS, CurrentType, RemainingSize);
      }
    }
  }

  // Return the current position within the stream, not counting the bytes
  // currently in the buffer.
  uint64_t current_pos() const override { return OS.tell(); }
};

class GOFFState {
  void writeHeader(GOFFYAML::FileHeader &FileHdr);
  void writeEnd();

  void reportError(const Twine &Msg) {
    ErrHandler(Msg);
    HasError = true;
  }

  GOFFState(raw_ostream &OS, GOFFYAML::Object &Doc,
            yaml::ErrorHandler ErrHandler)
      : GW(OS), Doc(Doc), ErrHandler(ErrHandler), HasError(false) {}

  ~GOFFState() { GW.finalize(); }

  bool writeObject();

public:
  static bool writeGOFF(raw_ostream &OS, GOFFYAML::Object &Doc,
                        yaml::ErrorHandler ErrHandler);

private:
  GOFFOstream GW;
  GOFFYAML::Object &Doc;
  yaml::ErrorHandler ErrHandler;
  bool HasError;
};

void GOFFState::writeHeader(GOFFYAML::FileHeader &FileHdr) {
  SmallString<16> CCSIDName;
  if (std::error_code EC =
          ConverterEBCDIC::convertToEBCDIC(FileHdr.CharacterSetName, CCSIDName))
    reportError("Conversion error on " + FileHdr.CharacterSetName);
  if (CCSIDName.size() > 16) {
    reportError("CharacterSetName too long");
    CCSIDName.resize(16);
  }
  SmallString<16> LangProd;
  if (std::error_code EC = ConverterEBCDIC::convertToEBCDIC(
          FileHdr.LanguageProductIdentifier, LangProd))
    reportError("Conversion error on " + FileHdr.LanguageProductIdentifier);
  if (LangProd.size() > 16) {
    reportError("LanguageProductIdentifier too long");
    LangProd.resize(16);
  }

  GW.makeNewRecord(GOFF::RT_HDR, GOFF::PayloadLength);
  GW << binaryBe(FileHdr.TargetEnvironment)     // TargetEnvironment
     << binaryBe(FileHdr.TargetOperatingSystem) // TargetOperatingSystem
     << zeros(2)                                // Reserved
     << binaryBe(FileHdr.CCSID)                 // CCSID
     << CCSIDName                               // CharacterSetName
     << zeros(16 - CCSIDName.size())            // Fill bytes
     << LangProd                                // LanguageProductIdentifier
     << zeros(16 - LangProd.size())             // Fill bytes
     << binaryBe(FileHdr.ArchitectureLevel);    // ArchitectureLevel
  // The module propties are optional. Figure out if we need to write them.
  uint16_t ModPropLen = 0;
  if (FileHdr.TargetSoftwareEnvironment)
    ModPropLen = 3;
  else if (FileHdr.InternalCCSID)
    ModPropLen = 2;
  if (ModPropLen) {
    GW << binaryBe(ModPropLen) << zeros(6);
    if (ModPropLen >= 2)
      GW << binaryBe(FileHdr.InternalCCSID ? *FileHdr.InternalCCSID : 0);
    if (ModPropLen >= 3)
      GW << binaryBe(FileHdr.TargetSoftwareEnvironment
                         ? *FileHdr.TargetSoftwareEnvironment
                         : 0);
  }
}

void GOFFState::writeEnd() {
  GW.makeNewRecord(GOFF::RT_END, GOFF::PayloadLength);
  GW << binaryBe(uint8_t(0)) // No entry point
     << binaryBe(uint8_t(0)) // No AMODE
     << zeros(3)             // Reserved
     << binaryBe(GW.logicalRecords());
  // No entry point yet. Automatically fill remaining space with zero bytes.
  GW.finalize();
}

bool GOFFState::writeObject() {
  writeHeader(Doc.Header);
  if (HasError)
    return false;
  writeEnd();
  return true;
}

bool GOFFState::writeGOFF(raw_ostream &OS, GOFFYAML::Object &Doc,
                          yaml::ErrorHandler ErrHandler) {
  GOFFState State(OS, Doc, ErrHandler);
  return State.writeObject();
}
} // namespace

namespace llvm {
namespace yaml {

bool yaml2goff(llvm::GOFFYAML::Object &Doc, raw_ostream &Out,
               ErrorHandler ErrHandler) {
  return GOFFState::writeGOFF(Out, Doc, ErrHandler);
}

} // namespace yaml
} // namespace llvm