1 /*-------------------------------------------------------------------------
5 * Copyright (c) 2015 Google Inc.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
21 * \brief Program binary registry.
22 *//*--------------------------------------------------------------------*/
24 #include "vkBinaryRegistry.hpp"
25 #include "tcuResource.hpp"
26 #include "tcuFormatUtil.hpp"
27 #include "deFilePath.hpp"
28 #include "deStringUtil.hpp"
29 #include "deDirectoryIterator.hpp"
42 namespace BinaryRegistryDetail
51 string getProgramFileName (deUint32 index)
53 return de::toString(tcu::toHex(index)) + ".spv";
56 string getProgramPath (const std::string& dirName, deUint32 index)
58 return de::FilePath::join(dirName, getProgramFileName(index)).getPath();
61 bool isHexChr (char c)
63 return de::inRange(c, '0', '9') || de::inRange(c, 'a', 'f') || de::inRange(c, 'A', 'F');
66 bool isProgramFileName (const std::string& name)
68 // 0x + 00000000 + .spv
69 if (name.length() != (2 + 8 + 4))
80 for (size_t ndx = 2; ndx < 10; ++ndx)
82 if (!isHexChr(name[ndx]))
89 deUint32 getProgramIndexFromName (const std::string& name)
91 DE_ASSERT(isProgramFileName(name));
94 std::stringstream str;
96 str << std::hex << name.substr(2,10);
99 DE_ASSERT(getProgramFileName(index) == name);
104 string getIndexPath (const std::string& dirName)
106 return de::FilePath::join(dirName, "index.bin").getPath();
109 void writeBinary (const ProgramBinary& binary, const std::string& dstPath)
111 const de::FilePath filePath(dstPath);
113 if (!de::FilePath(filePath.getDirName()).exists())
114 de::createDirectoryAndParents(filePath.getDirName().c_str());
117 std::ofstream out (dstPath.c_str(), std::ios_base::binary);
119 if (!out.is_open() || !out.good())
120 throw tcu::Exception("Failed to open " + dstPath);
122 out.write((const char*)binary.getBinary(), binary.getSize());
127 void writeBinary (const std::string& dstDir, deUint32 index, const ProgramBinary& binary)
129 writeBinary(binary, getProgramPath(dstDir, index));
132 ProgramBinary* readBinary (const std::string& srcPath)
134 std::ifstream in (srcPath.c_str(), std::ios::binary | std::ios::ate);
135 const size_t size = (size_t)in.tellg();
137 if (!in.is_open() || !in.good())
138 throw tcu::Exception("Failed to open " + srcPath);
141 throw tcu::Exception("Malformed binary, size = 0");
143 in.seekg(0, std::ios::beg);
146 std::vector<deUint8> bytes (size);
148 in.read((char*)&bytes[0], size);
149 DE_ASSERT(bytes[0] != 0);
151 return new ProgramBinary(vk::PROGRAM_FORMAT_SPIRV, bytes.size(), &bytes[0]);
155 deUint32 binaryHash (const ProgramBinary* binary)
157 return deMemoryHash(binary->getBinary(), binary->getSize());
160 deBool binaryEqual (const ProgramBinary* a, const ProgramBinary* b)
162 if (a->getSize() == b->getSize())
163 return deMemoryEqual(a->getBinary(), b->getBinary(), a->getSize());
168 std::vector<deUint32> getSearchPath (const ProgramIdentifier& id)
170 const std::string combinedStr = id.testCasePath + '#' + id.programName;
171 const size_t strLen = combinedStr.size();
172 const size_t numWords = strLen/4 + 1; // Must always end up with at least one 0 byte
173 vector<deUint32> words (numWords, 0u);
175 deMemcpy(&words[0], combinedStr.c_str(), strLen);
180 const deUint32* findBinaryIndex (BinaryIndexAccess* index, const ProgramIdentifier& id)
182 const vector<deUint32> words = getSearchPath(id);
188 const BinaryIndexNode& curNode = (*index)[nodeNdx];
190 if (curNode.word == words[wordNdx])
192 if (wordNdx+1 < words.size())
194 TCU_CHECK_INTERNAL((size_t)curNode.index < index->size());
196 nodeNdx = curNode.index;
199 else if (wordNdx+1 == words.size())
200 return &curNode.index;
204 else if (curNode.word != 0)
208 // Index should always be null-terminated
209 TCU_CHECK_INTERNAL(nodeNdx < index->size());
218 //! Sparse index node used for final binary index construction
219 struct SparseIndexNode
223 std::vector<SparseIndexNode*> children;
225 SparseIndexNode (deUint32 word_, deUint32 index_)
230 SparseIndexNode (void)
235 ~SparseIndexNode (void)
237 for (size_t ndx = 0; ndx < children.size(); ndx++)
238 delete children[ndx];
242 #if defined(DE_DEBUG)
243 bool isNullByteTerminated (deUint32 word)
246 deMemcpy(bytes, &word, sizeof(word));
247 return bytes[3] == 0;
251 void addToSparseIndex (SparseIndexNode* group, const deUint32* words, size_t numWords, deUint32 index)
253 const deUint32 curWord = words[0];
254 SparseIndexNode* child = DE_NULL;
256 for (size_t childNdx = 0; childNdx < group->children.size(); childNdx++)
258 if (group->children[childNdx]->word == curWord)
260 child = group->children[childNdx];
265 DE_ASSERT(numWords > 1 || !child);
269 group->children.reserve(group->children.size()+1);
270 group->children.push_back(new SparseIndexNode(curWord, numWords == 1 ? index : 0));
272 child = group->children.back();
276 addToSparseIndex(child, words+1, numWords-1, index);
278 DE_ASSERT(isNullByteTerminated(curWord));
281 // Prepares sparse index for finalization. Ensures that child with word = 0 is moved
282 // to the end, or one is added if there is no such child already.
283 void normalizeSparseIndex (SparseIndexNode* group)
285 int zeroChildPos = -1;
287 for (size_t childNdx = 0; childNdx < group->children.size(); childNdx++)
289 normalizeSparseIndex(group->children[childNdx]);
291 if (group->children[childNdx]->word == 0)
293 DE_ASSERT(zeroChildPos < 0);
294 zeroChildPos = (int)childNdx;
298 if (zeroChildPos >= 0)
300 // Move child with word = 0 to last
301 while (zeroChildPos != (int)group->children.size()-1)
303 std::swap(group->children[zeroChildPos], group->children[zeroChildPos+1]);
307 else if (!group->children.empty())
309 group->children.reserve(group->children.size()+1);
310 group->children.push_back(new SparseIndexNode(0, 0));
314 deUint32 getIndexSize (const SparseIndexNode* group)
316 size_t numNodes = group->children.size();
318 for (size_t childNdx = 0; childNdx < group->children.size(); childNdx++)
319 numNodes += getIndexSize(group->children[childNdx]);
321 DE_ASSERT(numNodes <= std::numeric_limits<deUint32>::max());
323 return (deUint32)numNodes;
326 deUint32 addAndCountNodes (BinaryIndexNode* index, deUint32 baseOffset, const SparseIndexNode* group)
328 const deUint32 numLocalNodes = (deUint32)group->children.size();
329 deUint32 curOffset = numLocalNodes;
331 // Must be normalized prior to construction of final index
332 DE_ASSERT(group->children.empty() || group->children.back()->word == 0);
334 for (size_t childNdx = 0; childNdx < numLocalNodes; childNdx++)
336 const SparseIndexNode* child = group->children[childNdx];
337 const deUint32 subtreeSize = addAndCountNodes(index+curOffset, baseOffset+curOffset, child);
339 index[childNdx].word = child->word;
341 if (subtreeSize == 0)
342 index[childNdx].index = child->index;
345 DE_ASSERT(child->index == 0);
346 index[childNdx].index = baseOffset+curOffset;
349 curOffset += subtreeSize;
355 void buildFinalIndex (std::vector<BinaryIndexNode>* dst, const SparseIndexNode* root)
357 const deUint32 indexSize = getIndexSize(root);
361 dst->resize(indexSize);
362 addAndCountNodes(&(*dst)[0], 0, root);
366 // Generate empty index
369 (*dst)[0].index = 0u;
373 void buildBinaryIndex (std::vector<BinaryIndexNode>* dst, size_t numEntries, const ProgramIdentifierIndex* entries)
375 de::UniquePtr<SparseIndexNode> sparseIndex (new SparseIndexNode());
377 for (size_t ndx = 0; ndx < numEntries; ndx++)
379 const std::vector<deUint32> searchPath = getSearchPath(entries[ndx].id);
380 addToSparseIndex(sparseIndex.get(), &searchPath[0], searchPath.size(), entries[ndx].index);
383 normalizeSparseIndex(sparseIndex.get());
384 buildFinalIndex(dst, sparseIndex.get());
391 DE_IMPLEMENT_POOL_HASH(BinaryIndexHashImpl, const ProgramBinary*, deUint32, binaryHash, binaryEqual);
393 BinaryIndexHash::BinaryIndexHash (void)
394 : m_hash(BinaryIndexHashImpl_create(m_memPool.getRawPool()))
397 throw std::bad_alloc();
400 BinaryIndexHash::~BinaryIndexHash (void)
404 deUint32* BinaryIndexHash::find (const ProgramBinary* binary) const
406 return BinaryIndexHashImpl_find(m_hash, binary);
409 void BinaryIndexHash::insert (const ProgramBinary* binary, deUint32 index)
411 if (!BinaryIndexHashImpl_insert(m_hash, binary, index))
412 throw std::bad_alloc();
415 // BinaryRegistryWriter
417 BinaryRegistryWriter::BinaryRegistryWriter (const std::string& dstPath)
420 if (de::FilePath(dstPath).exists())
421 initFromPath(dstPath);
424 BinaryRegistryWriter::~BinaryRegistryWriter (void)
426 for (BinaryVector::const_iterator binaryIter = m_binaries.begin();
427 binaryIter != m_binaries.end();
429 delete binaryIter->binary;
432 void BinaryRegistryWriter::initFromPath (const std::string& srcPath)
434 DE_ASSERT(m_binaries.empty());
436 for (de::DirectoryIterator iter(srcPath); iter.hasItem(); iter.next())
438 const de::FilePath path = iter.getItem();
439 const std::string baseName = path.getBaseName();
441 if (isProgramFileName(baseName))
443 const deUint32 index = getProgramIndexFromName(baseName);
444 const de::UniquePtr<ProgramBinary> binary (readBinary(path.getPath()));
446 addBinary(index, *binary);
447 // \note referenceCount is left to 0 and will only be incremented
448 // if binary is reused (added via addProgram()).
453 void BinaryRegistryWriter::addProgram (const ProgramIdentifier& id, const ProgramBinary& binary)
455 const deUint32* const indexPtr = findBinary(binary);
456 deUint32 index = indexPtr ? *indexPtr : ~0u;
460 index = getNextSlot();
461 addBinary(index, binary);
464 m_binaries[index].referenceCount += 1;
465 m_binaryIndices.push_back(ProgramIdentifierIndex(id, index));
468 deUint32* BinaryRegistryWriter::findBinary (const ProgramBinary& binary) const
470 return m_binaryHash.find(&binary);
473 deUint32 BinaryRegistryWriter::getNextSlot (void) const
475 const deUint32 index = (deUint32)m_binaries.size();
477 if ((size_t)index != m_binaries.size())
478 throw std::bad_alloc(); // Overflow
483 void BinaryRegistryWriter::addBinary (deUint32 index, const ProgramBinary& binary)
485 DE_ASSERT(binary.getFormat() == vk::PROGRAM_FORMAT_SPIRV);
486 DE_ASSERT(findBinary(binary) == DE_NULL);
488 ProgramBinary* const binaryClone = new ProgramBinary(binary);
492 if (m_binaries.size() < (size_t)index+1)
493 m_binaries.resize(index+1);
495 DE_ASSERT(!m_binaries[index].binary);
496 DE_ASSERT(m_binaries[index].referenceCount == 0);
498 m_binaries[index].binary = binaryClone;
499 // \note referenceCount is not incremented here
507 m_binaryHash.insert(binaryClone, index);
510 void BinaryRegistryWriter::write (void) const
512 writeToPath(m_dstPath);
515 void BinaryRegistryWriter::writeToPath (const std::string& dstPath) const
517 if (!de::FilePath(dstPath).exists())
518 de::createDirectoryAndParents(dstPath.c_str());
520 DE_ASSERT(m_binaries.size() <= 0xffffffffu);
521 for (size_t binaryNdx = 0; binaryNdx < m_binaries.size(); ++binaryNdx)
523 const BinarySlot& slot = m_binaries[binaryNdx];
525 if (slot.referenceCount > 0)
527 DE_ASSERT(slot.binary);
528 writeBinary(dstPath, (deUint32)binaryNdx, *slot.binary);
532 // Delete stale binary if such exists
533 const std::string progPath = getProgramPath(dstPath, (deUint32)binaryNdx);
535 if (de::FilePath(progPath).exists())
536 deDeleteFile(progPath.c_str());
543 const de::FilePath indexPath = getIndexPath(dstPath);
544 std::vector<BinaryIndexNode> index;
546 buildBinaryIndex(&index, m_binaryIndices.size(), !m_binaryIndices.empty() ? &m_binaryIndices[0] : DE_NULL);
548 // Even in empty index there is always terminating node for the root group
549 DE_ASSERT(!index.empty());
551 if (!de::FilePath(indexPath.getDirName()).exists())
552 de::createDirectoryAndParents(indexPath.getDirName().c_str());
555 std::ofstream indexOut(indexPath.getPath(), std::ios_base::binary);
557 if (!indexOut.is_open() || !indexOut.good())
558 throw tcu::InternalError(string("Failed to open program binary index file ") + indexPath.getPath());
560 indexOut.write((const char*)&index[0], index.size()*sizeof(BinaryIndexNode));
565 // BinaryRegistryReader
567 BinaryRegistryReader::BinaryRegistryReader (const tcu::Archive& archive, const std::string& srcPath)
568 : m_archive (archive)
569 , m_srcPath (srcPath)
573 BinaryRegistryReader::~BinaryRegistryReader (void)
577 ProgramBinary* BinaryRegistryReader::loadProgram (const ProgramIdentifier& id) const
583 m_binaryIndex = BinaryIndexPtr(new BinaryIndexAccess(de::MovePtr<tcu::Resource>(m_archive.getResource(getIndexPath(m_srcPath).c_str()))));
585 catch (const tcu::ResourceError& e)
587 throw ProgramNotFoundException(id, string("Failed to open binary index (") + e.what() + ")");
592 const deUint32* indexPos = findBinaryIndex(m_binaryIndex.get(), id);
596 const string fullPath = getProgramPath(m_srcPath, *indexPos);
600 de::UniquePtr<tcu::Resource> progRes (m_archive.getResource(fullPath.c_str()));
601 const int progSize = progRes->getSize();
602 vector<deUint8> bytes (progSize);
604 TCU_CHECK_INTERNAL(!bytes.empty());
606 progRes->read(&bytes[0], progSize);
608 return new ProgramBinary(vk::PROGRAM_FORMAT_SPIRV, bytes.size(), &bytes[0]);
610 catch (const tcu::ResourceError& e)
612 throw ProgramNotFoundException(id, e.what());
616 throw ProgramNotFoundException(id, "Program not found in index");
620 } // BinaryRegistryDetail