source: CLRX/CLRadeonExtender/trunk/amdbin/ROCmBinaries.cpp @ 2537

Last change on this file since 2537 was 2537, checked in by matszpk, 3 years ago

CLRadeonExtender: Add hash section to ROCm binaries. Add routines to calculate symbol's names hash codes and to optimize hash's buckets number.

File size: 9.2 KB
Line 
1/*
2 *  CLRadeonExtender - Unofficial OpenCL Radeon Extensions Library
3 *  Copyright (C) 2014-2016 Mateusz Szpakowski
4 *
5 *  This library is free software; you can redistribute it and/or
6 *  modify it under the terms of the GNU Lesser General Public
7 *  License as published by the Free Software Foundation; either
8 *  version 2.1 of the License, or (at your option) any later version.
9 *
10 *  This library is distributed in the hope that it will be useful,
11 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 *  Lesser General Public License for more details.
14 *
15 *  You should have received a copy of the GNU Lesser General Public
16 *  License along with this library; if not, write to the Free Software
17 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18 */
19
20#include <CLRX/Config.h>
21#include <cassert>
22#include <cstdint>
23#include <algorithm>
24#include <utility>
25#include <CLRX/amdbin/ElfBinaries.h>
26#include <CLRX/utils/Utilities.h>
27#include <CLRX/utils/MemAccess.h>
28#include <CLRX/utils/InputOutput.h>
29#include <CLRX/utils/Containers.h>
30#include <CLRX/amdbin/ROCmBinaries.h>
31
32using namespace CLRX;
33
34/* TODO: add support for various kernel code offset (now only 256 is supported) */
35
36ROCmBinary::ROCmBinary(size_t binaryCodeSize, cxbyte* binaryCode, Flags creationFlags)
37        : ElfBinary64(binaryCodeSize, binaryCode, creationFlags),
38          regionsNum(0), codeSize(0), code(nullptr)
39{
40    cxuint textIndex = SHN_UNDEF;
41    try
42    { textIndex = getSectionIndex(".text"); }
43    catch(const Exception& ex)
44    { } // ignore failed
45    uint64_t codeOffset = 0;
46    if (textIndex!=SHN_UNDEF)
47    {
48        code = getSectionContent(textIndex);
49        const Elf64_Shdr& textShdr = getSectionHeader(textIndex);
50        codeSize = ULEV(textShdr.sh_size);
51        codeOffset = ULEV(textShdr.sh_offset);
52    }
53   
54    regionsNum = 0;
55    const size_t symbolsNum = getSymbolsNum();
56    for (size_t i = 0; i < symbolsNum; i++)
57    {   // count regions number
58        const Elf64_Sym& sym = getSymbol(i);
59        const cxbyte symType = ELF64_ST_TYPE(sym.st_info);
60        const cxbyte bind = ELF64_ST_BIND(sym.st_info);
61        if (sym.st_shndx==textIndex &&
62            (symType==STT_GNU_IFUNC || (bind==STB_GLOBAL && symType==STT_OBJECT)))
63            regionsNum++;
64    }
65    if (code==nullptr && regionsNum!=0)
66        throw Exception("No code if regions number is not zero");
67    regions.reset(new ROCmRegion[regionsNum]);
68    size_t j = 0;
69    typedef std::pair<uint64_t, size_t> RegionOffsetEntry;
70    std::unique_ptr<RegionOffsetEntry[]> symOffsets(new RegionOffsetEntry[regionsNum]);
71   
72    for (size_t i = 0; i < symbolsNum; i++)
73    {
74        const Elf64_Sym& sym = getSymbol(i);
75        if (sym.st_shndx!=textIndex)
76            continue;   // if not in '.text' section
77        const size_t value = ULEV(sym.st_value);
78        if (value < codeOffset)
79            throw Exception("Region offset is too small!");
80        const size_t size = ULEV(sym.st_size);
81       
82        const cxbyte symType = ELF64_ST_TYPE(sym.st_info);
83        const cxbyte bind = ELF64_ST_BIND(sym.st_info);
84        if (symType==STT_GNU_IFUNC || (bind==STB_GLOBAL && symType==STT_OBJECT))
85        {
86            const bool isKernel = (symType==STT_GNU_IFUNC);
87            symOffsets[j] = std::make_pair(value, j);
88            if (isKernel && value+0x100 > codeOffset+codeSize)
89                throw Exception("Kernel offset is too big!");
90            regions[j++] = { getSymbolName(i), size, value, isKernel };
91        }
92    }
93    std::sort(symOffsets.get(), symOffsets.get()+regionsNum,
94            [](const RegionOffsetEntry& a, const RegionOffsetEntry& b)
95            { return a.first < b.first; });
96    // checking distance between regions
97    for (size_t i = 1; i <= regionsNum; i++)
98    {
99        size_t end = (i<regionsNum) ? symOffsets[i].first : codeOffset+codeSize;
100        ROCmRegion& region = regions[symOffsets[i-1].second];
101        if (region.isKernel && symOffsets[i-1].first+0x100 > end)
102            throw Exception("Kernel size is too small!");
103       
104        const size_t regSize = end - symOffsets[i-1].first;
105        if (region.size==0)
106            region.size = regSize;
107        else
108            region.size = std::min(regSize, region.size);
109    }
110   
111    if (hasRegionMap())
112    {   // create region map
113        regionsMap.resize(regionsNum);
114        for (size_t i = 0; i < regionsNum; i++)
115            regionsMap[i] = std::make_pair(regions[i].regionName, i);
116        mapSort(regionsMap.begin(), regionsMap.end());
117    }
118}
119
120const ROCmRegion& ROCmBinary::getRegion(const char* name) const
121{
122    RegionMap::const_iterator it = binaryMapFind(regionsMap.begin(),
123                             regionsMap.end(), name);
124    if (it == regionsMap.end())
125        throw Exception("Can't find region name");
126    return regions[it->second];
127}
128
129bool CLRX::isROCmBinary(size_t binarySize, const cxbyte* binary)
130{
131    if (!isElfBinary(binarySize, binary))
132        return false;
133    if (binary[EI_CLASS] != ELFCLASS64)
134        return false;
135    const Elf64_Ehdr* ehdr = reinterpret_cast<const Elf64_Ehdr*>(binary);
136    if (ULEV(ehdr->e_machine) != 0xe0 || ULEV(ehdr->e_flags)!=0)
137        return false;
138    return true;
139}
140
141/*
142 * ROCm Binary Generator
143 */
144
145ROCmBinGenerator::ROCmBinGenerator() : manageable(false), input(nullptr)
146{ }
147
148ROCmBinGenerator::ROCmBinGenerator(const ROCmInput* rocmInput)
149        : manageable(false), input(rocmInput)
150{ }
151
152ROCmBinGenerator::ROCmBinGenerator(GPUDeviceType deviceType,
153        uint32_t archMinor, uint32_t archStepping, size_t codeSize, const cxbyte* code,
154        const std::vector<ROCmSymbolInput>& symbols)
155{
156    input = new ROCmInput{ deviceType, archMinor, archStepping, symbols, codeSize, code };
157}
158
159ROCmBinGenerator::ROCmBinGenerator(GPUDeviceType deviceType,
160        uint32_t archMinor, uint32_t archStepping, size_t codeSize, const cxbyte* code,
161        std::vector<ROCmSymbolInput>&& symbols)
162{
163    input = new ROCmInput{ deviceType, archMinor, archStepping, std::move(symbols),
164                codeSize, code };
165}
166
167ROCmBinGenerator::~ROCmBinGenerator()
168{
169    if (manageable)
170        delete input;
171}
172
173void ROCmBinGenerator::setInput(const ROCmInput* input)
174{
175    if (manageable)
176        delete input;
177    manageable = false;
178    this->input = input;
179}
180
181void ROCmBinGenerator::generateInternal(std::ostream* osPtr, std::vector<char>* vPtr,
182             Array<cxbyte>* aPtr) const
183{
184    const char* comment = "CLRX ROCmBinGenerator " CLRX_VERSION;
185    uint32_t commentSize = ::strlen(comment);
186    if (input->comment!=nullptr)
187    {   // if comment, store comment section
188        comment = input->comment;
189        commentSize = input->commentSize;
190        if (commentSize==0)
191            commentSize = ::strlen(comment);
192    }
193   
194    ElfBinaryGen64 elfBinGen64;
195    elfBinGen64.addRegion(ElfRegion64::programHeaderTable());
196    elfBinGen64.addRegion(ElfRegion64::dynsymSection());
197    elfBinGen64.addRegion(ElfRegion64::hashSection());
198    elfBinGen64.addRegion(ElfRegion64::dynstrSection());
199    elfBinGen64.addRegion(ElfRegion64(input->codeSize, (const cxbyte*)input->code, 
200              0x1000, ".text", SHT_PROGBITS, SHF_ALLOC|SHF_EXECINSTR, 0, 0, 0, 0,
201              false, 256));
202    elfBinGen64.addRegion(ElfRegion64(0, (const cxbyte*)nullptr, 0x1000, ".dynamic",
203              SHT_DYNAMIC, SHF_ALLOC|SHF_WRITE, 2, 0, 0, 0, false, 8));
204    elfBinGen64.addRegion(ElfRegion64(0, (const cxbyte*)nullptr, 4, ".note",
205              SHT_NOTE, 0));
206    elfBinGen64.addRegion(ElfRegion64(commentSize, (const cxbyte*)comment, 1, ".comment",
207              SHT_PROGBITS, SHF_MERGE|SHF_STRINGS));
208    elfBinGen64.addRegion(ElfRegion64::symtabSection());
209    elfBinGen64.addRegion(ElfRegion64::shstrtabSection());
210    elfBinGen64.addRegion(ElfRegion64::strtabSection());
211    elfBinGen64.addRegion(ElfRegion64::sectionHeaderTable());
212   
213    size_t binarySize = elfBinGen64.countSize();
214    /****
215     * prepare for write binary to output
216     ****/
217    std::unique_ptr<std::ostream> outStreamHolder;
218    std::ostream* os = nullptr;
219    if (aPtr != nullptr)
220    {
221        aPtr->resize(binarySize);
222        outStreamHolder.reset(
223                new ArrayOStream(binarySize, reinterpret_cast<char*>(aPtr->data())));
224        os = outStreamHolder.get();
225    }
226    else if (vPtr != nullptr)
227    {
228        vPtr->resize(binarySize);
229        outStreamHolder.reset(new VectorOStream(*vPtr));
230        os = outStreamHolder.get();
231    }
232    else // from argument
233        os = osPtr;
234   
235    const std::ios::iostate oldExceptions = os->exceptions();
236    try
237    {
238    os->exceptions(std::ios::failbit | std::ios::badbit);
239    /****
240     * write binary to output
241     ****/
242    FastOutputBuffer bos(256, *os);
243    elfBinGen64.generate(bos);
244    assert(bos.getWritten() == binarySize);
245    }
246    catch(...)
247    {
248        os->exceptions(oldExceptions);
249        throw;
250    }
251    os->exceptions(oldExceptions);
252}
253
254void ROCmBinGenerator::generate(Array<cxbyte>& array) const
255{
256    generateInternal(nullptr, nullptr, &array);
257}
258
259void ROCmBinGenerator::generate(std::ostream& os) const
260{
261    generateInternal(&os, nullptr, nullptr);
262}
263
264void ROCmBinGenerator::generate(std::vector<char>& v) const
265{
266    generateInternal(nullptr, &v, nullptr);
267}
Note: See TracBrowser for help on using the repository browser.